5 import array,cgi,fcntl,glob,mimetypes,optparse,os,pty,random,re,signal,select,sys,threading,time,termios,struct,pwd
7 os.chdir(os.path.normpath(os.path.dirname(__file__)))
8 # Optional: Add QWeb in sys path
9 sys.path[0:0]=glob.glob('../../python')
14 def __init__(self,width=80,height=24):
24 "\x08": self.esc_0x08,
25 "\x09": self.esc_0x09,
26 "\x0a": self.esc_0x0a,
27 "\x0b": self.esc_0x0a,
28 "\x0c": self.esc_0x0a,
29 "\x0d": self.esc_0x0d,
38 "\x1b[c": self.esc_da,
39 "\x1b[0c": self.esc_da,
41 "\x1b7": self.esc_save,
42 "\x1b8": self.esc_restore,
55 for k,v in self.esc_seq.items():
57 self.esc_seq[k]=self.esc_ignore
60 r'\[\??([0-9;]*)([@ABCDEFGHJKLMPXacdefghlmnqrstu`])' : self.csi_dispatch,
61 r'\]([^\x07]+)\x07' : self.esc_ignore,
65 self.esc_re.append((re.compile('\x1b'+k),v))
66 # define csi sequences
68 '@': (self.csi_at,[1]),
69 '`': (self.csi_G,[1]),
70 'J': (self.csi_J,[0]),
71 'K': (self.csi_K,[0]),
73 for i in [i[4] for i in dir(self) if i.startswith('csi_') and len(i)==5]:
74 if not self.csi_seq.has_key(i):
75 self.csi_seq[i]=(getattr(self,'csi_'+i),[1])
76 # Init 0-256 to latin1 and html translation table
87 if i==0x0a or (i>32 and i<127) or i>160:
94 self.scr=array.array('i',[0x000700]*(self.width*self.height))
104 def peek(self,y1,x1,y2,x2):
105 return self.scr[self.width*y1+x1:self.width*y2+x2]
106 def poke(self,y,x,s):
108 self.scr[pos:pos+len(s)]=s
109 def zero(self,y1,x1,y2,x2):
110 w=self.width*(y2-y1)+x2-x1+1
111 z=array.array('i',[0x000700]*w)
112 self.scr[self.width*y1+x1:self.width*y2+x2+1]=z
113 def scroll_up(self,y1,y2):
114 self.poke(y1,0,self.peek(y1+1,0,y2,self.width))
115 self.zero(y2,0,y2,self.width-1)
116 def scroll_down(self,y1,y2):
117 self.poke(y1+1,0,self.peek(y1,0,y2-1,self.width))
118 self.zero(y1,0,y1,self.width-1)
119 def scroll_right(self,y,x):
120 self.poke(y,x+1,self.peek(y,x,y,self.width))
122 def cursor_down(self):
123 if self.cy>=self.st and self.cy<=self.sb:
125 q,r=divmod(self.cy+1,self.sb+1)
127 self.scroll_up(self.st,self.sb)
131 def cursor_right(self):
132 q,r=divmod(self.cx+1,self.width)
141 self.scr[(self.cy*self.width)+self.cx]=self.sgr|ord(c)
143 def esc_0x08(self,s):
144 self.cx=max(0,self.cx-1)
145 def esc_0x09(self,s):
148 self.cx=(q*8)%self.width
149 def esc_0x0a(self,s):
151 def esc_0x0d(self,s):
154 def esc_save(self,s):
157 def esc_restore(self,s):
162 self.outbuf="\x1b[?6c"
164 self.cy=max(self.st,self.cy-1)
166 self.scroll_down(self.st,self.sb)
167 def esc_ignore(self,*s):
169 # print "term:ignore: %s"%repr(s)
170 def csi_dispatch(self,seq,mo):
174 f=self.csi_seq.get(c,None)
177 l=[min(int(i),1024) for i in s.split(';') if len(i)<4]
184 # print 'csi ignore',c,l
186 for i in range(l[0]):
187 self.scroll_right(self.cy,self.cx)
189 self.cy=max(self.st,self.cy-l[0])
191 self.cy=min(self.sb,self.cy+l[0])
193 self.cx=min(self.width-1,self.cx+l[0])
196 self.cx=max(0,self.cx-l[0])
207 self.cx=min(self.width,l[0])-1
210 self.cx=min(self.width,l[1])-1
211 self.cy=min(self.height,l[0])-1
215 self.zero(self.cy,self.cx,self.height-1,self.width-1)
217 self.zero(0,0,self.cy,self.cx)
219 self.zero(0,0,self.height-1,self.width-1)
222 self.zero(self.cy,self.cx,self.cy,self.width-1)
224 self.zero(self.cy,0,self.cy,self.cx)
226 self.zero(self.cy,0,self.cy,self.width-1)
228 for i in range(l[0]):
230 self.scroll_down(self.cy,self.sb)
232 if self.cy>=self.st and self.cy<=self.sb:
233 for i in range(l[0]):
234 self.scroll_up(self.cy,self.sb)
236 w,cx,cy=self.width,self.cx,self.cy
237 end=self.peek(cy,cx,cy,w)
239 self.poke(cy,cx,end[l[0]:])
241 self.zero(self.cy,self.cx,self.cy,self.cx+l[0])
245 #'\x1b[?0c' 0-8 cursor size
248 self.cy=min(self.height,l[0])-1
263 if i==0 or i==39 or i==49 or i==27:
266 self.sgr=(self.sgr|0x000800)
269 elif i>=30 and i<=37:
271 self.sgr=(self.sgr&0xff08ff)|(c<<8)
272 elif i>=40 and i<=47:
274 self.sgr=(self.sgr&0x00ffff)|(c<<16)
276 # print "CSI sgr ignore",l,i
277 # print 'sgr: %r %x'%(l,self.sgr)
279 if len(l)<2: l=[0,self.height]
280 self.st=min(self.height-1,l[0]-1)
281 self.sb=min(self.height-1,l[1]-1)
282 self.sb=max(self.st,self.sb)
292 elif e in self.esc_seq:
296 for r,f in self.esc_re:
302 # if self.buf=='': print "ESC %r\n"%e
305 if len(self.buf) or (i in self.esc_seq):
321 def dumplatin1(self):
322 return self.dump().translate(self.trl1)
323 def dumphtml(self,color=1):
328 span_bg,span_fg=-1,-1
330 q,c=divmod(self.scr[i],256)
335 if i==self.cy*w+self.cx:
337 if (bg!=span_bg or fg!=span_fg or i==h*w-1):
339 r+='<span class="f%d b%d">%s</span>'%(span_fg,span_bg,cgi.escape(span.translate(self.trhtml)))
341 span_bg,span_fg=bg,fg
345 r='<?xml version="1.0" encoding="ISO-8859-1"?><pre class="term">%s</pre>'%r
346 if self.last_html==r:
347 return '<?xml version="1.0"?><idem></idem>'
355 for i in range(self.height):
356 r+="|%s|\n"%d[self.width*i:self.width*(i+1)]
359 class SynchronizedMethod:
360 def __init__(self,lock,orig):
363 def __call__(self,*l):
370 def __init__(self,cmd=None):
371 signal.signal(signal.SIGCHLD, signal.SIG_IGN)
374 self.lock=threading.RLock()
375 self.thread=threading.Thread(target=self.loop)
377 # synchronize methods
378 for name in ['create','fds','proc_read','proc_write','dump','die','run']:
379 orig=getattr(self,name)
380 setattr(self,name,SynchronizedMethod(self.lock,orig))
382 def create(self,w=80,h=25):
386 fdl=[int(i) for i in os.listdir('/proc/self/fd')]
389 for i in [i for i in fdl if i>2]:
395 cmd=['/bin/sh','-c',self.cmd]
399 sys.stdout.write("Login: ")
400 login=sys.stdin.readline().strip()
401 if re.match('^[0-9A-Za-z-_. ]+$',login):
403 cmd+=['-oPreferredAuthentications=keyboard-interactive,password']
404 cmd+=['-oNoHostAuthenticationForLocalhost=yes']
405 cmd+=['-oLogLevel=FATAL']
406 cmd+=['-F/dev/null','-l',login,'localhost']
410 env["COLUMNS"]=str(w)
413 env["PATH"]=os.environ['PATH']
414 os.execvpe(cmd[0],cmd,env)
416 fcntl.fcntl(fd, fcntl.F_SETFL, os.O_NONBLOCK)
417 # python bug http://python.org/sf/1112949 on amd64
418 fcntl.ioctl(fd, struct.unpack('i',struct.pack('I',termios.TIOCSWINSZ))[0], struct.pack("HHHH",h,w,0,0))
419 self.proc[fd]={'pid':pid,'term':Terminal(w,h),'buf':'','time':time.time()}
426 return self.proc.keys()
427 def proc_kill(self,fd):
429 self.proc[fd]['time']=0
431 for i in self.proc.keys():
432 t0=self.proc[i]['time']
436 os.kill(self.proc[i]['pid'],signal.SIGTERM)
437 except (IOError,OSError):
440 def proc_read(self,fd):
442 t=self.proc[fd]['term']
443 t.write(os.read(fd,65536))
447 self.proc[fd]['time']=time.time()
448 except (KeyError,IOError,OSError):
450 def proc_write(self,fd,s):
453 except (IOError,OSError):
455 def dump(self,fd,color=1):
457 return self.proc[fd]['term'].dumphtml(color)
463 i,o,e=select.select(fds, [], [], 1.0)
468 for i in self.proc.keys():
471 os.kill(self.proc[i]['pid'],signal.SIGTERM)
472 except (IOError,OSError):
476 def __init__(self,cmd=None,index_file='ajaxterm.html'):
478 for i in ['css','html','js']:
479 for j in glob.glob('*.%s'%i):
480 self.files[j]=file(j).read()
481 self.files['index']=file(index_file).read()
482 self.mime = mimetypes.types_map.copy()
483 self.mime['.html']= 'text/html; charset=UTF-8'
484 self.multi = Multiplex(cmd)
486 def __call__(self, environ, start_response):
487 req = qweb.QWebRequest(environ, start_response,session=None)
488 if req.PATH_INFO.endswith('/u'):
492 w=req.REQUEST.int("w")
493 h=req.REQUEST.int("h")
494 if s in self.session:
497 if not (w>2 and w<256 and h>2 and h<100):
499 term=self.session[s]=self.multi.create(w,h)
501 self.multi.proc_write(term,k)
503 dump=self.multi.dump(term,c)
504 req.response_headers['Content-Type']='text/xml'
505 if isinstance(dump,str):
507 req.response_gzencode=1
510 req.write('<?xml version="1.0"?><idem></idem>')
511 # print "sessions %r"%self.session
513 n=os.path.basename(req.PATH_INFO)
515 req.response_headers['Content-Type'] = self.mime.get(os.path.splitext(n)[1].lower(), 'application/octet-stream')
516 req.write(self.files[n])
518 req.response_headers['Content-Type'] = 'text/html; charset=UTF-8'
519 req.write(self.files['index'])
523 parser = optparse.OptionParser()
524 parser.add_option("-p", "--port", dest="port", default="8022", help="Set the TCP port (default: 8022)")
525 parser.add_option("-c", "--command", dest="cmd", default=None,help="set the command (default: /bin/login or ssh localhost)")
526 parser.add_option("-l", "--log", action="store_true", dest="log",default=0,help="log requests to stderr (default: quiet mode)")
527 parser.add_option("-d", "--daemon", action="store_true", dest="daemon", default=0, help="run as daemon in the background")
528 parser.add_option("-P", "--pidfile",dest="pidfile",default="/var/run/ajaxterm.pid",help="set the pidfile (default: /var/run/ajaxterm.pid)")
529 parser.add_option("-i", "--index", dest="index_file", default="ajaxterm.html",help="default index file (default: ajaxterm.html)")
530 parser.add_option("-u", "--uid", dest="uid", help="Set the daemon's user id")
531 (o, a) = parser.parse_args()
537 nullin = file('/dev/null', 'r')
538 nullout = file('/dev/null', 'w')
539 os.dup2(nullin.fileno(), sys.stdin.fileno())
540 os.dup2(nullout.fileno(), sys.stdout.fileno())
541 os.dup2(nullout.fileno(), sys.stderr.fileno())
542 if os.getuid()==0 and o.uid:
544 os.setuid(int(o.uid))
546 os.setuid(pwd.getpwnam(o.uid).pw_uid)
549 file(o.pidfile,'w+').write(str(pid)+'\n')
552 print 'AjaxTerm at http://localhost:%s/ pid: %d' % (o.port,pid)
555 print 'AjaxTerm at http://localhost:%s/' % o.port
556 at=AjaxTerm(o.cmd,o.index_file)
557 # f=lambda:os.system('firefox http://localhost:%s/&'%o.port)
558 # qweb.qweb_wsgi_autorun(at,ip='localhost',port=int(o.port),threaded=0,log=o.log,callback_ready=None)
560 qweb.QWebWSGIServer(at,ip='localhost',port=int(o.port),threaded=0,log=o.log).serve_forever()
561 except KeyboardInterrupt,e:
562 sys.excepthook(*sys.exc_info())
565 if __name__ == '__main__':