source: package_branches/invirt-web/ajaxterm-rebased/code/ajaxterm.py @ 2747

Last change on this file since 2747 was 2747, checked in by broder, 14 years ago

Import upstream ajaxterm 0.10

File size: 14.4 KB
Line 
1#!/usr/bin/env python
2
3""" Ajaxterm """
4
5import array,cgi,fcntl,glob,mimetypes,optparse,os,pty,random,re,signal,select,sys,threading,time,termios,struct,pwd
6
7os.chdir(os.path.normpath(os.path.dirname(__file__)))
8# Optional: Add QWeb in sys path
9sys.path[0:0]=glob.glob('../../python')
10
11import qweb
12
13class 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
359class 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
369class Multiplex:
370        def __init__(self,cmd=None):
371                signal.signal(signal.SIGCHLD, signal.SIG_IGN)
372                self.cmd=cmd
373                self.proc={}
374                self.lock=threading.RLock()
375                self.thread=threading.Thread(target=self.loop)
376                self.alive=1
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))
381                self.thread.start()
382        def create(self,w=80,h=25):
383                pid,fd=pty.fork()
384                if pid==0:
385                        try:
386                                fdl=[int(i) for i in os.listdir('/proc/self/fd')]
387                        except OSError:
388                                fdl=range(256)
389                        for i in [i for i in fdl if i>2]:
390                                try:
391                                        os.close(i)
392                                except OSError:
393                                        pass
394                        if self.cmd:
395                                cmd=['/bin/sh','-c',self.cmd]
396                        elif os.getuid()==0:
397                                cmd=['/bin/login']
398                        else:
399                                sys.stdout.write("Login: ")
400                                login=sys.stdin.readline().strip()
401                                if re.match('^[0-9A-Za-z-_. ]+$',login):
402                                        cmd=['ssh']
403                                        cmd+=['-oPreferredAuthentications=keyboard-interactive,password']
404                                        cmd+=['-oNoHostAuthenticationForLocalhost=yes']
405                                        cmd+=['-oLogLevel=FATAL']
406                                        cmd+=['-F/dev/null','-l',login,'localhost']
407                                else:
408                                        os._exit(0)
409                        env={}
410                        env["COLUMNS"]=str(w)
411                        env["LINES"]=str(h)
412                        env["TERM"]="linux"
413                        env["PATH"]=os.environ['PATH']
414                        os.execvpe(cmd[0],cmd,env)
415                else:
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()}
420                        return fd
421        def die(self):
422                self.alive=0
423        def run(self):
424                return self.alive
425        def fds(self):
426                return self.proc.keys()
427        def proc_kill(self,fd):
428                if fd in self.proc:
429                        self.proc[fd]['time']=0
430                t=time.time()
431                for i in self.proc.keys():
432                        t0=self.proc[i]['time']
433                        if (t-t0)>120:
434                                try:
435                                        os.close(i)
436                                        os.kill(self.proc[i]['pid'],signal.SIGTERM)
437                                except (IOError,OSError):
438                                        pass
439                                del self.proc[i]
440        def proc_read(self,fd):
441                try:
442                        t=self.proc[fd]['term']
443                        t.write(os.read(fd,65536))
444                        reply=t.read()
445                        if reply:
446                                os.write(fd,reply)
447                        self.proc[fd]['time']=time.time()
448                except (KeyError,IOError,OSError):
449                        self.proc_kill(fd)
450        def proc_write(self,fd,s):
451                try:
452                        os.write(fd,s)
453                except (IOError,OSError):
454                        self.proc_kill(fd)
455        def dump(self,fd,color=1):
456                try:
457                        return self.proc[fd]['term'].dumphtml(color)
458                except KeyError:
459                        return False
460        def loop(self):
461                while self.run():
462                        fds=self.fds()
463                        i,o,e=select.select(fds, [], [], 1.0)
464                        for fd in i:
465                                self.proc_read(fd)
466                        if len(i):
467                                time.sleep(0.002)
468                for i in self.proc.keys():
469                        try:
470                                os.close(i)
471                                os.kill(self.proc[i]['pid'],signal.SIGTERM)
472                        except (IOError,OSError):
473                                pass
474
475class AjaxTerm:
476        def __init__(self,cmd=None,index_file='ajaxterm.html'):
477                self.files={}
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)
485                self.session = {}
486        def __call__(self, environ, start_response):
487                req = qweb.QWebRequest(environ, start_response,session=None)
488                if req.PATH_INFO.endswith('/u'):
489                        s=req.REQUEST["s"]
490                        k=req.REQUEST["k"]
491                        c=req.REQUEST["c"]
492                        w=req.REQUEST.int("w")
493                        h=req.REQUEST.int("h")
494                        if s in self.session:
495                                term=self.session[s]
496                        else:
497                                if not (w>2 and w<256 and h>2 and h<100):
498                                        w,h=80,25
499                                term=self.session[s]=self.multi.create(w,h)
500                        if k:
501                                self.multi.proc_write(term,k)
502                        time.sleep(0.002)
503                        dump=self.multi.dump(term,c)
504                        req.response_headers['Content-Type']='text/xml'
505                        if isinstance(dump,str):
506                                req.write(dump)
507                                req.response_gzencode=1
508                        else:
509                                del self.session[s]
510                                req.write('<?xml version="1.0"?><idem></idem>')
511#                       print "sessions %r"%self.session
512                else:
513                        n=os.path.basename(req.PATH_INFO)
514                        if n in self.files:
515                                req.response_headers['Content-Type'] = self.mime.get(os.path.splitext(n)[1].lower(), 'application/octet-stream')
516                                req.write(self.files[n])
517                        else:
518                                req.response_headers['Content-Type'] = 'text/html; charset=UTF-8'
519                                req.write(self.files['index'])
520                return req
521
522def main():
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()
532        if o.daemon:
533                pid=os.fork()
534                if pid == 0:
535                        #os.setsid() ?
536                        os.setpgrp()
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:
543                                try:
544                                        os.setuid(int(o.uid))
545                                except:
546                                        os.setuid(pwd.getpwnam(o.uid).pw_uid)
547                else:
548                        try:
549                                file(o.pidfile,'w+').write(str(pid)+'\n')
550                        except:
551                                pass
552                        print 'AjaxTerm at http://localhost:%s/ pid: %d' % (o.port,pid)
553                        sys.exit(0)
554        else:
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)
559        try:
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())
563        at.multi.die()
564
565if __name__ == '__main__':
566        main()
567
Note: See TracBrowser for help on using the repository browser.