ajaxterm!
[invirt/packages/invirt-web.git] / code / ajaxterm.py
1 #!/usr/bin/env python
2
3 """ Ajaxterm """
4
5 import array,cgi,fcntl,glob,mimetypes,optparse,os,pty,random,re,signal,select,sys,threading,time,termios,struct,pwd
6
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')
10
11 import qweb
12
13 class Terminal:
14         def __init__(self,width=80,height=24):
15                 self.width=width
16                 self.height=height
17                 self.init()
18                 self.reset()
19         def init(self):
20                 self.esc_seq={
21                         "\x00": None,
22                         "\x05": self.esc_da,
23                         "\x07": None,
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,
30                         "\x0e": None,
31                         "\x0f": None,
32                         "\x1b#8": None,
33                         "\x1b=": None,
34                         "\x1b>": None,
35                         "\x1b(0": None,
36                         "\x1b(A": None,
37                         "\x1b(B": None,
38                         "\x1b[c": self.esc_da,
39                         "\x1b[0c": self.esc_da,
40                         "\x1b]R": None,
41                         "\x1b7": self.esc_save,
42                         "\x1b8": self.esc_restore,
43                         "\x1bD": None,
44                         "\x1bE": None,
45                         "\x1bH": None,
46                         "\x1bM": self.esc_ri,
47                         "\x1bN": None,
48                         "\x1bO": None,
49                         "\x1bZ": self.esc_da,
50                         "\x1ba": None,
51                         "\x1bc": self.reset,
52                         "\x1bn": None,
53                         "\x1bo": None,
54                 }
55                 for k,v in self.esc_seq.items():
56                         if v==None:
57                                 self.esc_seq[k]=self.esc_ignore
58                 # regex
59                 d={
60                         r'\[\??([0-9;]*)([@ABCDEFGHJKLMPXacdefghlmnqrstu`])' : self.csi_dispatch,
61                         r'\]([^\x07]+)\x07' : self.esc_ignore,
62                 }
63                 self.esc_re=[]
64                 for k,v in d.items():
65                         self.esc_re.append((re.compile('\x1b'+k),v))
66                 # define csi sequences
67                 self.csi_seq={
68                         '@': (self.csi_at,[1]),
69                         '`': (self.csi_G,[1]),
70                         'J': (self.csi_J,[0]),
71                         'K': (self.csi_K,[0]),
72                 }
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
77                 self.trl1=""
78                 for i in range(256):
79                         if i<32:
80                                 self.trl1+=" "
81                         elif i<127 or i>160:
82                                 self.trl1+=chr(i)
83                         else:
84                                 self.trl1+="?"
85                 self.trhtml=""
86                 for i in range(256):
87                         if i==0x0a or (i>32 and i<127) or i>160:
88                                 self.trhtml+=chr(i)
89                         elif i<=32:
90                                 self.trhtml+="\xa0"
91                         else:
92                                 self.trhtml+="?"
93         def reset(self,s=""):
94                 self.scr=array.array('i',[0x000700]*(self.width*self.height))
95                 self.st=0
96                 self.sb=self.height-1
97                 self.cx_bak=self.cx=0
98                 self.cy_bak=self.cy=0
99                 self.cl=0
100                 self.sgr=0x000700
101                 self.buf=""
102                 self.outbuf=""
103                 self.last_html=""
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):
107                 pos=self.width*y+x
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))
121                 self.zero(y,x,y,x)
122         def cursor_down(self):
123                 if self.cy>=self.st and self.cy<=self.sb:
124                         self.cl=0
125                         q,r=divmod(self.cy+1,self.sb+1)
126                         if q:
127                                 self.scroll_up(self.st,self.sb)
128                                 self.cy=self.sb
129                         else:
130                                 self.cy=r
131         def cursor_right(self):
132                 q,r=divmod(self.cx+1,self.width)
133                 if q:
134                         self.cl=1
135                 else:
136                         self.cx=r
137         def echo(self,c):
138                 if self.cl:
139                         self.cursor_down()
140                         self.cx=0
141                 self.scr[(self.cy*self.width)+self.cx]=self.sgr|ord(c)
142                 self.cursor_right()
143         def esc_0x08(self,s):
144                 self.cx=max(0,self.cx-1)
145         def esc_0x09(self,s):
146                 x=self.cx+8
147                 q,r=divmod(x,8)
148                 self.cx=(q*8)%self.width
149         def esc_0x0a(self,s):
150                 self.cursor_down()
151         def esc_0x0d(self,s):
152                 self.cl=0
153                 self.cx=0
154         def esc_save(self,s):
155                 self.cx_bak=self.cx
156                 self.cy_bak=self.cy
157         def esc_restore(self,s):
158                 self.cx=self.cx_bak
159                 self.cy=self.cy_bak
160                 self.cl=0
161         def esc_da(self,s):
162                 self.outbuf="\x1b[?6c"
163         def esc_ri(self,s):
164                 self.cy=max(self.st,self.cy-1)
165                 if self.cy==self.st:
166                         self.scroll_down(self.st,self.sb)
167         def esc_ignore(self,*s):
168                 pass
169 #               print "term:ignore: %s"%repr(s)
170         def csi_dispatch(self,seq,mo):
171         # CSI sequences
172                 s=mo.group(1)
173                 c=mo.group(2)
174                 f=self.csi_seq.get(c,None)
175                 if f:
176                         try:
177                                 l=[min(int(i),1024) for i in s.split(';') if len(i)<4]
178                         except ValueError:
179                                 l=[]
180                         if len(l)==0:
181                                 l=f[1]
182                         f[0](l)
183 #               else:
184 #                       print 'csi ignore',c,l
185         def csi_at(self,l):
186                 for i in range(l[0]):
187                         self.scroll_right(self.cy,self.cx)
188         def csi_A(self,l):
189                 self.cy=max(self.st,self.cy-l[0])
190         def csi_B(self,l):
191                 self.cy=min(self.sb,self.cy+l[0])
192         def csi_C(self,l):
193                 self.cx=min(self.width-1,self.cx+l[0])
194                 self.cl=0
195         def csi_D(self,l):
196                 self.cx=max(0,self.cx-l[0])
197                 self.cl=0
198         def csi_E(self,l):
199                 self.csi_B(l)
200                 self.cx=0
201                 self.cl=0
202         def csi_F(self,l):
203                 self.csi_A(l)
204                 self.cx=0
205                 self.cl=0
206         def csi_G(self,l):
207                 self.cx=min(self.width,l[0])-1
208         def csi_H(self,l):
209                 if len(l)<2: l=[1,1]
210                 self.cx=min(self.width,l[1])-1
211                 self.cy=min(self.height,l[0])-1
212                 self.cl=0
213         def csi_J(self,l):
214                 if l[0]==0:
215                         self.zero(self.cy,self.cx,self.height-1,self.width-1)
216                 elif l[0]==1:
217                         self.zero(0,0,self.cy,self.cx)
218                 elif l[0]==2:
219                         self.zero(0,0,self.height-1,self.width-1)
220         def csi_K(self,l):
221                 if l[0]==0:
222                         self.zero(self.cy,self.cx,self.cy,self.width-1)
223                 elif l[0]==1:
224                         self.zero(self.cy,0,self.cy,self.cx)
225                 elif l[0]==2:
226                         self.zero(self.cy,0,self.cy,self.width-1)
227         def csi_L(self,l):
228                 for i in range(l[0]):
229                         if self.cy<self.sb:
230                                 self.scroll_down(self.cy,self.sb)
231         def csi_M(self,l):
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)
235         def csi_P(self,l):
236                 w,cx,cy=self.width,self.cx,self.cy
237                 end=self.peek(cy,cx,cy,w)
238                 self.csi_K([0])
239                 self.poke(cy,cx,end[l[0]:])
240         def csi_X(self,l):
241                 self.zero(self.cy,self.cx,self.cy,self.cx+l[0])
242         def csi_a(self,l):
243                 self.csi_C(l)
244         def csi_c(self,l):
245                 #'\x1b[?0c' 0-8 cursor size
246                 pass
247         def csi_d(self,l):
248                 self.cy=min(self.height,l[0])-1
249         def csi_e(self,l):
250                 self.csi_B(l)
251         def csi_f(self,l):
252                 self.csi_H(l)
253         def csi_h(self,l):
254                 if l[0]==4:
255                         pass
256 #                       print "insert on"
257         def csi_l(self,l):
258                 if l[0]==4:
259                         pass
260 #                       print "insert off"
261         def csi_m(self,l):
262                 for i in l:
263                         if i==0 or i==39 or i==49 or i==27:
264                                 self.sgr=0x000700
265                         elif i==1:
266                                 self.sgr=(self.sgr|0x000800)
267                         elif i==7:
268                                 self.sgr=0x070000
269                         elif i>=30 and i<=37:
270                                 c=i-30
271                                 self.sgr=(self.sgr&0xff08ff)|(c<<8)
272                         elif i>=40 and i<=47:
273                                 c=i-40
274                                 self.sgr=(self.sgr&0x00ffff)|(c<<16)
275 #                       else:
276 #                               print "CSI sgr ignore",l,i
277 #               print 'sgr: %r %x'%(l,self.sgr)
278         def csi_r(self,l):
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)
283         def csi_s(self,l):
284                 self.esc_save(0)
285         def csi_u(self,l):
286                 self.esc_restore(0)
287         def escape(self):
288                 e=self.buf
289                 if len(e)>32:
290 #                       print "error %r"%e
291                         self.buf=""
292                 elif e in self.esc_seq:
293                         self.esc_seq[e](e)
294                         self.buf=""
295                 else:
296                         for r,f in self.esc_re:
297                                 mo=r.match(e)
298                                 if mo:
299                                         f(e,mo)
300                                         self.buf=""
301                                         break
302 #               if self.buf=='': print "ESC %r\n"%e
303         def write(self,s):
304                 for i in s:
305                         if len(self.buf) or (i in self.esc_seq):
306                                 self.buf+=i
307                                 self.escape()
308                         elif i == '\x1b':
309                                 self.buf+=i
310                         else:
311                                 self.echo(i)
312         def read(self):
313                 b=self.outbuf
314                 self.outbuf=""
315                 return b
316         def dump(self):
317                 r=''
318                 for i in self.scr:
319                         r+=chr(i&255)
320                 return r
321         def dumplatin1(self):
322                 return self.dump().translate(self.trl1)
323         def dumphtml(self,color=1):
324                 h=self.height
325                 w=self.width
326                 r=""
327                 span=""
328                 span_bg,span_fg=-1,-1
329                 for i in range(h*w):
330                         q,c=divmod(self.scr[i],256)
331                         if color:
332                                 bg,fg=divmod(q,256)
333                         else:
334                                 bg,fg=0,7
335                         if i==self.cy*w+self.cx:
336                                 bg,fg=1,7
337                         if (bg!=span_bg or fg!=span_fg or i==h*w-1):
338                                 if len(span):
339                                         r+='<span class="f%d b%d">%s</span>'%(span_fg,span_bg,cgi.escape(span.translate(self.trhtml)))
340                                 span=""
341                                 span_bg,span_fg=bg,fg
342                         span+=chr(c)
343                         if i%w==w-1:
344                                 span+='\n'
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>'
348                 else:
349                         self.last_html=r
350 #                       print self
351                         return r
352         def __repr__(self):
353                 d=self.dumplatin1()
354                 r=""
355                 for i in range(self.height):
356                         r+="|%s|\n"%d[self.width*i:self.width*(i+1)]
357                 return r
358
359 class SynchronizedMethod:
360         def __init__(self,lock,orig):
361                 self.lock=lock
362                 self.orig=orig
363         def __call__(self,*l):
364                 self.lock.acquire()
365                 r=self.orig(*l)
366                 self.lock.release()
367                 return r
368
369 class Multiplex:
370         def __init__(self):
371                 self.proc={}
372                 self.lock=threading.RLock()
373                 self.thread=threading.Thread(target=self.loop)
374                 self.thread.daemon=True
375                 self.alive=1
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))
380                 self.thread.start()
381         def create(self,cmd,w=80,h=25):
382                 pid,fd=pty.fork()
383                 if pid==0:
384                         try:
385                                 fdl=[int(i) for i in os.listdir('/proc/self/fd')]
386                         except OSError:
387                                 fdl=range(256)
388                         for i in [i for i in fdl if i>2]:
389                                 try:
390                                         os.close(i)
391                                 except OSError:
392                                         pass
393                         env={}
394                         env["COLUMNS"]=str(w)
395                         env["LINES"]=str(h)
396                         env["TERM"]="linux"
397                         env["PATH"]=os.environ['PATH']
398                         os.execvpe(cmd[0],cmd,env)
399                 else:
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()}
404                         return fd
405         def die(self):
406                 self.alive=0
407         def run(self):
408                 return self.alive
409         def fds(self):
410                 return self.proc.keys()
411         def proc_kill(self,fd):
412                 if fd in self.proc:
413                         self.proc[fd]['time']=0
414                 t=time.time()
415                 for i in self.proc.keys():
416                         t0=self.proc[i]['time']
417                         if (t-t0)>120:
418                                 try:
419                                         os.close(i)
420                                         os.kill(self.proc[i]['pid'],signal.SIGTERM)
421                                 except (IOError,OSError):
422                                         pass
423                                 del self.proc[i]
424         def proc_read(self,fd):
425                 try:
426                         t=self.proc[fd]['term']
427                         t.write(os.read(fd,65536))
428                         reply=t.read()
429                         if reply:
430                                 os.write(fd,reply)
431                         self.proc[fd]['time']=time.time()
432                 except (KeyError,IOError,OSError):
433                         self.proc_kill(fd)
434         def proc_write(self,fd,s):
435                 try:
436                         os.write(fd,s)
437                 except (IOError,OSError):
438                         self.proc_kill(fd)
439         def dump(self,fd,color=1):
440                 try:
441                         return self.proc[fd]['term'].dumphtml(color)
442                 except KeyError:
443                         return False
444         def loop(self):
445                 while self.run():
446                         fds=self.fds()
447                         i,o,e=select.select(fds, [], [], 1.0)
448                         for fd in i:
449                                 self.proc_read(fd)
450                         if len(i):
451                                 time.sleep(0.002)
452                 for i in self.proc.keys():
453                         try:
454                                 os.close(i)
455                                 os.kill(self.proc[i]['pid'],signal.SIGTERM)
456                         except (IOError,OSError):
457                                 pass
458
459 class AjaxTerm:
460         def __init__(self,cmd=None,index_file='ajaxterm.html'):
461                 self.files={}
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)
469                 self.session = {}
470         def __call__(self, environ, start_response):
471                 req = qweb.QWebRequest(environ, start_response,session=None)
472                 if req.PATH_INFO.endswith('/u'):
473                         s=req.REQUEST["s"]
474                         k=req.REQUEST["k"]
475                         c=req.REQUEST["c"]
476                         w=req.REQUEST.int("w")
477                         h=req.REQUEST.int("h")
478                         if s in self.session:
479                                 term=self.session[s]
480                         else:
481                                 if not (w>2 and w<256 and h>2 and h<100):
482                                         w,h=80,25
483                                 term=self.session[s]=self.multi.create(w,h)
484                         if k:
485                                 self.multi.proc_write(term,k)
486                         time.sleep(0.002)
487                         dump=self.multi.dump(term,c)
488                         req.response_headers['Content-Type']='text/xml'
489                         if isinstance(dump,str):
490                                 req.write(dump)
491                                 req.response_gzencode=1
492                         else:
493                                 del self.session[s]
494                                 req.write('<?xml version="1.0"?><idem></idem>')
495 #                       print "sessions %r"%self.session
496                 else:
497                         n=os.path.basename(req.PATH_INFO)
498                         if n in self.files:
499                                 req.response_headers['Content-Type'] = self.mime.get(os.path.splitext(n)[1].lower(), 'application/octet-stream')
500                                 req.write(self.files[n])
501                         else:
502                                 req.response_headers['Content-Type'] = 'text/html; charset=UTF-8'
503                                 req.write(self.files['index'])
504                 return req
505
506 def main():
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()
516         if o.daemon:
517                 pid=os.fork()
518                 if pid == 0:
519                         #os.setsid() ?
520                         os.setpgrp()
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:
527                                 try:
528                                         os.setuid(int(o.uid))
529                                 except:
530                                         os.setuid(pwd.getpwnam(o.uid).pw_uid)
531                 else:
532                         try:
533                                 file(o.pidfile,'w+').write(str(pid)+'\n')
534                         except:
535                                 pass
536                         print 'AjaxTerm at http://localhost:%s/ pid: %d' % (o.port,pid)
537                         sys.exit(0)
538         else:
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)
543         try:
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())
547         at.multi.die()
548
549 if __name__ == '__main__':
550         main()
551