15
15
from threading import Thread
16
from functools import partial
20
class ExpiryTimer(object):
21
def __init__(self, idle):
23
signal.signal(signal.SIGALRM, partial(self.timeout,self))
26
signal.alarm(self.idle)
28
def start(self, time):
34
def timeout(self, signum, frame):
17
37
class StdinFromWeb(object):
18
38
def __init__(self, cmdQ, lineQ):
42
59
sys.stdin = StdinFromWeb(self.cmdQ, self.lineQ)
43
60
sys.stdout = self.out
44
61
sys.stderr = self.out
46
62
res = eval(cmd, self.globs, self.locls)
48
63
self.cmdQ.put({"okay":(self.out.getvalue(),res)})
50
65
self.out = cStringIO.StringIO()
51
66
except Exception, exc:
53
67
self.cmdQ.put({"exc":(self.out.getvalue(),str(exc))})
55
69
self.out = cStringIO.StringIO()
85
98
cmd = compile(ln['block'], "<web session>", 'exec');
87
100
except Exception, exc:
89
101
self.cmdQ.put({"exc":(self.out.getvalue(),str(exc))})
90
102
self.curr_cmd = ''
91
103
self.out = cStringIO.StringIO()
113
125
lineQ = Queue.Queue()
114
126
interpThread = PythonRunner(cmdQ, lineQ)
128
# Default expiry time of 15 minutes
129
expiry = ExpiryTimer(15 * 60)
132
interpThread.setDaemon(True)
136
def dispatch_msg(msg):
138
lineQ.put({msg['cmd']:msg['text']})
116
141
if __name__ == "__main__":
117
142
port = int(sys.argv[1])
118
143
magic = sys.argv[2]
120
# Attempt to open the socket.
121
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
125
# Excellent! It worked. Let's turn ourself into a daemon,
126
# then get on with the job of being a python interpreter.
129
interpThread.setDaemon(True)
133
(conn, addr) = s.accept()
136
buf = cStringIO.StringIO()
137
blk = conn.recv(1024)
141
blk = conn.recv(1024, socket.MSG_DONTWAIT)
143
# Exception thrown if it WOULD block (but we
144
# told it not to wait) - ie. we are done
147
msg = cjson.decode(inp)
149
# Check that the message is
150
digest = md5.new(msg['text'] + magic).digest().encode('hex')
151
if msg['digest'] != digest:
155
lineQ.put({msg['cmd']:msg['text']})
157
conn.sendall(cjson.encode(r))
145
common.chat.start_server(port, magic, True, dispatch_msg, initializer)