This website requires JavaScript.
2010年09月17日 19:08:22 -07:00
#!/usr/bin/env python
import array,cgi,fcntl,glob,mimetypes,optparse,os,pty,random,re,signal,select,sys,threading,time,termios,struct,pwd
os.chdir(os.path.normpath(os.path.dirname(__file__)))
# Optional: Add QWeb in sys path
sys.path[0:0]=glob.glob('../../python')
2010年09月17日 19:10:08 -07:00
import string, subprocess, uuid
2011年01月03日 10:57:35 -08:00
TIMEOUT=300
2010年09月17日 19:08:22 -07:00
2010年09月17日 20:02:36 -07:00
def __init__(self,width=80,height=24):
"\x1b8": self.esc_restore,
for k,v in self.esc_seq.items():
self.esc_seq[k]=self.esc_ignore
r'\[\??([0-9;]*)([@ABCDEFGHJKLMPXacdefghlmnqrstu`])' : self.csi_dispatch,
r'\]([^\x07]+)\x07' : self.esc_ignore,
self.esc_re.append((re.compile('\x1b'+k),v))
for i in [i[4] for i in dir(self) if i.startswith('csi_') and len(i)==5]:
if not self.csi_seq.has_key(i):
self.csi_seq[i]=(getattr(self,'csi_'+i),[1])
# Init 0-256 to latin1 and html translation table
if i==0x0a or (i>32 and i<127) or i>160:
self.scr=array.array('i',[0x000700]*(self.width*self.height))
def peek(self,y1,x1,y2,x2):
return self.scr[self.width*y1+x1:self.width*y2+x2]
self.scr[pos:pos+len(s)]=s
def zero(self,y1,x1,y2,x2):
w=self.width*(y2-y1)+x2-x1+1
z=array.array('i',[0x000700]*w)
self.scr[self.width*y1+x1:self.width*y2+x2+1]=z
def scroll_up(self,y1,y2):
self.poke(y1,0,self.peek(y1+1,0,y2,self.width))
self.zero(y2,0,y2,self.width-1)
def scroll_down(self,y1,y2):
self.poke(y1+1,0,self.peek(y1,0,y2-1,self.width))
self.zero(y1,0,y1,self.width-1)
def scroll_right(self,y,x):
self.poke(y,x+1,self.peek(y,x,y,self.width))
if self.cy>=self.st and self.cy<=self.sb:
q,r=divmod(self.cy+1,self.sb+1)
self.scroll_up(self.st,self.sb)
q,r=divmod(self.cx+1,self.width)
self.scr[(self.cy*self.width)+self.cx]=self.sgr|ord(c)
self.cy=max(self.st,self.cy-1)
self.scroll_down(self.st,self.sb)
# print "term:ignore: %s"%repr(s)
def csi_dispatch(self,seq,mo):
f=self.csi_seq.get(c,None)
l=[min(int(i),1024) for i in s.split(';') if len(i)<4]
self.scroll_right(self.cy,self.cx)
self.cy=max(self.st,self.cy-l[0])
self.cy=min(self.sb,self.cy+l[0])
self.cx=min(self.width-1,self.cx+l[0])
self.cx=max(0,self.cx-l[0])
self.cx=min(self.width,l[0])-1
self.cx=min(self.width,l[1])-1
self.cy=min(self.height,l[0])-1
self.zero(self.cy,self.cx,self.height-1,self.width-1)
self.zero(0,0,self.cy,self.cx)
self.zero(0,0,self.height-1,self.width-1)
self.zero(self.cy,self.cx,self.cy,self.width-1)
self.zero(self.cy,0,self.cy,self.cx)
self.zero(self.cy,0,self.cy,self.width-1)
self.scroll_down(self.cy,self.sb)
if self.cy>=self.st and self.cy<=self.sb:
self.scroll_up(self.cy,self.sb)
w,cx,cy=self.width,self.cx,self.cy
end=self.peek(cy,cx,cy,w)
self.poke(cy,cx,end[l[0]:])
self.zero(self.cy,self.cx,self.cy,self.cx+l[0])
#'\x1b[?0c' 0-8 cursor size
self.cy=min(self.height,l[0])-1
if i==0 or i==39 or i==49 or i==27:
self.sgr=(self.sgr|0x000800)
self.sgr=(self.sgr&0xff08ff)|(c<<8)
self.sgr=(self.sgr&0x00ffff)|(c<<16)
# print "CSI sgr ignore",l,i
# print 'sgr: %r %x'%(l,self.sgr)
if len(l)<2: l=[0,self.height]
self.st=min(self.height-1,l[0]-1)
self.sb=min(self.height-1,l[1]-1)
self.sb=max(self.st,self.sb)
# if self.buf=='': print "ESC %r\n"%e
if len(self.buf) or (i in self.esc_seq):
return self.dump().translate(self.trl1)
def dumphtml(self,color=1):
q,c=divmod(self.scr[i],256)
if (bg!=span_bg or fg!=span_fg or i==h*w-1):
r+='<span class="f%d b%d">%s</span>'%(span_fg,span_bg,cgi.escape(span.translate(self.trhtml)))
r='<?xml version="1.0" encoding="ISO-8859-1"?><pre class="term">%s</pre>'%r
return '<?xml version="1.0"?><idem></idem>'
for i in range(self.height):
r+="|%s|\n"%d[self.width*i:self.width*(i+1)]
2010年09月17日 19:08:22 -07:00
class SynchronizedMethod:
2010年09月17日 20:02:36 -07:00
def __init__(self,lock,orig):
2010年09月17日 19:08:22 -07:00
2010年09月17日 20:02:36 -07:00
def __init__(self,cmd=None):
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
self.lock=threading.RLock()
self.thread=threading.Thread(target=self.loop)
self.lastActivity=time.time()
for name in ['create','fds','proc_read','proc_write','dump','die','run']:
setattr(self,name,SynchronizedMethod(self.lock,orig))
def create(self,w=80,h=25):
fdl=[int(i) for i in os.listdir('/proc/self/fd')]
for i in [i for i in fdl if i>2]:
cmd=['/bin/sh','-c',self.cmd]
sys.stdout.write("Login: ")
login=sys.stdin.readline().strip()
if re.match('^[0-9A-Za-z-_. ]+$',login):
cmd+=['-oPreferredAuthentications=keyboard-interactive,password']
cmd+=['-oNoHostAuthenticationForLocalhost=yes']
cmd+=['-oLogLevel=FATAL']
cmd+=['-F/dev/null','-l',login,'localhost']
env["PATH"]=os.environ['PATH']
os.execvpe(cmd[0],cmd,env)
fcntl.fcntl(fd, fcntl.F_SETFL, os.O_NONBLOCK)
# python bug http://python.org/sf/1112949 on amd64
fcntl.ioctl(fd, struct.unpack('i',struct.pack('I',termios.TIOCSWINSZ))[0], struct.pack("HHHH",h,w,0,0))
self.proc[fd]={'pid':pid,'term':Terminal(w,h),'buf':'','time':time.time()}
for i in self.proc.keys():
2011年01月03日 10:57:35 -08:00
if (t-t0)>TIMEOUT:
2010年09月17日 20:02:36 -07:00
try:
os.kill(self.proc[i]['pid'],signal.SIGTERM)
except (IOError,OSError):
t.write(os.read(fd,65536))
self.proc[fd]['time']=time.time()
except (KeyError,IOError,OSError):
def proc_write(self,fd,s):
except (IOError,OSError):
def dump(self,fd,color=1):
return self.proc[fd]['term'].dumphtml(color)
i,o,e=select.select(fds, [], [], 1.0)
2011年01月03日 10:57:35 -08:00
if time.time() - self.lastActivity > TIMEOUT:
2010年09月17日 20:02:36 -07:00
global g_server
for i in self.proc.keys():
os.kill(self.proc[i]['pid'],signal.SIGTERM)
except (IOError,OSError):
2010年09月17日 19:08:22 -07:00
2010年09月17日 20:02:36 -07:00
def __init__(self,cmd=None,index_file='ajaxterm.html',token=None):
for i in ['css','html','js']:
for j in glob.glob('*.%s'%i):
self.files[j]=file(j).read()
self.files['index']=file(index_file).read()
self.mime = mimetypes.types_map.copy()
self.mime['.html']= 'text/html; charset=UTF-8'
self.multi = Multiplex(cmd)
def __call__(self, environ, start_response):
req = qweb.QWebRequest(environ, start_response,session=None)
if req.PATH_INFO.endswith('/u'):
raise Exception('Not Authorized')
# The original code below was insecure, because it allowed unauthorized sessions to be created
# if not (w>2 and w<256 and h>2 and h<100):
# term=self.session[s]=self.multi.create(w,h)
self.multi.proc_write(term,k)
self.multi.lastActivity = time.time();
dump=self.multi.dump(term,c)
req.response_headers['Content-Type']='text/xml'
req.write('<?xml version="1.0"?><idem></idem>')
# print "sessions %r"%self.session
n=os.path.basename(req.PATH_INFO)
req.response_headers['Content-Type'] = self.mime.get(os.path.splitext(n)[1].lower(), 'application/octet-stream')
elif req.REQUEST['token'] == self.token:
req.response_headers['Content-Type'] = 'text/html; charset=UTF-8'
session_id = str(uuid.uuid4())
req.write(string.Template(self.files['index']).substitute(session_id=session_id))
term=self.session[session_id]=self.multi.create(80,25)
raise Exception("Not Authorized")
2010年09月17日 19:08:22 -07:00
2010年09月17日 20:02:36 -07:00
parser = optparse.OptionParser()
parser.add_option("-p", "--port", dest="port", default="8022", help="Set the TCP port (default: 8022)")
parser.add_option("-c", "--command", dest="cmd", default=None,help="set the command (default: /bin/login or ssh 0.0.0.0)")
parser.add_option("-l", "--log", action="store_true", dest="log",default=0,help="log requests to stderr (default: quiet mode)")
parser.add_option("-d", "--daemon", action="store_true", dest="daemon", default=0, help="run as daemon in the background")
parser.add_option("-P", "--pidfile",dest="pidfile",default="/var/run/ajaxterm.pid",help="set the pidfile (default: /var/run/ajaxterm.pid)")
parser.add_option("-i", "--index", dest="index_file", default="ajaxterm.html",help="default index file (default: ajaxterm.html)")
parser.add_option("-u", "--uid", dest="uid", help="Set the daemon's user id")
parser.add_option("-t", "--token", dest="token", help="Set authorization token")
(o, a) = parser.parse_args()
nullin = file('/dev/null', 'r')
nullout = file('/dev/null', 'w')
os.dup2(nullin.fileno(), sys.stdin.fileno())
os.dup2(nullout.fileno(), sys.stdout.fileno())
os.dup2(nullout.fileno(), sys.stderr.fileno())
if os.getuid()==0 and o.uid:
os.setuid(pwd.getpwnam(o.uid).pw_uid)
file(o.pidfile,'w+').write(str(pid)+'\n')
print 'AjaxTerm at http://0.0.0.0:%s/ pid: %d' % (o.port,pid)
print 'AjaxTerm at http://0.0.0.0:%s/' % o.port
at=AjaxTerm(o.cmd,o.index_file,o.token)
# f=lambda:os.system('firefox http://localhost:%s/&'%o.port)
# qweb.qweb_wsgi_autorun(at,ip='localhost',port=int(o.port),threaded=0,log=o.log,callback_ready=None)
g_server = qweb.QWebWSGIServer(at,ip='0.0.0.0',port=int(o.port),threaded=0,log=o.log)
except KeyboardInterrupt,e:
sys.excepthook(*sys.exc_info())
2010年09月17日 19:08:22 -07:00
if __name__ == '__main__':
2010年09月17日 20:02:36 -07:00
main()
2010年09月17日 19:08:22 -07:00