websocket.py 6.6 KB

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