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):
372 self.lock=threading.RLock()
373 self.thread=threading.Thread(target=self.loop)
374 self.thread.daemon=True
376 # synchronize methods
377 for name in ['create','fds','proc_read','proc_write','dump','die','run']:
378 orig=getattr(self,name)
379 setattr(self,name,SynchronizedMethod(self.lock,orig))
381 def create(self,cmd,w=80,h=25):
385 fdl=[int(i) for i in os.listdir('/proc/self/fd')]
388 for i in [i for i in fdl if i>2]:
394 env["COLUMNS"]=str(w)
397 env["PATH"]=os.environ['PATH']
398 os.execvpe(cmd[0],cmd,env)
400 fcntl.fcntl(fd, fcntl.F_SETFL, os.O_NONBLOCK)
401 # python bug http://python.org/sf/1112949 on amd64
402 fcntl.ioctl(fd, struct.unpack('i',struct.pack('I',termios.TIOCSWINSZ))[0], struct.pack("HHHH",h,w,0,0))
403 self.proc[fd]={'pid':pid,'term':Terminal(w,h),'buf':'','time':time.time()}
410 return self.proc.keys()
411 def proc_kill(self,fd):
413 self.proc[fd]['time']=0
415 for i in self.proc.keys():
416 t0=self.proc[i]['time']
420 os.kill(self.proc[i]['pid'],signal.SIGTERM)
421 except (IOError,OSError):
424 def proc_read(self,fd):
426 t=self.proc[fd]['term']
427 t.write(os.read(fd,65536))
431 self.proc[fd]['time']=time.time()
432 except (KeyError,IOError,OSError):
434 def proc_write(self,fd,s):
437 except (IOError,OSError):
439 def dump(self,fd,color=1):
441 return self.proc[fd]['term'].dumphtml(color)
447 i,o,e=select.select(fds, [], [], 1.0)
452 for i in self.proc.keys():
455 os.kill(self.proc[i]['pid'],signal.SIGTERM)
456 except (IOError,OSError):
460 def __init__(self,cmd=None,index_file='ajaxterm.html'):
462 for i in ['css','html','js']:
463 for j in glob.glob('*.%s'%i):
464 self.files[j]=file(j).read()
465 self.files['index']=file(index_file).read()
466 self.mime = mimetypes.types_map.copy()
467 self.mime['.html']= 'text/html; charset=UTF-8'
468 self.multi = Multiplex(cmd)
470 def __call__(self, environ, start_response):
471 req = qweb.QWebRequest(environ, start_response,session=None)
472 if req.PATH_INFO.endswith('/u'):
476 w=req.REQUEST.int("w")
477 h=req.REQUEST.int("h")
478 if s in self.session:
481 if not (w>2 and w<256 and h>2 and h<100):
483 term=self.session[s]=self.multi.create(w,h)
485 self.multi.proc_write(term,k)
487 dump=self.multi.dump(term,c)
488 req.response_headers['Content-Type']='text/xml'
489 if isinstance(dump,str):
491 req.response_gzencode=1
494 req.write('<?xml version="1.0"?><idem></idem>')
495 # print "sessions %r"%self.session
497 n=os.path.basename(req.PATH_INFO)
499 req.response_headers['Content-Type'] = self.mime.get(os.path.splitext(n)[1].lower(), 'application/octet-stream')
500 req.write(self.files[n])
502 req.response_headers['Content-Type'] = 'text/html; charset=UTF-8'
503 req.write(self.files['index'])
507 parser = optparse.OptionParser()
508 parser.add_option("-p", "--port", dest="port", default="8022", help="Set the TCP port (default: 8022)")
509 parser.add_option("-c", "--command", dest="cmd", default=None,help="set the command (default: /bin/login or ssh localhost)")
510 parser.add_option("-l", "--log", action="store_true", dest="log",default=0,help="log requests to stderr (default: quiet mode)")
511 parser.add_option("-d", "--daemon", action="store_true", dest="daemon", default=0, help="run as daemon in the background")
512 parser.add_option("-P", "--pidfile",dest="pidfile",default="/var/run/ajaxterm.pid",help="set the pidfile (default: /var/run/ajaxterm.pid)")
513 parser.add_option("-i", "--index", dest="index_file", default="ajaxterm.html",help="default index file (default: ajaxterm.html)")
514 parser.add_option("-u", "--uid", dest="uid", help="Set the daemon's user id")
515 (o, a) = parser.parse_args()
521 nullin = file('/dev/null', 'r')
522 nullout = file('/dev/null', 'w')
523 os.dup2(nullin.fileno(), sys.stdin.fileno())
524 os.dup2(nullout.fileno(), sys.stdout.fileno())
525 os.dup2(nullout.fileno(), sys.stderr.fileno())
526 if os.getuid()==0 and o.uid:
528 os.setuid(int(o.uid))
530 os.setuid(pwd.getpwnam(o.uid).pw_uid)
533 file(o.pidfile,'w+').write(str(pid)+'\n')
536 print 'AjaxTerm at http://localhost:%s/ pid: %d' % (o.port,pid)
539 print 'AjaxTerm at http://localhost:%s/' % o.port
540 at=AjaxTerm(o.cmd,o.index_file)
541 # f=lambda:os.system('firefox http://localhost:%s/&'%o.port)
542 # qweb.qweb_wsgi_autorun(at,ip='localhost',port=int(o.port),threaded=0,log=o.log,callback_ready=None)
544 qweb.QWebWSGIServer(at,ip='localhost',port=int(o.port),threaded=0,log=o.log).serve_forever()
545 except KeyboardInterrupt,e:
546 sys.excepthook(*sys.exc_info())
549 if __name__ == '__main__':