websocket.py 5.4 KB

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