~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to ivle/chat.py

  • Committer: William Grant
  • Date: 2010-02-18 03:31:47 UTC
  • Revision ID: grantw@unimelb.edu.au-20100218033147-z1es9tzrx7eg85gu
Ensure that we always close the DB connection at request termination, even in the case of an exception.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# IVLE - Informatics Virtual Learning Environment
 
2
# Copyright (C) 2007-2008 The University of Melbourne
 
3
#
 
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.
 
8
#
 
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.
 
13
#
 
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
 
17
 
 
18
# Module: Chat
 
19
# Author: Thomas Conway
 
20
# Date:   5/2/2008
 
21
 
 
22
import cjson
 
23
import cStringIO
 
24
import hashlib
 
25
import sys
 
26
import os
 
27
import socket
 
28
import traceback
 
29
 
 
30
SOCKETTIMEOUT = 60
 
31
BLOCKSIZE = 1024
 
32
 
 
33
class Terminate(Exception):
 
34
    """Exception thrown when server is to be shut down. It will attempt to
 
35
    send the final_response to the client and then exits"""
 
36
    def __init__(self, final_response=None):
 
37
        self.final_response = final_response
 
38
 
 
39
    def __str__(self):
 
40
        return repr(self.final_response)
 
41
 
 
42
 
 
43
def start_server(port, magic, daemon_mode, handler, initializer = None):
 
44
    # Attempt to open the socket.
 
45
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
46
    s.bind(('', port))
 
47
    s.listen(1)
 
48
 
 
49
    # Excellent! It worked. Let's turn ourself into a daemon,
 
50
    # then get on with the job of being a python interpreter.
 
51
    if daemon_mode:
 
52
        if os.fork():   # launch child and...
 
53
            os._exit(0) # kill off parent
 
54
        os.setsid()
 
55
        if os.fork():   # launch child and...
 
56
            os._exit(0) # kill off parent again.
 
57
        os.umask(077)
 
58
 
 
59
        try:
 
60
            MAXFD = os.sysconf("SC_OPEN_MAX")
 
61
        except:
 
62
            MAXFD = 256
 
63
 
 
64
        # Close all file descriptors, except the socket.
 
65
        for i in xrange(MAXFD):
 
66
            if i == s.fileno():
 
67
                continue
 
68
            try:
 
69
                os.close(i)
 
70
            except OSError:
 
71
                pass
 
72
 
 
73
        si = os.open(os.devnull, os.O_RDONLY)
 
74
        os.dup2(si, sys.stdin.fileno())
 
75
 
 
76
        so = os.open(os.devnull, os.O_WRONLY)
 
77
        os.dup2(so, sys.stdout.fileno())
 
78
 
 
79
        se = os.open(os.devnull, os.O_WRONLY)
 
80
        os.dup2(se, sys.stderr.fileno())
 
81
 
 
82
    if initializer:
 
83
        initializer()
 
84
 
 
85
    while True:
 
86
        (conn, addr) = s.accept()
 
87
        conn.settimeout(SOCKETTIMEOUT)
 
88
        try:
 
89
            # Grab the input
 
90
            inp = recv_netstring(conn)
 
91
            env = cjson.decode(inp)
 
92
 
 
93
            # Check that the message is 
 
94
            digest = hashlib.md5(env['content'] + magic).hexdigest()
 
95
            if env['digest'] != digest:
 
96
                conn.close()
 
97
                continue
 
98
 
 
99
            content = cjson.decode(env['content'])
 
100
 
 
101
            response = handler(content)
 
102
 
 
103
            send_netstring(conn, cjson.encode(response))
 
104
 
 
105
            conn.close()
 
106
 
 
107
        except Terminate, t:
 
108
            # Try and send final response and then terminate
 
109
            if t.final_response:
 
110
                send_netstring(conn, cjson.encode(t.final_response))
 
111
            conn.close()
 
112
            sys.exit(0)
 
113
        except Exception:
 
114
            # Make a JSON object full of exceptional goodness
 
115
            tb_dump = cStringIO.StringIO()
 
116
            e_type, e_val, e_tb = sys.exc_info()
 
117
            traceback.print_tb(e_tb, file=tb_dump)
 
118
            json_exc = {
 
119
                "type": e_type.__name__,
 
120
                "value": str(e_val),
 
121
                "traceback": tb_dump.getvalue()
 
122
            }
 
123
            send_netstring(conn, cjson.encode(json_exc))
 
124
            conn.close()
 
125
 
 
126
 
 
127
def chat(host, port, msg, magic, decode = True):
 
128
    sok = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
129
    sok.connect((host, port))
 
130
    sok.settimeout(SOCKETTIMEOUT)
 
131
    content = cjson.encode(msg)
 
132
    digest = hashlib.md5(content + magic).hexdigest()
 
133
    env = {'digest':digest,'content':content}
 
134
    json = cjson.encode(env)
 
135
 
 
136
    send_netstring(sok, json)
 
137
    inp = recv_netstring(sok)
 
138
 
 
139
    sok.close()
 
140
 
 
141
    if decode:
 
142
        return cjson.decode(inp)
 
143
    else:
 
144
        return inp
 
145
 
 
146
 
 
147
def send_netstring(sok, data):
 
148
    netstring = "%d:%s,"%(len(data),data)
 
149
    sok.sendall(netstring)
 
150
 
 
151
 
 
152
def recv_netstring(sok):
 
153
    # Decode netstring
 
154
    size_buffer = []
 
155
    c = sok.recv(1)
 
156
    while c != ':':
 
157
        # Limit the Netstring to less than 10^10 bytes (~1GB).
 
158
        if len(size_buffer) >= 10:
 
159
            raise ValueError("Not valid Netstring: More than 10^10 bytes")
 
160
        size_buffer.append(c)
 
161
        c = sok.recv(1)
 
162
    try:
 
163
        # Message should be length plus ',' terminator
 
164
        recv_expected = int(''.join(size_buffer)) + 1
 
165
    except ValueError, e:
 
166
        raise ValueError("Not valid Netstring: '%s'"%blk)
 
167
 
 
168
    # Read data
 
169
    buf = []
 
170
    recv_data = sok.recv(min(recv_expected, BLOCKSIZE))
 
171
    recv_size = len(recv_data)
 
172
    while recv_size < recv_expected:
 
173
        buf.append(recv_data)
 
174
        recv_data = sok.recv(min(recv_expected-recv_size, 1024))
 
175
        recv_size = recv_size + len(recv_data)
 
176
    assert(recv_size == recv_expected)
 
177
 
 
178
    # Did we receive the correct amount?
 
179
    if recv_data[-1] != ',':
 
180
        raise ValueError("Not valid Netstring: Did not end with ','")
 
181
    buf.append(recv_data[:-1])
 
182
 
 
183
    return ''.join(buf)