7 from processor import Session, Dispatcher, print_log
9 class TcpSession(Session):
11 def __init__(self, connection, address, use_ssl, ssl_certfile, ssl_keyfile):
12 Session.__init__(self)
15 self._connection = ssl.wrap_socket(
18 certfile=ssl_certfile,
20 ssl_version=ssl.PROTOCOL_SSLv23)
22 self._connection = connection
24 self.address = address[0]
29 raise Exception("Session was stopped")
31 return self._connection
34 self._connection.close()
35 #print "Terminating connection:", self.address
39 def send_response(self, response):
40 data = json.dumps(response) + "\n"
41 # Possible race condition here by having session
43 # I assume Python connections are thread safe interfaces
45 connection = self.connection()
47 l = connection.send(data)
54 class TcpClientRequestor(threading.Thread):
56 def __init__(self, dispatcher, session):
57 self.shared = dispatcher.shared
58 self.dispatcher = dispatcher
60 self.session = session
61 threading.Thread.__init__(self)
64 while not self.shared.stopped():
68 self.session.time = time.time()
85 return self.session.connection().recv(2048)
90 raw_buffer = self.message.find('\n')
94 raw_command = self.message[0:raw_buffer].strip()
95 self.message = self.message[raw_buffer + 1:]
96 if raw_command == 'quit':
101 command = json.loads(raw_command)
103 self.dispatcher.push_response({"error": "bad JSON", "request": raw_command})
107 # Try to load vital fields, and return an error if
109 message_id = command['id']
110 method = command['method']
112 # Return an error JSON in response.
113 self.dispatcher.push_response({"error": "syntax error", "request": raw_command})
115 self.dispatcher.push_request(self.session,command)
119 class TcpServer(threading.Thread):
121 def __init__(self, dispatcher, host, port, use_ssl, ssl_certfile, ssl_keyfile):
122 self.shared = dispatcher.shared
123 self.dispatcher = dispatcher.request_dispatcher
124 threading.Thread.__init__(self)
128 self.lock = threading.Lock()
129 self.use_ssl = use_ssl
130 self.ssl_keyfile = ssl_keyfile
131 self.ssl_certfile = ssl_certfile
135 print_log( "TCP/SSL server started.")
137 print_log( "TCP server started.")
138 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
139 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
140 sock.bind((self.host, self.port))
142 while not self.shared.stopped():
143 session = TcpSession(*sock.accept(), use_ssl=self.use_ssl, ssl_certfile=self.ssl_certfile, ssl_keyfile=self.ssl_keyfile)
144 self.dispatcher.add_session(session)
145 self.dispatcher.collect_garbage()
146 client_req = TcpClientRequestor(self.dispatcher, session)