websocket.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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, traceback
  9. from base64 import b64encode, b64decode
  10. client_settings = {}
  11. send_seq = 0
  12. server_handshake = """HTTP/1.1 101 Web Socket Protocol Handshake\r
  13. Upgrade: WebSocket\r
  14. Connection: Upgrade\r
  15. WebSocket-Origin: %s\r
  16. WebSocket-Location: %s://%s%s\r
  17. WebSocket-Protocol: sample\r
  18. \r
  19. """
  20. policy_response = """<cross-domain-policy><allow-access-from domain="*" to-ports="*" /></cross-domain-policy>\n"""
  21. def traffic(token="."):
  22. sys.stdout.write(token)
  23. sys.stdout.flush()
  24. def decode(buf):
  25. """ Parse out WebSocket packets. """
  26. if buf.count('\xff') > 1:
  27. if client_settings["b64encode"]:
  28. return [b64decode(d[1:]) for d in buf.split('\xff')]
  29. else:
  30. # Modified UTF-8 decode
  31. return [d[1:].replace("\xc4\x80", "\x00").decode('utf-8').encode('latin-1') for d in buf.split('\xff')]
  32. else:
  33. if client_settings["b64encode"]:
  34. return [b64decode(buf[1:-1])]
  35. else:
  36. return [buf[1:-1].replace("\xc4\x80", "\x00").decode('utf-8').encode('latin-1')]
  37. def encode(buf):
  38. global send_seq
  39. if client_settings["b64encode"]:
  40. buf = b64encode(buf)
  41. else:
  42. # Modified UTF-8 encode
  43. buf = buf.decode('latin-1').encode('utf-8').replace("\x00", "\xc4\x80")
  44. if client_settings["seq_num"]:
  45. send_seq += 1
  46. return "\x00%d:%s\xff" % (send_seq-1, buf)
  47. else:
  48. return "\x00%s\xff" % buf
  49. def do_handshake(sock):
  50. global client_settings, send_seq
  51. send_seq = 0
  52. # Peek, but don't read the data
  53. handshake = sock.recv(1024, socket.MSG_PEEK)
  54. #print "Handshake [%s]" % repr(handshake)
  55. if handshake.startswith("<policy-file-request/>"):
  56. handshake = sock.recv(1024)
  57. print "Sending flash policy response"
  58. sock.send(policy_response)
  59. sock.close()
  60. return False
  61. elif handshake.startswith("\x16"):
  62. retsock = ssl.wrap_socket(
  63. sock,
  64. server_side=True,
  65. certfile='self.pem',
  66. ssl_version=ssl.PROTOCOL_TLSv1)
  67. scheme = "wss"
  68. print "Using SSL/TLS"
  69. else:
  70. retsock = sock
  71. scheme = "ws"
  72. print "Using plain (not SSL) socket"
  73. handshake = retsock.recv(4096)
  74. req_lines = handshake.split("\r\n")
  75. _, path, _ = req_lines[0].split(" ")
  76. _, origin = req_lines[4].split(" ")
  77. _, host = req_lines[3].split(" ")
  78. # Parse settings from the path
  79. cvars = path.partition('?')[2].partition('#')[0].split('&')
  80. client_settings = {'b64encode': None, 'seq_num': None}
  81. for cvar in [c for c in cvars if c]:
  82. name, _, value = cvar.partition('=')
  83. client_settings[name] = value and value or True
  84. print "client_settings:", client_settings
  85. retsock.send(server_handshake % (origin, scheme, host, path))
  86. return retsock
  87. def start_server(listen_port, handler, listen_host=''):
  88. lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  89. lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  90. lsock.bind((listen_host, listen_port))
  91. lsock.listen(100)
  92. while True:
  93. try:
  94. csock = None
  95. print 'waiting for connection on port %s' % listen_port
  96. startsock, address = lsock.accept()
  97. print 'Got client connection from %s' % address[0]
  98. csock = do_handshake(startsock)
  99. if not csock: continue
  100. handler(csock)
  101. except Exception:
  102. print "Ignoring exception:"
  103. print traceback.format_exc()
  104. if csock: csock.close()