websocket.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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 base64 import b64encode, b64decode
  13. try:
  14. from hashlib import md5
  15. except:
  16. from md5 import md5 # Support python 2.4
  17. from urlparse import urlsplit
  18. from cgi import parse_qsl
  19. settings = {
  20. 'listen_host' : '',
  21. 'listen_port' : None,
  22. 'handler' : None,
  23. 'handler_id' : 1,
  24. 'cert' : None,
  25. 'ssl_only' : False,
  26. 'daemon' : True,
  27. 'multiprocess': False,
  28. 'record' : None, }
  29. server_handshake = """HTTP/1.1 101 Web Socket Protocol Handshake\r
  30. Upgrade: WebSocket\r
  31. Connection: Upgrade\r
  32. %sWebSocket-Origin: %s\r
  33. %sWebSocket-Location: %s://%s%s\r
  34. %sWebSocket-Protocol: sample\r
  35. \r
  36. %s"""
  37. policy_response = """<cross-domain-policy><allow-access-from domain="*" to-ports="*" /></cross-domain-policy>\n"""
  38. class EClose(Exception):
  39. pass
  40. def traffic(token="."):
  41. if not settings['daemon'] and not settings['multiprocess']:
  42. sys.stdout.write(token)
  43. sys.stdout.flush()
  44. def handler_msg(msg):
  45. if not settings['daemon']:
  46. if settings['multiprocess']:
  47. print " %d: %s" % (settings['handler_id'], msg)
  48. else:
  49. print " %s" % msg
  50. def encode(buf):
  51. buf = b64encode(buf)
  52. return "\x00%s\xff" % buf
  53. def decode(buf):
  54. """ Parse out WebSocket packets. """
  55. if buf.count('\xff') > 1:
  56. return [b64decode(d[1:]) for d in buf.split('\xff')]
  57. else:
  58. return [b64decode(buf[1:-1])]
  59. def parse_handshake(handshake):
  60. ret = {}
  61. req_lines = handshake.split("\r\n")
  62. if not req_lines[0].startswith("GET "):
  63. raise Exception("Invalid handshake: no GET request line")
  64. ret['path'] = req_lines[0].split(" ")[1]
  65. for line in req_lines[1:]:
  66. if line == "": break
  67. var, val = line.split(": ")
  68. ret[var] = val
  69. if req_lines[-2] == "":
  70. ret['key3'] = req_lines[-1]
  71. return ret
  72. def gen_md5(keys):
  73. key1 = keys['Sec-WebSocket-Key1']
  74. key2 = keys['Sec-WebSocket-Key2']
  75. key3 = keys['key3']
  76. spaces1 = key1.count(" ")
  77. spaces2 = key2.count(" ")
  78. num1 = int("".join([c for c in key1 if c.isdigit()])) / spaces1
  79. num2 = int("".join([c for c in key2 if c.isdigit()])) / spaces2
  80. return md5(struct.pack('>II8s', num1, num2, key3)).digest()
  81. def do_handshake(sock):
  82. # Peek, but don't read the data
  83. handshake = sock.recv(1024, socket.MSG_PEEK)
  84. #handler_msg("Handshake [%s]" % repr(handshake))
  85. if handshake == "":
  86. handler_msg("ignoring empty handshake")
  87. sock.close()
  88. return False
  89. elif handshake.startswith("<policy-file-request/>"):
  90. handshake = sock.recv(1024)
  91. handler_msg("Sending flash policy response")
  92. sock.send(policy_response)
  93. sock.close()
  94. return False
  95. elif handshake.startswith("\x16"):
  96. retsock = ssl.wrap_socket(
  97. sock,
  98. server_side=True,
  99. certfile=settings['cert'],
  100. ssl_version=ssl.PROTOCOL_TLSv1)
  101. scheme = "wss"
  102. handler_msg("using SSL/TLS")
  103. elif settings['ssl_only']:
  104. handler_msg("non-SSL connection disallowed")
  105. sock.close()
  106. return False
  107. else:
  108. retsock = sock
  109. scheme = "ws"
  110. handler_msg("using plain (not SSL) socket")
  111. handshake = retsock.recv(4096)
  112. #handler_msg("handshake: " + repr(handshake))
  113. h = parse_handshake(handshake)
  114. if h.get('key3'):
  115. trailer = gen_md5(h)
  116. pre = "Sec-"
  117. handler_msg("using protocol version 76")
  118. else:
  119. trailer = ""
  120. pre = ""
  121. handler_msg("using protocol version 75")
  122. response = server_handshake % (pre, h['Origin'], pre, scheme,
  123. h['Host'], h['path'], pre, trailer)
  124. #handler_msg("sending response:", repr(response))
  125. retsock.send(response)
  126. return retsock
  127. def daemonize(keepfd=None):
  128. os.umask(0)
  129. os.chdir('/')
  130. os.setgid(os.getgid()) # relinquish elevations
  131. os.setuid(os.getuid()) # relinquish elevations
  132. # Double fork to daemonize
  133. if os.fork() > 0: os._exit(0) # Parent exits
  134. os.setsid() # Obtain new process group
  135. if os.fork() > 0: os._exit(0) # Parent exits
  136. # Signal handling
  137. def terminate(a,b): os._exit(0)
  138. signal.signal(signal.SIGTERM, terminate)
  139. signal.signal(signal.SIGINT, signal.SIG_IGN)
  140. # Close open files
  141. maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
  142. if maxfd == resource.RLIM_INFINITY: maxfd = 256
  143. for fd in reversed(range(maxfd)):
  144. try:
  145. if fd != keepfd:
  146. os.close(fd)
  147. else:
  148. print "Keeping fd: %d" % fd
  149. except OSError, exc:
  150. if exc.errno != errno.EBADF: raise
  151. # Redirect I/O to /dev/null
  152. os.dup2(os.open(os.devnull, os.O_RDWR), sys.stdin.fileno())
  153. os.dup2(os.open(os.devnull, os.O_RDWR), sys.stdout.fileno())
  154. os.dup2(os.open(os.devnull, os.O_RDWR), sys.stderr.fileno())
  155. def start_server():
  156. lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  157. lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  158. lsock.bind((settings['listen_host'], settings['listen_port']))
  159. lsock.listen(100)
  160. if settings['daemon']:
  161. daemonize(keepfd=lsock.fileno())
  162. if settings['multiprocess']:
  163. print 'Waiting for connections on %s:%s' % (
  164. settings['listen_host'], settings['listen_port'])
  165. # Reep zombies
  166. signal.signal(signal.SIGCHLD, signal.SIG_IGN)
  167. while True:
  168. try:
  169. csock = startsock = None
  170. pid = 0
  171. if not settings['multiprocess']:
  172. print 'Waiting for connection on %s:%s' % (
  173. settings['listen_host'], settings['listen_port'])
  174. startsock, address = lsock.accept()
  175. handler_msg('got client connection from %s' % address[0])
  176. if settings['multiprocess']:
  177. handler_msg("forking handler process")
  178. pid = os.fork()
  179. if pid == 0: # handler process
  180. csock = do_handshake(startsock)
  181. if not csock:
  182. if settings['multiprocess']:
  183. handler_msg("No connection after handshake");
  184. break
  185. else:
  186. continue
  187. settings['handler'](csock)
  188. else: # parent process
  189. settings['handler_id'] += 1
  190. except EClose, exc:
  191. handler_msg("handler exit: %s" % exc.args)
  192. except Exception, exc:
  193. handler_msg("handler exception: %s" % str(exc))
  194. #handler_msg(traceback.format_exc())
  195. if pid == 0:
  196. if csock: csock.close()
  197. if startsock and startsock != csock: startsock.close()
  198. if settings['multiprocess']: break # Child process exits