websocket.py 6.4 KB

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