websocket.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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, ssl_only=False):
  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. elif ssl_only:
  70. print "Non-SSL connection disallowed"
  71. sock.close()
  72. return False
  73. else:
  74. retsock = sock
  75. scheme = "ws"
  76. print "Using plain (not SSL) socket"
  77. handshake = retsock.recv(4096)
  78. req_lines = handshake.split("\r\n")
  79. _, path, _ = req_lines[0].split(" ")
  80. _, origin = req_lines[4].split(" ")
  81. _, host = req_lines[3].split(" ")
  82. # Parse settings from the path
  83. cvars = path.partition('?')[2].partition('#')[0].split('&')
  84. client_settings = {'b64encode': None, 'seq_num': None}
  85. for cvar in [c for c in cvars if c]:
  86. name, _, value = cvar.partition('=')
  87. client_settings[name] = value and value or True
  88. print "client_settings:", client_settings
  89. retsock.send(server_handshake % (origin, scheme, host, path))
  90. return retsock
  91. def start_server(listen_port, handler, listen_host='', ssl_only=False):
  92. lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  93. lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  94. lsock.bind((listen_host, listen_port))
  95. lsock.listen(100)
  96. while True:
  97. try:
  98. csock = None
  99. print 'waiting for connection on port %s' % listen_port
  100. startsock, address = lsock.accept()
  101. print 'Got client connection from %s' % address[0]
  102. csock = do_handshake(startsock, ssl_only=ssl_only)
  103. if not csock: continue
  104. handler(csock)
  105. except Exception:
  106. print "Ignoring exception:"
  107. print traceback.format_exc()
  108. if csock: csock.close()