websocket.py 6.4 KB

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