websocket.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. #!/usr/bin/python
  2. '''
  3. Python WebSocket library with support for "wss://" encryption.
  4. Copyright 2010 Joel Martin
  5. Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3)
  6. You can make a cert/key with openssl using:
  7. openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem
  8. as taken from http://docs.python.org/dev/library/ssl.html#certificates
  9. '''
  10. import sys, socket, ssl, struct, traceback
  11. import os, resource, errno, signal # daemonizing
  12. from SimpleHTTPServer import SimpleHTTPRequestHandler
  13. from cStringIO import StringIO
  14. from base64 import b64encode, b64decode
  15. try:
  16. from hashlib import md5
  17. except:
  18. from md5 import md5 # Support python 2.4
  19. from urlparse import urlsplit
  20. from cgi import parse_qsl
  21. class WebSocketServer():
  22. """
  23. WebSockets server class.
  24. Must be sub-classed with handler method definition.
  25. """
  26. server_handshake = """HTTP/1.1 101 Web Socket Protocol Handshake\r
  27. Upgrade: WebSocket\r
  28. Connection: Upgrade\r
  29. %sWebSocket-Origin: %s\r
  30. %sWebSocket-Location: %s://%s%s\r
  31. %sWebSocket-Protocol: sample\r
  32. \r
  33. %s"""
  34. policy_response = """<cross-domain-policy><allow-access-from domain="*" to-ports="*" /></cross-domain-policy>\n"""
  35. class EClose(Exception):
  36. pass
  37. def __init__(self, listen_host='', listen_port=None,
  38. verbose=False, cert='', key='', ssl_only=None,
  39. daemon=False, record='', web=''):
  40. # settings
  41. self.verbose = verbose
  42. self.listen_host = listen_host
  43. self.listen_port = listen_port
  44. self.ssl_only = ssl_only
  45. self.daemon = daemon
  46. # Make paths settings absolute
  47. self.cert = os.path.abspath(cert)
  48. self.key = self.web = self.record = ''
  49. if key:
  50. self.key = os.path.abspath(key)
  51. if web:
  52. self.web = os.path.abspath(web)
  53. if record:
  54. self.record = os.path.abspath(record)
  55. if self.web:
  56. os.chdir(self.web)
  57. self.handler_id = 1
  58. #
  59. # WebSocketServer static methods
  60. #
  61. @staticmethod
  62. def daemonize(self, keepfd=None):
  63. os.umask(0)
  64. if self.web:
  65. os.chdir(self.web)
  66. else:
  67. os.chdir('/')
  68. os.setgid(os.getgid()) # relinquish elevations
  69. os.setuid(os.getuid()) # relinquish elevations
  70. # Double fork to daemonize
  71. if os.fork() > 0: os._exit(0) # Parent exits
  72. os.setsid() # Obtain new process group
  73. if os.fork() > 0: os._exit(0) # Parent exits
  74. # Signal handling
  75. def terminate(a,b): os._exit(0)
  76. signal.signal(signal.SIGTERM, terminate)
  77. signal.signal(signal.SIGINT, signal.SIG_IGN)
  78. # Close open files
  79. maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
  80. if maxfd == resource.RLIM_INFINITY: maxfd = 256
  81. for fd in reversed(range(maxfd)):
  82. try:
  83. if fd != keepfd:
  84. os.close(fd)
  85. except OSError, exc:
  86. if exc.errno != errno.EBADF: raise
  87. # Redirect I/O to /dev/null
  88. os.dup2(os.open(os.devnull, os.O_RDWR), sys.stdin.fileno())
  89. os.dup2(os.open(os.devnull, os.O_RDWR), sys.stdout.fileno())
  90. os.dup2(os.open(os.devnull, os.O_RDWR), sys.stderr.fileno())
  91. @staticmethod
  92. def encode(buf):
  93. """ Encode a WebSocket packet. """
  94. buf = b64encode(buf)
  95. return "\x00%s\xff" % buf
  96. @staticmethod
  97. def decode(buf):
  98. """ Decode WebSocket packets. """
  99. if buf.count('\xff') > 1:
  100. return [b64decode(d[1:]) for d in buf.split('\xff')]
  101. else:
  102. return [b64decode(buf[1:-1])]
  103. @staticmethod
  104. def parse_handshake(handshake):
  105. """ Parse fields from client WebSockets handshake. """
  106. ret = {}
  107. req_lines = handshake.split("\r\n")
  108. if not req_lines[0].startswith("GET "):
  109. raise Exception("Invalid handshake: no GET request line")
  110. ret['path'] = req_lines[0].split(" ")[1]
  111. for line in req_lines[1:]:
  112. if line == "": break
  113. var, val = line.split(": ")
  114. ret[var] = val
  115. if req_lines[-2] == "":
  116. ret['key3'] = req_lines[-1]
  117. return ret
  118. @staticmethod
  119. def gen_md5(keys):
  120. """ Generate hash value for WebSockets handshake v76. """
  121. key1 = keys['Sec-WebSocket-Key1']
  122. key2 = keys['Sec-WebSocket-Key2']
  123. key3 = keys['key3']
  124. spaces1 = key1.count(" ")
  125. spaces2 = key2.count(" ")
  126. num1 = int("".join([c for c in key1 if c.isdigit()])) / spaces1
  127. num2 = int("".join([c for c in key2 if c.isdigit()])) / spaces2
  128. return md5(struct.pack('>II8s', num1, num2, key3)).digest()
  129. #
  130. # WebSocketServer logging/output functions
  131. #
  132. def traffic(self, token="."):
  133. """ Show traffic flow in verbose mode. """
  134. if self.verbose and not self.daemon:
  135. sys.stdout.write(token)
  136. sys.stdout.flush()
  137. def msg(self, msg):
  138. """ Output message with handler_id prefix. """
  139. if not self.daemon:
  140. print "% 3d: %s" % (self.handler_id, msg)
  141. def vmsg(self, msg):
  142. """ Same as msg() but only if verbose. """
  143. if self.verbose:
  144. self.msg(msg)
  145. #
  146. # Main WebSocketServer methods
  147. #
  148. def do_handshake(self, sock, address):
  149. """
  150. do_handshake does the following:
  151. - Peek at the first few bytes from the socket.
  152. - If the connection is Flash policy request then answer it,
  153. close the socket and return.
  154. - If the connection is an HTTPS/SSL/TLS connection then SSL
  155. wrap the socket.
  156. - Read from the (possibly wrapped) socket.
  157. - If we have received a HTTP GET request and the webserver
  158. functionality is enabled, answer it, close the socket and
  159. return.
  160. - Assume we have a WebSockets connection, parse the client
  161. handshake data.
  162. - Send a WebSockets handshake server response.
  163. - Return the socket for this WebSocket client.
  164. """
  165. stype = ""
  166. # Peek, but don't read the data
  167. handshake = sock.recv(1024, socket.MSG_PEEK)
  168. #self.msg("Handshake [%s]" % repr(handshake))
  169. if handshake == "":
  170. raise self.EClose("ignoring empty handshake")
  171. elif handshake.startswith("<policy-file-request/>"):
  172. # Answer Flash policy request
  173. handshake = sock.recv(1024)
  174. sock.send(self.policy_response)
  175. raise self.EClose("Sending flash policy response")
  176. elif handshake[0] in ("\x16", "\x80"):
  177. # SSL wrap the connection
  178. if not os.path.exists(self.cert):
  179. raise self.EClose("SSL connection but '%s' not found"
  180. % self.cert)
  181. try:
  182. retsock = ssl.wrap_socket(
  183. sock,
  184. server_side=True,
  185. certfile=self.cert,
  186. keyfile=self.key)
  187. except ssl.SSLError, x:
  188. if x.args[0] == ssl.SSL_ERROR_EOF:
  189. raise self.EClose("")
  190. else:
  191. raise
  192. scheme = "wss"
  193. stype = "SSL/TLS (wss://)"
  194. elif self.ssl_only:
  195. raise self.EClose("non-SSL connection received but disallowed")
  196. else:
  197. retsock = sock
  198. scheme = "ws"
  199. stype = "Plain non-SSL (ws://)"
  200. # Now get the data from the socket
  201. handshake = retsock.recv(4096)
  202. #self.msg("handshake: " + repr(handshake))
  203. if len(handshake) == 0:
  204. raise self.EClose("Client closed during handshake")
  205. # Check for and handle normal web requests
  206. if handshake.startswith('GET ') and \
  207. handshake.find('Upgrade: WebSocket\r\n') == -1:
  208. if not self.web:
  209. raise self.EClose("Normal web request received but disallowed")
  210. sh = SplitHTTPHandler(handshake, retsock, address)
  211. if sh.last_code < 200 or sh.last_code >= 300:
  212. raise self.EClose(sh.last_message)
  213. elif self.verbose:
  214. raise self.EClose(sh.last_message)
  215. else:
  216. raise self.EClose("")
  217. # Parse client WebSockets handshake
  218. h = self.parse_handshake(handshake)
  219. if h.get('key3'):
  220. trailer = self.gen_md5(h)
  221. pre = "Sec-"
  222. ver = 76
  223. else:
  224. trailer = ""
  225. pre = ""
  226. ver = 75
  227. self.msg("%s: %s WebSocket connection (version %s)"
  228. % (address[0], stype, ver))
  229. # Send server WebSockets handshake response
  230. response = self.server_handshake % (pre, h['Origin'], pre,
  231. scheme, h['Host'], h['path'], pre, trailer)
  232. #self.msg("sending response:", repr(response))
  233. retsock.send(response)
  234. # Return the WebSockets socket which may be SSL wrapped
  235. return retsock
  236. def handler(self, client):
  237. """ Do something with a WebSockets client connection. """
  238. raise("WebSocketServer.handler() must be overloaded")
  239. def start_server(self):
  240. """
  241. Daemonize if requested. Listen for for connections. Run
  242. do_handshake() method for each connection. If the connection
  243. is a WebSockets client then call handler() method (which must
  244. be overridden) for each connection.
  245. """
  246. lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  247. lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  248. lsock.bind((self.listen_host, self.listen_port))
  249. lsock.listen(100)
  250. print "WebSocket server settings:"
  251. print " - Listening on %s:%s" % (
  252. self.listen_host, self.listen_port)
  253. if self.daemon:
  254. print " - Backgrounding (daemon)"
  255. print " - Flash security policy server"
  256. if self.web:
  257. print " - Web server"
  258. if os.path.exists(self.cert):
  259. print " - SSL/TLS support"
  260. if self.ssl_only:
  261. print " - Deny non-SSL/TLS connections"
  262. if self.daemon:
  263. self.daemonize(self, keepfd=lsock.fileno())
  264. # Reep zombies
  265. signal.signal(signal.SIGCHLD, signal.SIG_IGN)
  266. while True:
  267. try:
  268. csock = startsock = None
  269. pid = 0
  270. startsock, address = lsock.accept()
  271. self.vmsg('%s: forking handler' % address[0])
  272. pid = os.fork()
  273. if pid == 0:
  274. # handler process
  275. csock = self.do_handshake(startsock, address)
  276. self.handler(csock)
  277. else:
  278. # parent process
  279. self.handler_id += 1
  280. except self.EClose, exc:
  281. # Connection was not a WebSockets connection
  282. if exc.args[0]:
  283. self.msg("%s: %s" % (address[0], exc.args[0]))
  284. except KeyboardInterrupt, exc:
  285. pass
  286. except Exception, exc:
  287. self.msg("handler exception: %s" % str(exc))
  288. if self.verbose:
  289. self.msg(traceback.format_exc())
  290. finally:
  291. if csock and csock != startsock:
  292. csock.close()
  293. if startsock:
  294. startsock.close()
  295. if pid == 0:
  296. break # Child process exits
  297. # HTTP handler with request from a string and response to a socket
  298. class SplitHTTPHandler(SimpleHTTPRequestHandler):
  299. def __init__(self, req, resp, addr):
  300. # Save the response socket
  301. self.response = resp
  302. SimpleHTTPRequestHandler.__init__(self, req, addr, object())
  303. def setup(self):
  304. self.connection = self.response
  305. # Duck type request string to file object
  306. self.rfile = StringIO(self.request)
  307. self.wfile = self.connection.makefile('wb', self.wbufsize)
  308. def send_response(self, code, message=None):
  309. # Save the status code
  310. self.last_code = code
  311. SimpleHTTPRequestHandler.send_response(self, code, message)
  312. def log_message(self, f, *args):
  313. # Save instead of printing
  314. self.last_message = f % args