1
# IVLE - Informatics Virtual Learning Environment
2
# Copyright (C) 2007-2008 The University of Melbourne
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU General Public License for more details.
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19
# Author: Thomas Conway
30
class Terminate(Exception):
31
"""Exception thrown when server is to be shut down. It will attempt to sned
32
the final_response to the client and then exits"""
33
def __init__(self, final_response=None):
34
self.final_response = final_response
37
return repr(self.final_response)
40
def start_server(port, magic, daemon_mode, handler, initializer = None):
41
# Attempt to open the socket.
42
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
46
# Excellent! It worked. Let's turn ourself into a daemon,
47
# then get on with the job of being a python interpreter.
49
if os.fork(): # launch child and...
50
os._exit(0) # kill off parent
52
if os.fork(): # launch child and...
53
os._exit(0) # kill off parent again.
60
(conn, addr) = s.accept()
63
buf = cStringIO.StringIO()
68
blk = conn.recv(1024, socket.MSG_DONTWAIT)
70
# Exception thrown if it WOULD block (but we
71
# told it not to wait) - ie. we are done
74
env = cjson.decode(inp)
76
# Check that the message is
77
digest = md5.new(env['content'] + magic).digest().encode('hex')
78
if env['digest'] != digest:
82
content = cjson.decode(env['content'])
84
response = handler(content)
86
conn.sendall(cjson.encode(response))
91
# Try and send final response and then terminate
93
conn.sendall(cjson.encode(t.final_response))
97
# Make a JSON object full of exceptional goodness
98
tb_dump = cStringIO.StringIO()
99
e_type, e_val, e_tb = sys.exc_info()
100
traceback.print_tb(e_tb, file=tb_dump)
102
"type": e_type.__name__,
104
"traceback": tb_dump.getvalue()
106
conn.sendall(cjson.encode(json_exc))
110
def chat(host, port, msg, magic, decode = True):
111
sok = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
112
sok.connect((host, port))
113
content = cjson.encode(msg)
114
digest = md5.new(content + magic).digest().encode("hex")
115
env = {'digest':digest,'content':content}
116
sok.send(cjson.encode(env))
118
buf = cStringIO.StringIO()
123
blk = conn.recv(1024, socket.MSG_DONTWAIT)
125
# Exception thrown if it WOULD block (but we
126
# told it not to wait) - ie. we are done
132
return cjson.decode(inp)