1 #include "TtyProcess.h"
2 
3 #include <QDir>
4 #include <QProcessEnvironment>
5 #include <QTimer>
6 
7 #define DEBUG 1
8 
TTYProcess(QObject * parent)9 TTYProcess::TTYProcess(QObject *parent) : QObject(parent){
10   childProc = 0;
11   sn = 0;
12   ttyfd = 0;
13   starting = true;
14   fixReply = -1;
15 }
16 
~TTYProcess()17 TTYProcess::~TTYProcess(){
18   closeTTY(); //make sure everything is closed properly
19 }
20 
21 // === PUBLIC ===
startTTY(QString prog,QStringList args,QString workdir)22 bool TTYProcess::startTTY(QString prog, QStringList args, QString workdir){
23   if(workdir=="~"){ workdir = QDir::homePath(); }
24   QDir::setCurrent(workdir);
25   QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
26   setenv("TERM","vt220-color",1);//"vt102-color",1); //vt100: VT100 emulation support (QTerminal sets "xterm" here)
27 
28   //setenv("TERMINFO","/etc/termcap",0);
29   unsetenv("WINDOWID");
30   //unsetenv("TERMCAP");
31   //setenv("TERMCAP","/etc/termcap",1);
32   //setenv("TERMCAP","vt220-color",1);
33   //setenv("TERMCAP","vt102|vt220-color|dec vt102:' :do=^J:co#80:li#24:cl=50\E[;H\E[2J: :le=^H:bs:cm=5\E[%i%d;%dH:nd=2\E[C:up=2\E[A: :ce=3\E[K:cd=50\E[J:so=2\E[7m:se=2\E[m:us=2\E[4m:ue=2\E[m: :md=2\E[1m:mr=2\E[7m:mb=2\E[5m:me=2\E[m:is=\E[1;24r\E[24;1H: :rs=\E>\E[?3l\E[?4l\E[?5l\E[?7h\E[?8h:ks=\E[?1h\E=:ke=\E[?1l\E>: :ku=\EOA:kd=\EOB:kr=\EOC:kl=\EOD:kb=^H: :ho=\E[H:k1=\EOP:k2=\EOQ:k3=\EOR:k4=\EOS:pt:sr=5\EM:vt#3: :sc=\E7:rc=\E8:cs=\E[%i%d;%dr:vs=\E[?7l:ve=\E[?7h: :mi:al=\E[L:dc=\E[P:dl=\E[M:ei=\E[4l:im=\E[4h:' vi $*",1);
34   /*setenv("TERMCAP","'vt220-color' :do=2\E[B:co#80:li#24:cl=50\E[H\E[J:sf=2*\ED:\
35 	:le=^H:bs:am:cm=5\E[%i%d;%dH:nd=2\E[C:up=2\E[A:\
36 	:ce=3\E[K:cd=50\E[J:so=2\E[7m:se=2\E[m:us=2\E[4m:ue=2\E[m:\
37 	:md=2\E[1m:mr=2\E[7m:mb=2\E[5m:me=2\E[m:\
38 	:is=\E>\E[?1;3;4;5l\E[?7;8h\E[1;24r\E[24;1H:\
39 	:if=/usr/share/tabset/vt100:nw=2\EE:ho=\E[H:\
40 	:as=2\E(0:ae=2\E(B:\
41 	:ac=``aaffggjjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||:\
42 	:rs=\E>\E[?1;3;4;5l\E[?7;8h:ks=\E[?1h\E=:ke=\E[?1l\E>:\
43 	:ku=\EOA:kd=\EOB:kr=\EOC:kl=\EOD:kb=\177:\
44 	:k0=\EOy:k1=\EOP:k2=\EOQ:k3=\EOR:k4=\EOS:k5=\EOt:\
45 	:k6=\EOu:k7=\EOv:k8=\EOl:k9=\EOw:k;=\EOx:@8=\EOM:\
46 	:K1=\EOq:K2=\EOr:K3=\EOs:K4=\EOp:K5=\EOn:pt:sr=2*\EM:xn:\
47 	:sc=2\E7:rc=2\E8:cs=5\E[%i%d;%dr:UP=2\E[%dA:DO=2\E[%dB:RI=2\E[%dC:\
48 	:LE=2\E[%dD:ct=2\E[3g:st=2\EH:ta=^I:ms:bl=^G:cr=^M:eo:it#8:\
49 	:RA=\E[?7l:SA=\E[?7h:po=\E[5i:pf=\E[4i:",1); //see /etc/termcap as well */
50   QStringList filter = env.keys().filter("XTERM");
51   for(int i=0; i<filter.length(); i++){ unsetenv(filter[i].toLocal8Bit().data()); }
52   //if(env.contains("TERM")){ unsetenv("TERM"); }
53   //else if(env.contains
54   //Turn the program/arguments into C-compatible arrays
55   char cprog[prog.length()]; strcpy(cprog, prog.toLocal8Bit().data());
56   char *cargs[args.length()+2];
57   QByteArray nullarray;
58   for(int i=0; i<args.length()+2; i++){
59     // First arg needs to be the program
60     if ( i == 0 ) {
61       cargs[i] = new char[ prog.toLocal8Bit().size()+1];
62       strcpy( cargs[i], prog.toLocal8Bit().data() );
63     } else if(i<args.length()){
64       cargs[i] = new char[ args[i].toLocal8Bit().size()+1];
65       strcpy( cargs[i], args[i].toLocal8Bit().data() );
66     }else{
67       cargs[i] = NULL;
68     }
69   }
70   if(DEBUG){ qDebug() << "PTY Start:" << prog; }
71   //Launch the process attached to a new PTY
72   int FD = 0;
73   pid_t tmp = LaunchProcess(FD, cprog, cargs);
74   if(DEBUG){
75     qDebug() << " - PID:" << tmp;
76     qDebug() << " - FD:" << FD;
77   }
78   if(tmp<0){ return false; } //error
79   else{
80     childProc = tmp;
81     //Load the file for close notifications
82       //TO-DO
83     //Watch the socket for activity
84     sn= new QSocketNotifier(FD, QSocketNotifier::Read);
85 	sn->setEnabled(true);
86 	connect(sn, SIGNAL(activated(int)), this, SLOT(checkStatus(int)) );
87     ttyfd = FD;
88    if(DEBUG){ qDebug() << " - PTY:" << ptsname(FD); }
89     starting = true;
90     return true;
91   }
92 }
93 
closeTTY()94 void TTYProcess::closeTTY(){
95   int junk;
96   if(0==waitpid(childProc, &junk, WNOHANG)){
97     kill(childProc, SIGKILL);
98   }
99   if(ttyfd!=0 && sn!=0){
100     sn->setEnabled(false);
101     ::close(ttyfd);
102     ttyfd = 0;
103     emit processClosed();
104   }
105 }
106 
writeTTY(QByteArray output)107 void TTYProcess::writeTTY(QByteArray output){
108   //qDebug() << "Write:" << output;
109   static QList<QByteArray> knownFixes;
110   if(knownFixes.isEmpty()){ knownFixes << "\x1b[C" << "\x1b[D" << "\b" << "\x7F" << "\x08"; }//<<"\x1b[H"<<"\x1b[F"; }
111   fixReply = knownFixes.indexOf(output);
112   ::write(ttyfd, output.data(), output.size());
113 }
114 
readTTY()115 QByteArray TTYProcess::readTTY(){
116   QByteArray BA;
117   //qDebug() << "Read TTY";
118   if(sn==0){ return BA; } //not setup yet
119   char buffer[64];
120   ssize_t rtot = read(sn->socket(),&buffer,64);
121   //buffer[rtot]='\0';
122   BA = QByteArray(buffer, rtot);
123   //qDebug() << " - Got Data:" << BA;
124   if(!fragBA.isEmpty()){
125     //Have a leftover fragment, include this too
126     BA = BA.prepend(fragBA);
127     fragBA.clear();
128   }
129   bool bad = true;
130   BA = CleanANSI(BA, bad);
131   if(bad){
132     //incomplete fragent - read some more first
133     fragBA = BA;
134     return readTTY();
135   }else{
136     if(DEBUG){ qDebug() << "Read Data:" << BA; }
137     //BUG BYPASS - 12/7/16
138     //If the PTY gets input fairly soon after starting, the PTY will re-print the initial line(s)
139     /*if(starting && !BA.contains("\n") ){
140       //qDebug() << "Starting phase 1:" << BA;
141        writeTTY("tset\n"); //Terminal Setup utility (uses the TERM env variable)
142       BA.clear();
143     }else if(starting){
144       //qDebug() << "Starting phase 2:" << BA;
145       BA.remove(0, BA.indexOf("\n")+1);
146       starting = false;
147     }*/
148     //Apply known fixes for replies to particular inputs (mostly related to cursor position *within* the current line)
149     // This appears to be primarily from the concept that the cursor position is always at the end of the line (old VT limitation?)
150     //  so almost all these fixes are for cursor positioning within the current line
151     if(fixReply >= 0){
152       if(DEBUG){ qDebug() << "Fix Reply:" <<fixReply <<  BA; }
153       switch(fixReply){
154 	case 0: //Right arrow ("\x1b[C") - PTY reply re-prints the next character rather than moving the cursor
155           if(BA.length()>0){
156             BA.remove(0,1);
157             BA.prepend("\x1b[C"); //just move the cursor - don't re-print that 1 character
158           }
159 	  break;
160 	case 1: //Left arrow ("\x1b[D") - PTY erases the previous character instead of moving the cursor
161           if(BA.startsWith("\b")){
162             BA.remove(0,1);
163             BA.prepend("\x1b[D"); //just move the cursor - don't send the "back" character (\b)
164           }
165 	  break;
166 	case 2: //Backspace or delete - PTY works fine if on the end of the line, but when in the middle of a line it will backpace a number of times after clearing (same as left arrow issue)
167         case 3:
168 	case 4:
169           if(BA.contains("\x1b[K")){
170 	    while(BA.indexOf("\x1b[K") < BA.lastIndexOf("\b") ){
171               BA.replace( BA.lastIndexOf("\b"), 1, "\x1b[D"); //just move the cursor left - don't send the "back" character (\b)
172             }
173           }
174 	  break;
175 	case 5: //Home Key
176           BA = "\x1b[H";
177           break;
178 	case 6: //End Key
179           BA = "\x1b[F";
180           break;
181       }
182       fixReply = -1; //done with the fix - resume normal operations
183       if(DEBUG){ qDebug() << " - Fixed:" << BA; }
184     }
185     return BA;
186   }
187 }
188 
setTerminalSize(QSize chars,QSize pixels)189 void TTYProcess::setTerminalSize(QSize chars, QSize pixels){
190   if(ttyfd==0 || chars.isNull() || chars.width()<2 || chars.height()<2 ){ return; }
191   struct winsize c_sz;
192     c_sz.ws_row = chars.height();
193     c_sz.ws_col = chars.width();
194     c_sz.ws_xpixel = pixels.width();
195     c_sz.ws_ypixel = pixels.height();
196   if( ioctl(ttyfd, TIOCGWINSZ, &ws) ){
197     qDebug() << "Error settings terminal size:" << chars << pixels;
198   }else{
199 
200     //qDebug() <<"Set Terminal Size:" << pixels << chars;
201   }
202 }
203 
isOpen()204 bool TTYProcess::isOpen(){
205   return (ttyfd!=0);
206 }
207 
CleanANSI(QByteArray raw,bool & incomplete)208 QByteArray TTYProcess::CleanANSI(QByteArray raw, bool &incomplete){
209   incomplete = true;
210   //qDebug() << "Clean ANSI Data:" << raw;
211   //IN_LINE TERMINAL COLOR CODES (ANSI Escape Codes) "\x1B[<colorcode>m"
212   //  - Just remove them for now
213 
214   //Special XTERM encoding (legacy support)
215   int index = raw.indexOf("\x1B]");
216   while(index>=0){
217     //The end character of this sequence is the Bell command ("\x07")
218     int end = raw.indexOf("\x07");
219     if(end<0){ return raw; } //incomplete raw array
220     raw = raw.remove(index, end-index+1);
221     index = raw.indexOf("\x1B]");
222   }
223 
224   // GENERIC ANSI CODES ((Make sure the output is not cut off in the middle of a code)
225   index = raw.indexOf("\x1B");
226   while(index>=0){
227     //CURSOR MOVEMENT
228     int end = 0;
229     for(int i=1; i<raw.size() && end==0; i++){
230       if(raw.size() < index+i){ return raw; }//cut off - go back for more data
231       //qDebug() << "Check Char:" << raw.at(index+i);
232       if( QChar(raw.at(index+i)).isLetter() ){
233         end = i; //found the end of the control code
234       }
235     }
236     index = raw.indexOf("\x1B",index+1); //now find the next one
237   }
238 
239   // SYSTEM BELL
240   index = raw.indexOf("\x07");
241   while(index>=0){
242     //qDebug() << "Remove Bell:" << index;
243     raw = raw.remove(index,1);
244     index = raw.indexOf("\x07");
245   }
246   //VT220(?) print character code (cut out the code, leave the character)
247   index=raw.indexOf("\x1b[@");
248   while(index>=0){
249     raw = raw.remove(index,3);
250     index = raw.indexOf("\x1b[@");
251   }
252 
253   //VT102 Identify request
254   index = raw.indexOf("\x1b[Z");
255   while(index>=0){
256     raw = raw.remove(index,3);
257     index = raw.indexOf("\x1b[Z");
258     //Also send the proper reply to this identify request right away
259     writeTTY("\x1b[/Z");
260   }
261  //Terminal Status request
262   index = raw.indexOf("\x1b[5n");
263   while(index>=0){
264     raw = raw.remove(index,4);
265     index = raw.indexOf("\x1b[5n");
266     //Also send the proper reply to this identify request right away
267     writeTTY("\x1b[c"); //everything ok
268    }
269   //Terminal Identify request
270   index = raw.indexOf("\x1b[c");
271   while(index>=0){
272     raw = raw.remove(index,3);
273     index = raw.indexOf("\x1b[c");
274     //Also send the proper reply to this identify request right away
275     writeTTY("\x1b[1c"); //VT220 reply code
276   }
277   //Terminal Identify request (xterm/termcap?)
278   /*index = raw.indexOf("\x1b[P");
279   while(index>=0){
280     raw = raw.remove(index,3);
281     index = raw.indexOf("\x1b[P");
282     //Also send the proper reply to this identify request right away
283     qDebug() << " - Got XTERM/TERMCAP identify request ([P)";
284     writeTTY("\x1b[/Z");
285   }*/
286 
287   incomplete = false;
288   return raw;
289 }
290 
291 // === PRIVATE ===
LaunchProcess(int & fd,char * prog,char ** child_args)292 pid_t TTYProcess::LaunchProcess(int& fd, char *prog, char **child_args){
293   //Returns: -1 for errors, positive value (file descriptor) for the master side of the TTY to watch
294   //First open/setup a new pseudo-terminal file/device on the system (master side)
295   //fd = posix_openpt(O_RDWR | O_NOCTTY); //open read/write
296   pid_t PID = forkpty( &fd, 0, 0, 0);
297   if(PID==0){
298     //Child process
299     int rc = execvp(prog, child_args);
300     //::close(fds); //no need to keep original file descriptor open any more
301     exit(rc);
302   }else{
303     //Master process
304     return PID;
305   }
306   /*if(fd<0){ return -1; } //could not create pseudo-terminal
307   int rc = grantpt(fd); //set permissions
308   if(rc!=0){ return -1; }
309   rc = unlockpt(fd); //unlock file (ready for use)
310   //rc = fchown(fd, getuid(), getgid());
311   setupTtyFd(fd);
312   if(rc!=0){ return -1; }
313   //Now fork, return the Master device and setup the child
314   pid_t PID = fork();
315   if(PID==0){
316     //SLAVE/child
317     int fds = ::open(ptsname(fd), O_RDWR | O_NOCTTY); //open slave side read/write
318     rc = fchown(fds, getuid(), getgid());
319     ::close(fd); //close the master side from the slave thread
320 
321     //Adjust the slave side mode to SANE
322     setupTtyFd(fds);
323     //Change the controlling terminal in child thread to the slave PTY
324     ::close(0); //close current terminal standard input
325     ::close(1); //close current terminal standard output
326     ::close(2); //close current terminal standard error
327     dup(fds); // Set slave PTY as standard input (0);
328     dup(fds); // Set slave PTY as standard output (1);
329     dup(fds); // Set slave PTY as standard error (2);
330 
331     setsid();  //Make current process new session leader (so we can set controlling terminal)
332     ioctl(0,TIOCSCTTY, 1); //Set the controlling terminal to the slave PTY
333 
334     //Execute the designated program
335     //rc = execvp("tset", NULL);
336     rc = execvp(prog, child_args);
337     ::close(fds); //no need to keep original file descriptor open any more
338     exit(rc);
339   }*/
340   //MASTER thread (or error)
341   return PID;
342 }
343 
setupTtyFd(int fd)344 void TTYProcess::setupTtyFd(int fd){
345   struct termios TSET;
346     tcgetattr(fd, &TSET); //read the current settings
347     cfmakesane(&TSET); //set the SANE mode on the settings ( RAW: cfmakeraw(&TSET); )
348     //Set Input Modes
349     //TSET.c_iflag |= IGNPAR; //ignore parity errors
350     //TSET.c_iflag &= ~(IGNBRK | PARMRK | ISTRIP | ICRNL | IXON | IXANY | IXOFF); //ignore special characters
351     //TSET.c_iflag &= IUTF8; //enable UTF-8 support
352     //Set Local Modes
353     TSET.c_lflag &= (ECHO | ECHONL | ECHOKE); //Echo inputs (normal, newline, and KILL character line break)
354     //TSET.c_lflag &= ~ICANON ;  //non-canonical mode (individual inputs - not a line-at-a-time)
355     //Set Control Modes
356     //TSET.c_cflag |= CLOCAL; //Local Terminal Connection (non-modem)
357     //TSET.c_lflag &= ~IEXTEN;
358     //TSET.c_cflag &= ~(CSIZE | PARENB);
359     //TSET.c_cflag |= CS8;
360     //tt.c_oflag &= ~OPOST; // disable special output processing
361     //Set Output Modes
362     //TSET.c_oflag |= OPOST;
363     //TSET.c_oflag |= OXTABS;
364     TSET.c_cc[VTIME] = 0; // timeout
365     //Now apply the settings
366     tcsetattr(fd, TCSANOW, &TSET); //apply the changed settings
367 }
368 
369 // === PRIVATE SLOTS ===
checkStatus(int sock)370 void TTYProcess::checkStatus(int sock){
371   //This is run when the socket gets activated
372   if(sock!=ttyfd){
373 
374   }
375   //Make sure the child PID is still active
376   int junk;
377   if(0!=waitpid(childProc, &junk, WNOHANG)){
378     this->closeTTY(); //clean up everything else
379   }else{
380     emit readyRead();
381   }
382 }
383