websocket.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. #!/usr/bin/env 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. try:
  128. var, val = line.split(": ")
  129. except:
  130. raise Exception("Invalid handshake header: %s" % line)
  131. ret[var] = val
  132. if req_lines[-2] == "":
  133. ret['key3'] = req_lines[-1]
  134. return ret
  135. @staticmethod
  136. def gen_md5(keys):
  137. """ Generate hash value for WebSockets handshake v76. """
  138. key1 = keys['Sec-WebSocket-Key1']
  139. key2 = keys['Sec-WebSocket-Key2']
  140. key3 = keys['key3']
  141. spaces1 = key1.count(" ")
  142. spaces2 = key2.count(" ")
  143. num1 = int("".join([c for c in key1 if c.isdigit()])) / spaces1
  144. num2 = int("".join([c for c in key2 if c.isdigit()])) / spaces2
  145. return md5(struct.pack('>II8s', num1, num2, key3)).digest()
  146. #
  147. # WebSocketServer logging/output functions
  148. #
  149. def traffic(self, token="."):
  150. """ Show traffic flow in verbose mode. """
  151. if self.verbose and not self.daemon:
  152. sys.stdout.write(token)
  153. sys.stdout.flush()
  154. def msg(self, msg):
  155. """ Output message with handler_id prefix. """
  156. if not self.daemon:
  157. print "% 3d: %s" % (self.handler_id, msg)
  158. def vmsg(self, msg):
  159. """ Same as msg() but only if verbose. """
  160. if self.verbose:
  161. self.msg(msg)
  162. #
  163. # Main WebSocketServer methods
  164. #
  165. def do_handshake(self, sock, address):
  166. """
  167. do_handshake does the following:
  168. - Peek at the first few bytes from the socket.
  169. - If the connection is Flash policy request then answer it,
  170. close the socket and return.
  171. - If the connection is an HTTPS/SSL/TLS connection then SSL
  172. wrap the socket.
  173. - Read from the (possibly wrapped) socket.
  174. - If we have received a HTTP GET request and the webserver
  175. functionality is enabled, answer it, close the socket and
  176. return.
  177. - Assume we have a WebSockets connection, parse the client
  178. handshake data.
  179. - Send a WebSockets handshake server response.
  180. - Return the socket for this WebSocket client.
  181. """
  182. stype = ""
  183. ready = select.select([sock], [], [], 3)[0]
  184. if not ready:
  185. raise self.EClose("ignoring socket not ready")
  186. # Peek, but do not read the data so that we have a opportunity
  187. # to SSL wrap the socket first
  188. handshake = sock.recv(1024, socket.MSG_PEEK)
  189. #self.msg("Handshake [%s]" % repr(handshake))
  190. if handshake == "":
  191. raise self.EClose("ignoring empty handshake")
  192. elif handshake.startswith("<policy-file-request/>"):
  193. # Answer Flash policy request
  194. handshake = sock.recv(1024)
  195. sock.send(self.policy_response)
  196. raise self.EClose("Sending flash policy response")
  197. elif handshake[0] in ("\x16", "\x80"):
  198. # SSL wrap the connection
  199. if not os.path.exists(self.cert):
  200. raise self.EClose("SSL connection but '%s' not found"
  201. % self.cert)
  202. try:
  203. retsock = ssl.wrap_socket(
  204. sock,
  205. server_side=True,
  206. certfile=self.cert,
  207. keyfile=self.key)
  208. except ssl.SSLError, x:
  209. if x.args[0] == ssl.SSL_ERROR_EOF:
  210. raise self.EClose("")
  211. else:
  212. raise
  213. scheme = "wss"
  214. stype = "SSL/TLS (wss://)"
  215. elif self.ssl_only:
  216. raise self.EClose("non-SSL connection received but disallowed")
  217. else:
  218. retsock = sock
  219. scheme = "ws"
  220. stype = "Plain non-SSL (ws://)"
  221. # Now get the data from the socket
  222. handshake = retsock.recv(4096)
  223. if len(handshake) == 0:
  224. raise self.EClose("Client closed during handshake")
  225. # Check for and handle normal web requests
  226. if handshake.startswith('GET ') and \
  227. handshake.find('Upgrade: WebSocket\r\n') == -1:
  228. if not self.web:
  229. raise self.EClose("Normal web request received but disallowed")
  230. sh = SplitHTTPHandler(handshake, retsock, address)
  231. if sh.last_code < 200 or sh.last_code >= 300:
  232. raise self.EClose(sh.last_message)
  233. elif self.verbose:
  234. raise self.EClose(sh.last_message)
  235. else:
  236. raise self.EClose("")
  237. #self.msg("handshake: " + repr(handshake))
  238. # Parse client WebSockets handshake
  239. h = self.parse_handshake(handshake)
  240. if h.get('key3'):
  241. trailer = self.gen_md5(h)
  242. pre = "Sec-"
  243. ver = 76
  244. else:
  245. trailer = ""
  246. pre = ""
  247. ver = 75
  248. self.msg("%s: %s WebSocket connection (version %s)"
  249. % (address[0], stype, ver))
  250. # Send server WebSockets handshake response
  251. response = self.server_handshake % (pre, h['Origin'], pre,
  252. scheme, h['Host'], h['path'], pre, trailer)
  253. #self.msg("sending response:", repr(response))
  254. retsock.send(response)
  255. # Return the WebSockets socket which may be SSL wrapped
  256. return retsock
  257. #
  258. # Events that can/should be overridden in sub-classes
  259. #
  260. def started(self):
  261. """ Called after WebSockets startup """
  262. self.vmsg("WebSockets server started")
  263. def poll(self):
  264. """ Run periodically while waiting for connections. """
  265. #self.vmsg("Running poll()")
  266. pass
  267. def top_SIGCHLD(self, sig, stack):
  268. # Reap zombies after calling child SIGCHLD handler
  269. self.do_SIGCHLD(sig, stack)
  270. self.vmsg("Got SIGCHLD, reaping zombies")
  271. try:
  272. result = os.waitpid(-1, os.WNOHANG)
  273. while result[0]:
  274. self.vmsg("Reaped child process %s" % result[0])
  275. result = os.waitpid(-1, os.WNOHANG)
  276. except (OSError):
  277. pass
  278. def do_SIGCHLD(self, sig, stack):
  279. pass
  280. def do_SIGINT(self, sig, stack):
  281. self.msg("Got SIGINT, exiting")
  282. sys.exit(0)
  283. def new_client(self, client):
  284. """ Do something with a WebSockets client connection. """
  285. raise("WebSocketServer.new_client() must be overloaded")
  286. def start_server(self):
  287. """
  288. Daemonize if requested. Listen for for connections. Run
  289. do_handshake() method for each connection. If the connection
  290. is a WebSockets client then call new_client() method (which must
  291. be overridden) for each new client connection.
  292. """
  293. lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  294. lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  295. lsock.bind((self.listen_host, self.listen_port))
  296. lsock.listen(100)
  297. if self.daemon:
  298. self.daemonize(self, keepfd=lsock.fileno())
  299. self.started() # Some things need to happen after daemonizing
  300. # Reep zombies
  301. signal.signal(signal.SIGCHLD, self.top_SIGCHLD)
  302. signal.signal(signal.SIGINT, self.do_SIGINT)
  303. while True:
  304. try:
  305. try:
  306. csock = startsock = None
  307. pid = err = 0
  308. try:
  309. self.poll()
  310. ready = select.select([lsock], [], [], 1)[0];
  311. if lsock in ready:
  312. startsock, address = lsock.accept()
  313. else:
  314. continue
  315. except Exception, exc:
  316. if hasattr(exc, 'errno'):
  317. err = exc.errno
  318. else:
  319. err = exc[0]
  320. if err == errno.EINTR:
  321. self.vmsg("Ignoring interrupted syscall")
  322. continue
  323. else:
  324. raise
  325. self.vmsg('%s: forking handler' % address[0])
  326. pid = os.fork()
  327. if pid == 0:
  328. # handler process
  329. csock = self.do_handshake(startsock, address)
  330. self.new_client(csock)
  331. else:
  332. # parent process
  333. self.handler_id += 1
  334. except self.EClose, exc:
  335. # Connection was not a WebSockets connection
  336. if exc.args[0]:
  337. self.msg("%s: %s" % (address[0], exc.args[0]))
  338. except KeyboardInterrupt, exc:
  339. pass
  340. except Exception, exc:
  341. self.msg("handler exception: %s" % str(exc))
  342. if self.verbose:
  343. self.msg(traceback.format_exc())
  344. finally:
  345. if csock and csock != startsock:
  346. csock.close()
  347. if startsock:
  348. startsock.close()
  349. if pid == 0:
  350. break # Child process exits
  351. # HTTP handler with request from a string and response to a socket
  352. class SplitHTTPHandler(SimpleHTTPRequestHandler):
  353. def __init__(self, req, resp, addr):
  354. # Save the response socket
  355. self.response = resp
  356. SimpleHTTPRequestHandler.__init__(self, req, addr, object())
  357. def setup(self):
  358. self.connection = self.response
  359. # Duck type request string to file object
  360. self.rfile = StringIO(self.request)
  361. self.wfile = self.connection.makefile('wb', self.wbufsize)
  362. def send_response(self, code, message=None):
  363. # Save the status code
  364. self.last_code = code
  365. SimpleHTTPRequestHandler.send_response(self, code, message)
  366. def log_message(self, f, *args):
  367. # Save instead of printing
  368. self.last_message = f % args