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')
12
import string, subprocess, uuid
18
def __init__(self,width=80,height=24):
28
"\x08": self.esc_0x08,
29
"\x09": self.esc_0x09,
30
"\x0a": self.esc_0x0a,
31
"\x0b": self.esc_0x0a,
32
"\x0c": self.esc_0x0a,
33
"\x0d": self.esc_0x0d,
42
"\x1b[c": self.esc_da,
43
"\x1b[0c": self.esc_da,
45
"\x1b7": self.esc_save,
46
"\x1b8": self.esc_restore,
59
for k,v in self.esc_seq.items():
61
self.esc_seq[k]=self.esc_ignore
64
r'\[\??([0-9;]*)([@ABCDEFGHJKLMPXacdefghlmnqrstu`])' : self.csi_dispatch,
65
r'\]([^\x07]+)\x07' : self.esc_ignore,
69
self.esc_re.append((re.compile('\x1b'+k),v))
70
# define csi sequences
72
'@': (self.csi_at,[1]),
73
'`': (self.csi_G,[1]),
74
'J': (self.csi_J,[0]),
75
'K': (self.csi_K,[0]),
77
for i in [i[4] for i in dir(self) if i.startswith('csi_') and len(i)==5]:
78
if not self.csi_seq.has_key(i):
79
self.csi_seq[i]=(getattr(self,'csi_'+i),[1])
80
# Init 0-256 to latin1 and html translation table
91
if i==0x0a or (i>32 and i<127) or i>160:
98
self.scr=array.array('i',[0x000700]*(self.width*self.height))
100
self.sb=self.height-1
101
self.cx_bak=self.cx=0
102
self.cy_bak=self.cy=0
108
def peek(self,y1,x1,y2,x2):
109
return self.scr[self.width*y1+x1:self.width*y2+x2]
110
def poke(self,y,x,s):
112
self.scr[pos:pos+len(s)]=s
113
def zero(self,y1,x1,y2,x2):
114
w=self.width*(y2-y1)+x2-x1+1
115
z=array.array('i',[0x000700]*w)
116
self.scr[self.width*y1+x1:self.width*y2+x2+1]=z
117
def scroll_up(self,y1,y2):
118
self.poke(y1,0,self.peek(y1+1,0,y2,self.width))
119
self.zero(y2,0,y2,self.width-1)
120
def scroll_down(self,y1,y2):
121
self.poke(y1+1,0,self.peek(y1,0,y2-1,self.width))
122
self.zero(y1,0,y1,self.width-1)
123
def scroll_right(self,y,x):
124
self.poke(y,x+1,self.peek(y,x,y,self.width))
126
def cursor_down(self):
127
if self.cy>=self.st and self.cy<=self.sb:
129
q,r=divmod(self.cy+1,self.sb+1)
131
self.scroll_up(self.st,self.sb)
135
def cursor_right(self):
136
q,r=divmod(self.cx+1,self.width)
145
self.scr[(self.cy*self.width)+self.cx]=self.sgr|ord(c)
147
def esc_0x08(self,s):
148
self.cx=max(0,self.cx-1)
149
def esc_0x09(self,s):
152
self.cx=(q*8)%self.width
153
def esc_0x0a(self,s):
155
def esc_0x0d(self,s):
158
def esc_save(self,s):
161
def esc_restore(self,s):
166
self.outbuf="\x1b[?6c"
168
self.cy=max(self.st,self.cy-1)
170
self.scroll_down(self.st,self.sb)
171
def esc_ignore(self,*s):
173
# print "term:ignore: %s"%repr(s)
174
def csi_dispatch(self,seq,mo):
178
f=self.csi_seq.get(c,None)
181
l=[min(int(i),1024) for i in s.split(';') if len(i)<4]
188
# print 'csi ignore',c,l
190
for i in range(l[0]):
191
self.scroll_right(self.cy,self.cx)
193
self.cy=max(self.st,self.cy-l[0])
195
self.cy=min(self.sb,self.cy+l[0])
197
self.cx=min(self.width-1,self.cx+l[0])
200
self.cx=max(0,self.cx-l[0])
211
self.cx=min(self.width,l[0])-1
214
self.cx=min(self.width,l[1])-1
215
self.cy=min(self.height,l[0])-1
219
self.zero(self.cy,self.cx,self.height-1,self.width-1)
221
self.zero(0,0,self.cy,self.cx)
223
self.zero(0,0,self.height-1,self.width-1)
226
self.zero(self.cy,self.cx,self.cy,self.width-1)
228
self.zero(self.cy,0,self.cy,self.cx)
230
self.zero(self.cy,0,self.cy,self.width-1)
232
for i in range(l[0]):
234
self.scroll_down(self.cy,self.sb)
236
if self.cy>=self.st and self.cy<=self.sb:
237
for i in range(l[0]):
238
self.scroll_up(self.cy,self.sb)
240
w,cx,cy=self.width,self.cx,self.cy
241
end=self.peek(cy,cx,cy,w)
243
self.poke(cy,cx,end[l[0]:])
245
self.zero(self.cy,self.cx,self.cy,self.cx+l[0])
249
#'\x1b[?0c' 0-8 cursor size
252
self.cy=min(self.height,l[0])-1
267
if i==0 or i==39 or i==49 or i==27:
270
self.sgr=(self.sgr|0x000800)
273
elif i>=30 and i<=37:
275
self.sgr=(self.sgr&0xff08ff)|(c<<8)
276
elif i>=40 and i<=47:
278
self.sgr=(self.sgr&0x00ffff)|(c<<16)
280
# print "CSI sgr ignore",l,i
281
# print 'sgr: %r %x'%(l,self.sgr)
283
if len(l)<2: l=[0,self.height]
284
self.st=min(self.height-1,l[0]-1)
285
self.sb=min(self.height-1,l[1]-1)
286
self.sb=max(self.st,self.sb)
296
elif e in self.esc_seq:
300
for r,f in self.esc_re:
306
# if self.buf=='': print "ESC %r\n"%e
309
if len(self.buf) or (i in self.esc_seq):
325
def dumplatin1(self):
326
return self.dump().translate(self.trl1)
327
def dumphtml(self,color=1):
332
span_bg,span_fg=-1,-1
334
q,c=divmod(self.scr[i],256)
339
if i==self.cy*w+self.cx:
341
if (bg!=span_bg or fg!=span_fg or i==h*w-1):
343
r+='<span class="f%d b%d">%s</span>'%(span_fg,span_bg,cgi.escape(span.translate(self.trhtml)))
345
span_bg,span_fg=bg,fg
349
r='<?xml version="1.0" encoding="ISO-8859-1"?><pre class="term">%s</pre>'%r
350
if self.last_html==r:
351
return '<?xml version="1.0"?><idem></idem>'
359
for i in range(self.height):
360
r+="|%s|\n"%d[self.width*i:self.width*(i+1)]
363
class SynchronizedMethod:
364
def __init__(self,lock,orig):
367
def __call__(self,*l):
374
def __init__(self,cmd=None):
375
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
378
self.lock=threading.RLock()
379
self.thread=threading.Thread(target=self.loop)
381
self.lastActivity=time.time()
382
# synchronize methods
383
for name in ['create','fds','proc_read','proc_write','dump','die','run']:
384
orig=getattr(self,name)
385
setattr(self,name,SynchronizedMethod(self.lock,orig))
387
def create(self,w=80,h=25):
391
fdl=[int(i) for i in os.listdir('/proc/self/fd')]
394
for i in [i for i in fdl if i>2]:
400
cmd=['/bin/sh','-c',self.cmd]
404
sys.stdout.write("Login: ")
405
login=sys.stdin.readline().strip()
406
if re.match('^[0-9A-Za-z-_. ]+$',login):
408
cmd+=['-oPreferredAuthentications=keyboard-interactive,password']
409
cmd+=['-oNoHostAuthenticationForLocalhost=yes']
410
cmd+=['-oLogLevel=FATAL']
411
cmd+=['-F/dev/null','-l',login,'localhost']
415
env["COLUMNS"]=str(w)
418
env["PATH"]=os.environ['PATH']
419
os.execvpe(cmd[0],cmd,env)
421
fcntl.fcntl(fd, fcntl.F_SETFL, os.O_NONBLOCK)
422
# python bug http://python.org/sf/1112949 on amd64
423
fcntl.ioctl(fd, struct.unpack('i',struct.pack('I',termios.TIOCSWINSZ))[0], struct.pack("HHHH",h,w,0,0))
424
self.proc[fd]={'pid':pid,'term':Terminal(w,h),'buf':'','time':time.time()}
431
return self.proc.keys()
432
def proc_kill(self,fd):
434
self.proc[fd]['time']=0
436
for i in self.proc.keys():
437
t0=self.proc[i]['time']
441
os.kill(self.proc[i]['pid'],signal.SIGTERM)
442
except (IOError,OSError):
445
def proc_read(self,fd):
447
t=self.proc[fd]['term']
448
t.write(os.read(fd,65536))
452
self.proc[fd]['time']=time.time()
453
except (KeyError,IOError,OSError):
455
def proc_write(self,fd,s):
458
except (IOError,OSError):
460
def dump(self,fd,color=1):
462
return self.proc[fd]['term'].dumphtml(color)
468
i,o,e=select.select(fds, [], [], 1.0)
469
if time.time() - self.lastActivity > TIMEOUT:
476
for i in self.proc.keys():
479
os.kill(self.proc[i]['pid'],signal.SIGTERM)
480
except (IOError,OSError):
484
def __init__(self,cmd=None,index_file='ajaxterm.html',token=None):
487
for i in ['css','html','js']:
488
for j in glob.glob('*.%s'%i):
489
self.files[j]=file(j).read()
490
self.files['index']=file(index_file).read()
491
self.mime = mimetypes.types_map.copy()
492
self.mime['.html']= 'text/html; charset=UTF-8'
493
self.multi = Multiplex(cmd)
495
def __call__(self, environ, start_response):
496
req = qweb.QWebRequest(environ, start_response,session=None)
497
if req.PATH_INFO.endswith('/u'):
501
w=req.REQUEST.int("w")
502
h=req.REQUEST.int("h")
503
if s in self.session:
506
raise Exception('Not Authorized')
507
# The original code below was insecure, because it allowed unauthorized sessions to be created
508
# if not (w>2 and w<256 and h>2 and h<100):
510
# term=self.session[s]=self.multi.create(w,h)
512
self.multi.proc_write(term,k)
514
self.multi.lastActivity = time.time();
515
dump=self.multi.dump(term,c)
516
req.response_headers['Content-Type']='text/xml'
517
if isinstance(dump,str):
519
req.response_gzencode=1
522
req.write('<?xml version="1.0"?><idem></idem>')
523
# print "sessions %r"%self.session
525
n=os.path.basename(req.PATH_INFO)
527
req.response_headers['Content-Type'] = self.mime.get(os.path.splitext(n)[1].lower(), 'application/octet-stream')
528
req.write(self.files[n])
529
elif req.REQUEST['token'] == self.token:
530
req.response_headers['Content-Type'] = 'text/html; charset=UTF-8'
531
session_id = str(uuid.uuid4())
532
req.write(string.Template(self.files['index']).substitute(session_id=session_id))
533
term=self.session[session_id]=self.multi.create(80,25)
535
raise Exception("Not Authorized")
539
parser = optparse.OptionParser()
540
parser.add_option("-p", "--port", dest="port", default="8022", help="Set the TCP port (default: 8022)")
541
parser.add_option("-c", "--command", dest="cmd", default=None,help="set the command (default: /bin/login or ssh 0.0.0.0)")
542
parser.add_option("-l", "--log", action="store_true", dest="log",default=0,help="log requests to stderr (default: quiet mode)")
543
parser.add_option("-d", "--daemon", action="store_true", dest="daemon", default=0, help="run as daemon in the background")
544
parser.add_option("-P", "--pidfile",dest="pidfile",default="/var/run/ajaxterm.pid",help="set the pidfile (default: /var/run/ajaxterm.pid)")
545
parser.add_option("-i", "--index", dest="index_file", default="ajaxterm.html",help="default index file (default: ajaxterm.html)")
546
parser.add_option("-u", "--uid", dest="uid", help="Set the daemon's user id")
547
parser.add_option("-t", "--token", dest="token", help="Set authorization token")
548
(o, a) = parser.parse_args()
554
nullin = file('/dev/null', 'r')
555
nullout = file('/dev/null', 'w')
556
os.dup2(nullin.fileno(), sys.stdin.fileno())
557
os.dup2(nullout.fileno(), sys.stdout.fileno())
558
os.dup2(nullout.fileno(), sys.stderr.fileno())
559
if os.getuid()==0 and o.uid:
561
os.setuid(int(o.uid))
563
os.setuid(pwd.getpwnam(o.uid).pw_uid)
566
file(o.pidfile,'w+').write(str(pid)+'\n')
569
print 'AjaxTerm at http://0.0.0.0:%s/ pid: %d' % (o.port,pid)
572
print 'AjaxTerm at http://0.0.0.0:%s/' % o.port
573
at=AjaxTerm(o.cmd,o.index_file,o.token)
574
# f=lambda:os.system('firefox http://localhost:%s/&'%o.port)
575
# qweb.qweb_wsgi_autorun(at,ip='localhost',port=int(o.port),threaded=0,log=o.log,callback_ready=None)
578
g_server = qweb.QWebWSGIServer(at,ip='0.0.0.0',port=int(o.port),threaded=0,log=o.log)
579
g_server.serve_forever()
580
except KeyboardInterrupt,e:
581
sys.excepthook(*sys.exc_info())
584
if __name__ == '__main__':