websocket.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. #!/usr/bin/python
  2. '''
  3. Python WebSocket library with support for "wss://" encryption.
  4. Copyright 2010 Joel Martin
  5. Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3)
  6. You can make a cert/key with openssl using:
  7. openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem
  8. as taken from http://docs.python.org/dev/library/ssl.html#certificates
  9. '''
  10. import sys, socket, ssl, struct, traceback, select
  11. import os, resource, errno, signal # daemonizing
  12. from SimpleHTTPServer import SimpleHTTPRequestHandler
  13. from cStringIO import StringIO
  14. from base64 import b64encode, b64decode
  15. try:
  16. from hashlib import md5
  17. except:
  18. from md5 import md5 # Support python 2.4
  19. from urlparse import urlsplit
  20. from cgi import parse_qsl
  21. class WebSocketServer(object):
  22. """
  23. WebSockets server class.
  24. Must be sub-classed with new_client method definition.
  25. """
  26. server_handshake = """HTTP/1.1 101 Web Socket Protocol Handshake\r
  27. Upgrade: WebSocket\r
  28. Connection: Upgrade\r
  29. %sWebSocket-Origin: %s\r
  30. %sWebSocket-Location: %s://%s%s\r
  31. %sWebSocket-Protocol: sample\r
  32. \r
  33. %s"""
  34. policy_response = """<cross-domain-policy><allow-access-from domain="*" to-ports="*" /></cross-domain-policy>\n"""
  35. class EClose(Exception):
  36. pass
  37. def __init__(self, listen_host='', listen_port=None,
  38. verbose=False, cert='', key='', ssl_only=None,
  39. daemon=False, record='', web=''):
  40. # settings
  41. self.verbose = verbose
  42. self.listen_host = listen_host
  43. self.listen_port = listen_port
  44. self.ssl_only = ssl_only
  45. self.daemon = daemon
  46. # Make paths settings absolute
  47. self.cert = os.path.abspath(cert)
  48. self.key = self.web = self.record = ''
  49. if key:
  50. self.key = os.path.abspath(key)
  51. if web:
  52. self.web = os.path.abspath(web)
  53. if record:
  54. self.record = os.path.abspath(record)
  55. if self.web:
  56. os.chdir(self.web)
  57. self.handler_id = 1
  58. print "WebSocket server settings:"
  59. print " - Listen on %s:%s" % (
  60. self.listen_host, self.listen_port)
  61. print " - Flash security policy server"
  62. if self.web:
  63. print " - Web server"
  64. if os.path.exists(self.cert):
  65. print " - SSL/TLS support"
  66. if self.ssl_only:
  67. print " - Deny non-SSL/TLS connections"
  68. else:
  69. print " - No SSL/TLS support (no cert file)"
  70. if self.daemon:
  71. print " - Backgrounding (daemon)"
  72. #
  73. # WebSocketServer static methods
  74. #
  75. @staticmethod
  76. def daemonize(self, keepfd=None):
  77. os.umask(0)
  78. if self.web:
  79. os.chdir(self.web)
  80. else:
  81. os.chdir('/')
  82. os.setgid(os.getgid()) # relinquish elevations
  83. os.setuid(os.getuid()) # relinquish elevations
  84. # Double fork to daemonize
  85. if os.fork() > 0: os._exit(0) # Parent exits
  86. os.setsid() # Obtain new process group
  87. if os.fork() > 0: os._exit(0) # Parent exits
  88. # Signal handling
  89. def terminate(a,b): os._exit(0)
  90. signal.signal(signal.SIGTERM, terminate)
  91. signal.signal(signal.SIGINT, signal.SIG_IGN)
  92. # Close open files
  93. maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
  94. if maxfd == resource.RLIM_INFINITY: maxfd = 256
  95. for fd in reversed(range(maxfd)):
  96. try:
  97. if fd != keepfd:
  98. os.close(fd)
  99. except OSError, exc:
  100. if exc.errno != errno.EBADF: raise
  101. # Redirect I/O to /dev/null
  102. os.dup2(os.open(os.devnull, os.O_RDWR), sys.stdin.fileno())
  103. os.dup2(os.open(os.devnull, os.O_RDWR), sys.stdout.fileno())
  104. os.dup2(os.open(os.devnull, os.O_RDWR), sys.stderr.fileno())
  105. @staticmethod
  106. def encode(buf):
  107. """ Encode a WebSocket packet. """
  108. buf = b64encode(buf)
  109. return "\x00%s\xff" % buf
  110. @staticmethod
  111. def decode(buf):
  112. """ Decode WebSocket packets. """
  113. if buf.count('\xff') > 1:
  114. return [b64decode(d[1:]) for d in buf.split('\xff')]
  115. else:
  116. return [b64decode(buf[1:-1])]
  117. @staticmethod
  118. def parse_handshake(handshake):
  119. """ Parse fields from client WebSockets handshake. """
  120. ret = {}
  121. req_lines = handshake.split("\r\n")
  122. if not req_lines[0].startswith("GET "):
  123. raise Exception("Invalid handshake: no GET request line")
  124. ret['path'] = req_lines[0].split(" ")[1]
  125. for line in req_lines[1:]:
  126. if line == "": break
  127. var, val = line.split(": ")
  128. ret[var] = val
  129. if req_lines[-2] == "":
  130. ret['key3'] = req_lines[-1]
  131. return ret
  132. @staticmethod
  133. def gen_md5(keys):
  134. """ Generate hash value for WebSockets handshake v76. """
  135. key1 = keys['Sec-WebSocket-Key1']
  136. key2 = keys['Sec-WebSocket-Key2']
  137. key3 = keys['key3']
  138. spaces1 = key1.count(" ")
  139. spaces2 = key2.count(" ")
  140. num1 = int("".join([c for c in key1 if c.isdigit()])) / spaces1
  141. num2 = int("".join([c for c in key2 if c.isdigit()])) / spaces2
  142. return md5(struct.pack('>II8s', num1, num2, key3)).digest()
  143. #
  144. # WebSocketServer logging/output functions
  145. #
  146. def traffic(self, token="."):
  147. """ Show traffic flow in verbose mode. """
  148. if self.verbose and not self.daemon:
  149. sys.stdout.write(token)
  150. sys.stdout.flush()
  151. def msg(self, msg):
  152. """ Output message with handler_id prefix. """
  153. if not self.daemon:
  154. print "% 3d: %s" % (self.handler_id, msg)
  155. def vmsg(self, msg):
  156. """ Same as msg() but only if verbose. """
  157. if self.verbose:
  158. self.msg(msg)
  159. #
  160. # Main WebSocketServer methods
  161. #
  162. def do_handshake(self, sock, address):
  163. """
  164. do_handshake does the following:
  165. - Peek at the first few bytes from the socket.
  166. - If the connection is Flash policy request then answer it,
  167. close the socket and return.
  168. - If the connection is an HTTPS/SSL/TLS connection then SSL
  169. wrap the socket.
  170. - Read from the (possibly wrapped) socket.
  171. - If we have received a HTTP GET request and the webserver
  172. functionality is enabled, answer it, close the socket and
  173. return.
  174. - Assume we have a WebSockets connection, parse the client
  175. handshake data.
  176. - Send a WebSockets handshake server response.
  177. - Return the socket for this WebSocket client.
  178. """
  179. stype = ""
  180. # Peek, but don't read the data
  181. handshake = sock.recv(1024, socket.MSG_PEEK)
  182. #self.msg("Handshake [%s]" % repr(handshake))
  183. if handshake == "":
  184. raise self.EClose("ignoring empty handshake")
  185. elif handshake.startswith("<policy-file-request/>"):
  186. # Answer Flash policy request
  187. handshake = sock.recv(1024)
  188. sock.send(self.policy_response)
  189. raise self.EClose("Sending flash policy response")
  190. elif handshake[0] in ("\x16", "\x80"):
  191. # SSL wrap the connection
  192. if not os.path.exists(self.cert):
  193. raise self.EClose("SSL connection but '%s' not found"
  194. % self.cert)
  195. try:
  196. retsock = ssl.wrap_socket(
  197. sock,
  198. server_side=True,
  199. certfile=self.cert,
  200. keyfile=self.key)
  201. except ssl.SSLError, x:
  202. if x.args[0] == ssl.SSL_ERROR_EOF:
  203. raise self.EClose("")
  204. else:
  205. raise
  206. scheme = "wss"
  207. stype = "SSL/TLS (wss://)"
  208. elif self.ssl_only:
  209. raise self.EClose("non-SSL connection received but disallowed")
  210. else:
  211. retsock = sock
  212. scheme = "ws"
  213. stype = "Plain non-SSL (ws://)"
  214. # Now get the data from the socket
  215. handshake = retsock.recv(4096)
  216. if len(handshake) == 0:
  217. raise self.EClose("Client closed during handshake")
  218. # Check for and handle normal web requests
  219. if handshake.startswith('GET ') and \
  220. handshake.find('Upgrade: WebSocket\r\n') == -1:
  221. if not self.web:
  222. raise self.EClose("Normal web request received but disallowed")
  223. sh = SplitHTTPHandler(handshake, retsock, address)
  224. if sh.last_code < 200 or sh.last_code >= 300:
  225. raise self.EClose(sh.last_message)
  226. elif self.verbose:
  227. raise self.EClose(sh.last_message)
  228. else:
  229. raise self.EClose("")
  230. #self.msg("handshake: " + repr(handshake))
  231. # Parse client WebSockets handshake
  232. h = self.parse_handshake(handshake)
  233. if h.get('key3'):
  234. trailer = self.gen_md5(h)
  235. pre = "Sec-"
  236. ver = 76
  237. else:
  238. trailer = ""
  239. pre = ""
  240. ver = 75
  241. self.msg("%s: %s WebSocket connection (version %s)"
  242. % (address[0], stype, ver))
  243. # Send server WebSockets handshake response
  244. response = self.server_handshake % (pre, h['Origin'], pre,
  245. scheme, h['Host'], h['path'], pre, trailer)
  246. #self.msg("sending response:", repr(response))
  247. retsock.send(response)
  248. # Return the WebSockets socket which may be SSL wrapped
  249. return retsock
  250. #
  251. # Events that can/should be overridden in sub-classes
  252. #
  253. def started(self):
  254. """ Called after WebSockets startup """
  255. self.vmsg("WebSockets server started")
  256. def poll(self):
  257. """ Run periodically while waiting for connections. """
  258. self.msg("Running poll()")
  259. def do_SIGCHLD(self, sig, stack):
  260. self.vmsg("Got SIGCHLD, ignoring")
  261. def do_SIGINT(self, sig, stack):
  262. self.msg("Got SIGINT, exiting")
  263. sys.exit(0)
  264. def new_client(self, client):
  265. """ Do something with a WebSockets client connection. """
  266. raise("WebSocketServer.new_client() must be overloaded")
  267. def start_server(self):
  268. """
  269. Daemonize if requested. Listen for for connections. Run
  270. do_handshake() method for each connection. If the connection
  271. is a WebSockets client then call new_client() method (which must
  272. be overridden) for each new client connection.
  273. """
  274. lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  275. lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  276. lsock.bind((self.listen_host, self.listen_port))
  277. lsock.listen(100)
  278. if self.daemon:
  279. self.daemonize(self, keepfd=lsock.fileno())
  280. self.started() # Some things need to happen after daemonizing
  281. # Reep zombies
  282. signal.signal(signal.SIGCHLD, self.do_SIGCHLD)
  283. signal.signal(signal.SIGINT, self.do_SIGINT)
  284. while True:
  285. try:
  286. try:
  287. csock = startsock = None
  288. pid = err = 0
  289. try:
  290. self.poll()
  291. ready = select.select([lsock], [], [], 1)[0];
  292. if lsock in ready:
  293. startsock, address = lsock.accept()
  294. else:
  295. continue
  296. except Exception, exc:
  297. if hasattr(exc, 'errno'):
  298. err = exc.errno
  299. else:
  300. err = exc[0]
  301. if err == errno.EINTR:
  302. self.vmsg("Ignoring interrupted syscall")
  303. continue
  304. else:
  305. raise
  306. self.vmsg('%s: forking handler' % address[0])
  307. pid = os.fork()
  308. if pid == 0:
  309. # handler process
  310. csock = self.do_handshake(startsock, address)
  311. self.new_client(csock)
  312. else:
  313. # parent process
  314. self.handler_id += 1
  315. except self.EClose, exc:
  316. # Connection was not a WebSockets connection
  317. if exc.args[0]:
  318. self.msg("%s: %s" % (address[0], exc.args[0]))
  319. except KeyboardInterrupt, exc:
  320. pass
  321. except Exception, exc:
  322. self.msg("handler exception: %s" % str(exc))
  323. if self.verbose:
  324. self.msg(traceback.format_exc())
  325. finally:
  326. if csock and csock != startsock:
  327. csock.close()
  328. if startsock:
  329. startsock.close()
  330. if pid == 0:
  331. break # Child process exits
  332. # HTTP handler with request from a string and response to a socket
  333. class SplitHTTPHandler(SimpleHTTPRequestHandler):
  334. def __init__(self, req, resp, addr):
  335. # Save the response socket
  336. self.response = resp
  337. SimpleHTTPRequestHandler.__init__(self, req, addr, object())
  338. def setup(self):
  339. self.connection = self.response
  340. # Duck type request string to file object
  341. self.rfile = StringIO(self.request)
  342. self.wfile = self.connection.makefile('wb', self.wbufsize)
  343. def send_response(self, code, message=None):
  344. # Save the status code
  345. self.last_code = code
  346. SimpleHTTPRequestHandler.send_response(self, code, message)
  347. def log_message(self, f, *args):
  348. # Save instead of printing
  349. self.last_message = f % args