2010-05-06 16:32:07 +01:00
|
|
|
#!/usr/bin/python
|
|
|
|
|
|
|
|
'''
|
|
|
|
Python WebSocket library with support for "wss://" encryption.
|
2010-07-17 18:05:58 +01:00
|
|
|
Copyright 2010 Joel Martin
|
|
|
|
Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3)
|
2010-05-06 16:32:07 +01:00
|
|
|
|
|
|
|
You can make a cert/key with openssl using:
|
|
|
|
openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem
|
|
|
|
as taken from http://docs.python.org/dev/library/ssl.html#certificates
|
|
|
|
|
|
|
|
'''
|
|
|
|
|
2010-06-24 23:04:57 +01:00
|
|
|
import sys, socket, ssl, struct, traceback
|
2010-06-17 22:06:18 +01:00
|
|
|
import os, resource, errno, signal # daemonizing
|
2011-01-07 00:26:54 +00:00
|
|
|
from SimpleHTTPServer import SimpleHTTPRequestHandler
|
|
|
|
from cStringIO import StringIO
|
2010-05-06 16:32:07 +01:00
|
|
|
from base64 import b64encode, b64decode
|
2010-08-04 20:32:10 +01:00
|
|
|
try:
|
|
|
|
from hashlib import md5
|
|
|
|
except:
|
|
|
|
from md5 import md5 # Support python 2.4
|
|
|
|
from urlparse import urlsplit
|
|
|
|
from cgi import parse_qsl
|
2010-05-06 16:32:07 +01:00
|
|
|
|
2010-06-17 22:06:18 +01:00
|
|
|
settings = {
|
2010-09-11 21:10:54 +01:00
|
|
|
'verbose' : False,
|
2010-06-17 22:06:18 +01:00
|
|
|
'listen_host' : '',
|
|
|
|
'listen_port' : None,
|
|
|
|
'handler' : None,
|
2010-09-10 19:05:48 +01:00
|
|
|
'handler_id' : 1,
|
2010-06-17 22:06:18 +01:00
|
|
|
'cert' : None,
|
2010-11-06 15:55:09 +00:00
|
|
|
'key' : None,
|
2010-06-17 22:06:18 +01:00
|
|
|
'ssl_only' : False,
|
|
|
|
'daemon' : True,
|
2011-01-07 00:26:54 +00:00
|
|
|
'record' : None,
|
|
|
|
'web' : False, }
|
2010-05-06 16:32:07 +01:00
|
|
|
|
|
|
|
server_handshake = """HTTP/1.1 101 Web Socket Protocol Handshake\r
|
|
|
|
Upgrade: WebSocket\r
|
|
|
|
Connection: Upgrade\r
|
2010-06-24 23:04:57 +01:00
|
|
|
%sWebSocket-Origin: %s\r
|
|
|
|
%sWebSocket-Location: %s://%s%s\r
|
|
|
|
%sWebSocket-Protocol: sample\r
|
2010-05-06 16:32:07 +01:00
|
|
|
\r
|
2010-06-24 23:04:57 +01:00
|
|
|
%s"""
|
2010-05-06 16:32:07 +01:00
|
|
|
|
|
|
|
policy_response = """<cross-domain-policy><allow-access-from domain="*" to-ports="*" /></cross-domain-policy>\n"""
|
|
|
|
|
2010-09-10 19:05:48 +01:00
|
|
|
class EClose(Exception):
|
|
|
|
pass
|
|
|
|
|
2011-01-07 00:26:54 +00:00
|
|
|
# HTTP handler with request from a string and response to a socket
|
|
|
|
class SplitHTTPHandler(SimpleHTTPRequestHandler):
|
|
|
|
def __init__(self, req, resp, addr):
|
|
|
|
# Save the response socket
|
|
|
|
self.response = resp
|
|
|
|
SimpleHTTPRequestHandler.__init__(self, req, addr, object())
|
|
|
|
|
|
|
|
def setup(self):
|
|
|
|
self.connection = self.response
|
|
|
|
# Duck type request string to file object
|
|
|
|
self.rfile = StringIO(self.request)
|
|
|
|
self.wfile = self.connection.makefile('wb', self.wbufsize)
|
|
|
|
|
|
|
|
def send_response(self, code, message=None):
|
|
|
|
# Save the status code
|
|
|
|
self.last_code = code
|
|
|
|
SimpleHTTPRequestHandler.send_response(self, code, message)
|
|
|
|
|
|
|
|
def log_message(self, f, *args):
|
|
|
|
# Save instead of printing
|
|
|
|
self.last_message = f % args
|
|
|
|
|
|
|
|
|
2010-05-06 16:32:07 +01:00
|
|
|
def traffic(token="."):
|
2010-09-11 21:10:54 +01:00
|
|
|
if settings['verbose'] and not settings['daemon']:
|
2010-09-10 19:05:48 +01:00
|
|
|
sys.stdout.write(token)
|
|
|
|
sys.stdout.flush()
|
|
|
|
|
|
|
|
def handler_msg(msg):
|
|
|
|
if not settings['daemon']:
|
2011-01-07 00:26:54 +00:00
|
|
|
print "% 3d: %s" % (settings['handler_id'], msg)
|
|
|
|
|
|
|
|
def handler_vmsg(msg):
|
|
|
|
if settings['verbose']: handler_msg(msg)
|
2010-05-06 16:32:07 +01:00
|
|
|
|
2010-07-01 02:39:41 +01:00
|
|
|
def encode(buf):
|
2010-08-27 18:10:09 +01:00
|
|
|
buf = b64encode(buf)
|
2010-07-01 02:39:41 +01:00
|
|
|
|
2010-07-01 18:13:17 +01:00
|
|
|
return "\x00%s\xff" % buf
|
2010-07-01 02:39:41 +01:00
|
|
|
|
2010-05-06 16:32:07 +01:00
|
|
|
def decode(buf):
|
|
|
|
""" Parse out WebSocket packets. """
|
|
|
|
if buf.count('\xff') > 1:
|
2010-08-27 18:10:09 +01:00
|
|
|
return [b64decode(d[1:]) for d in buf.split('\xff')]
|
2010-05-06 16:32:07 +01:00
|
|
|
else:
|
2010-08-27 18:10:09 +01:00
|
|
|
return [b64decode(buf[1:-1])]
|
2010-05-06 16:32:07 +01:00
|
|
|
|
2010-07-01 02:39:41 +01:00
|
|
|
def parse_handshake(handshake):
|
|
|
|
ret = {}
|
|
|
|
req_lines = handshake.split("\r\n")
|
|
|
|
if not req_lines[0].startswith("GET "):
|
|
|
|
raise Exception("Invalid handshake: no GET request line")
|
|
|
|
ret['path'] = req_lines[0].split(" ")[1]
|
|
|
|
for line in req_lines[1:]:
|
|
|
|
if line == "": break
|
2010-08-04 20:18:55 +01:00
|
|
|
var, val = line.split(": ")
|
2010-07-01 02:39:41 +01:00
|
|
|
ret[var] = val
|
2010-05-06 16:32:07 +01:00
|
|
|
|
2010-07-01 02:39:41 +01:00
|
|
|
if req_lines[-2] == "":
|
|
|
|
ret['key3'] = req_lines[-1]
|
|
|
|
|
|
|
|
return ret
|
|
|
|
|
|
|
|
def gen_md5(keys):
|
|
|
|
key1 = keys['Sec-WebSocket-Key1']
|
|
|
|
key2 = keys['Sec-WebSocket-Key2']
|
|
|
|
key3 = keys['key3']
|
|
|
|
spaces1 = key1.count(" ")
|
|
|
|
spaces2 = key2.count(" ")
|
|
|
|
num1 = int("".join([c for c in key1 if c.isdigit()])) / spaces1
|
|
|
|
num2 = int("".join([c for c in key2 if c.isdigit()])) / spaces2
|
|
|
|
|
|
|
|
return md5(struct.pack('>II8s', num1, num2, key3)).digest()
|
2010-05-06 16:32:07 +01:00
|
|
|
|
|
|
|
|
2011-01-07 00:26:54 +00:00
|
|
|
def do_handshake(sock, address):
|
|
|
|
stype = ""
|
2010-06-17 22:06:18 +01:00
|
|
|
|
2010-05-06 16:32:07 +01:00
|
|
|
# Peek, but don't read the data
|
|
|
|
handshake = sock.recv(1024, socket.MSG_PEEK)
|
2010-09-10 19:05:48 +01:00
|
|
|
#handler_msg("Handshake [%s]" % repr(handshake))
|
2010-07-01 02:39:41 +01:00
|
|
|
if handshake == "":
|
2011-01-07 00:26:54 +00:00
|
|
|
raise EClose("ignoring empty handshake")
|
2010-07-01 02:39:41 +01:00
|
|
|
elif handshake.startswith("<policy-file-request/>"):
|
2010-05-06 16:32:07 +01:00
|
|
|
handshake = sock.recv(1024)
|
|
|
|
sock.send(policy_response)
|
2011-01-07 00:26:54 +00:00
|
|
|
raise EClose("Sending flash policy response")
|
2010-09-15 18:09:17 +01:00
|
|
|
elif handshake[0] in ("\x16", "\x80"):
|
2011-01-04 19:14:46 +00:00
|
|
|
if not os.path.exists(settings['cert']):
|
2011-01-07 00:26:54 +00:00
|
|
|
raise EClose("SSL connection but '%s' not found"
|
|
|
|
% settings['cert'])
|
|
|
|
try:
|
|
|
|
retsock = ssl.wrap_socket(
|
|
|
|
sock,
|
|
|
|
server_side=True,
|
|
|
|
certfile=settings['cert'],
|
|
|
|
keyfile=settings['key'])
|
|
|
|
except ssl.SSLError, x:
|
|
|
|
if x.args[0] == ssl.SSL_ERROR_EOF:
|
|
|
|
raise EClose("")
|
|
|
|
else:
|
|
|
|
raise
|
|
|
|
|
2010-05-06 16:32:07 +01:00
|
|
|
scheme = "wss"
|
2011-01-07 00:26:54 +00:00
|
|
|
stype = "SSL/TLS (wss://)"
|
2010-06-17 22:06:18 +01:00
|
|
|
elif settings['ssl_only']:
|
2011-01-07 00:26:54 +00:00
|
|
|
raise EClose("non-SSL connection received but disallowed")
|
2010-05-06 16:32:07 +01:00
|
|
|
else:
|
|
|
|
retsock = sock
|
|
|
|
scheme = "ws"
|
2011-01-07 00:26:54 +00:00
|
|
|
stype = "Plain non-SSL (ws://)"
|
|
|
|
|
|
|
|
# Now get the data from the socket
|
2010-05-06 16:32:07 +01:00
|
|
|
handshake = retsock.recv(4096)
|
2010-09-10 19:05:48 +01:00
|
|
|
#handler_msg("handshake: " + repr(handshake))
|
2011-01-07 00:26:54 +00:00
|
|
|
|
2010-09-15 18:09:17 +01:00
|
|
|
if len(handshake) == 0:
|
|
|
|
raise EClose("Client closed during handshake")
|
2011-01-07 00:26:54 +00:00
|
|
|
|
|
|
|
# Handle normal web requests
|
|
|
|
if handshake.startswith('GET ') and \
|
|
|
|
handshake.find('Upgrade: WebSocket\r\n') == -1:
|
|
|
|
if not settings['web']:
|
|
|
|
raise EClose("Normal web request received but disallowed")
|
|
|
|
sh = SplitHTTPHandler(handshake, retsock, address)
|
|
|
|
if sh.last_code < 200 or sh.last_code >= 300:
|
|
|
|
raise EClose(sh.last_message)
|
|
|
|
elif settings['verbose']:
|
|
|
|
raise EClose(sh.last_message)
|
|
|
|
else:
|
|
|
|
raise EClose("")
|
|
|
|
|
|
|
|
# Do WebSockets handshake and return the socket
|
2010-06-24 23:04:57 +01:00
|
|
|
h = parse_handshake(handshake)
|
2010-05-06 16:32:07 +01:00
|
|
|
|
2010-06-24 23:04:57 +01:00
|
|
|
if h.get('key3'):
|
|
|
|
trailer = gen_md5(h)
|
|
|
|
pre = "Sec-"
|
2011-01-07 00:26:54 +00:00
|
|
|
ver = 76
|
2010-06-24 23:04:57 +01:00
|
|
|
else:
|
|
|
|
trailer = ""
|
|
|
|
pre = ""
|
2011-01-07 00:26:54 +00:00
|
|
|
ver = 75
|
|
|
|
|
|
|
|
handler_msg("%s WebSocket connection (version %s) from %s"
|
|
|
|
% (stype, ver, address[0]))
|
2010-06-24 23:04:57 +01:00
|
|
|
|
|
|
|
response = server_handshake % (pre, h['Origin'], pre, scheme,
|
|
|
|
h['Host'], h['path'], pre, trailer)
|
|
|
|
|
2010-09-10 19:05:48 +01:00
|
|
|
#handler_msg("sending response:", repr(response))
|
2010-06-24 23:04:57 +01:00
|
|
|
retsock.send(response)
|
2010-05-06 16:32:07 +01:00
|
|
|
return retsock
|
|
|
|
|
2010-07-17 18:05:58 +01:00
|
|
|
def daemonize(keepfd=None):
|
2010-06-17 22:06:18 +01:00
|
|
|
os.umask(0)
|
|
|
|
os.chdir('/')
|
|
|
|
os.setgid(os.getgid()) # relinquish elevations
|
|
|
|
os.setuid(os.getuid()) # relinquish elevations
|
|
|
|
|
|
|
|
# Double fork to daemonize
|
|
|
|
if os.fork() > 0: os._exit(0) # Parent exits
|
|
|
|
os.setsid() # Obtain new process group
|
|
|
|
if os.fork() > 0: os._exit(0) # Parent exits
|
|
|
|
|
|
|
|
# Signal handling
|
|
|
|
def terminate(a,b): os._exit(0)
|
|
|
|
signal.signal(signal.SIGTERM, terminate)
|
|
|
|
signal.signal(signal.SIGINT, signal.SIG_IGN)
|
|
|
|
|
|
|
|
# Close open files
|
|
|
|
maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
|
|
|
|
if maxfd == resource.RLIM_INFINITY: maxfd = 256
|
|
|
|
for fd in reversed(range(maxfd)):
|
|
|
|
try:
|
2010-07-17 18:05:58 +01:00
|
|
|
if fd != keepfd:
|
|
|
|
os.close(fd)
|
2011-01-07 00:26:54 +00:00
|
|
|
else:
|
|
|
|
handler_vmsg("Keeping fd: %d" % fd)
|
2010-06-17 22:06:18 +01:00
|
|
|
except OSError, exc:
|
|
|
|
if exc.errno != errno.EBADF: raise
|
|
|
|
|
|
|
|
# Redirect I/O to /dev/null
|
|
|
|
os.dup2(os.open(os.devnull, os.O_RDWR), sys.stdin.fileno())
|
|
|
|
os.dup2(os.open(os.devnull, os.O_RDWR), sys.stdout.fileno())
|
|
|
|
os.dup2(os.open(os.devnull, os.O_RDWR), sys.stderr.fileno())
|
|
|
|
|
|
|
|
|
|
|
|
def start_server():
|
|
|
|
|
2010-05-06 16:32:07 +01:00
|
|
|
lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
|
|
lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
2010-06-17 22:06:18 +01:00
|
|
|
lsock.bind((settings['listen_host'], settings['listen_port']))
|
2010-05-06 16:32:07 +01:00
|
|
|
lsock.listen(100)
|
2010-07-17 18:05:58 +01:00
|
|
|
|
2010-09-10 19:05:48 +01:00
|
|
|
if settings['daemon']:
|
|
|
|
daemonize(keepfd=lsock.fileno())
|
|
|
|
|
2010-09-11 21:10:54 +01:00
|
|
|
# Reep zombies
|
|
|
|
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
|
|
|
|
|
|
|
|
print 'Waiting for connections on %s:%s' % (
|
|
|
|
settings['listen_host'], settings['listen_port'])
|
2010-07-17 18:05:58 +01:00
|
|
|
|
2010-05-06 16:32:07 +01:00
|
|
|
while True:
|
|
|
|
try:
|
2010-06-17 22:06:18 +01:00
|
|
|
csock = startsock = None
|
2010-09-10 19:05:48 +01:00
|
|
|
pid = 0
|
2010-05-06 16:32:07 +01:00
|
|
|
startsock, address = lsock.accept()
|
2011-01-07 00:26:54 +00:00
|
|
|
handler_vmsg('%s: forking handler' % address[0])
|
2010-09-11 21:10:54 +01:00
|
|
|
pid = os.fork()
|
2010-05-06 16:32:07 +01:00
|
|
|
|
2010-09-10 19:05:48 +01:00
|
|
|
if pid == 0: # handler process
|
2011-01-07 00:26:54 +00:00
|
|
|
csock = do_handshake(startsock, address)
|
2010-09-10 19:05:48 +01:00
|
|
|
settings['handler'](csock)
|
|
|
|
else: # parent process
|
|
|
|
settings['handler_id'] += 1
|
|
|
|
|
|
|
|
except EClose, exc:
|
2011-01-07 00:26:54 +00:00
|
|
|
if csock and csock != startsock:
|
|
|
|
csock.close()
|
|
|
|
startsock.close()
|
|
|
|
if exc.args[0]:
|
|
|
|
handler_msg("%s: %s" % (address[0], exc.args[0]))
|
2010-09-10 19:05:48 +01:00
|
|
|
except Exception, exc:
|
|
|
|
handler_msg("handler exception: %s" % str(exc))
|
2011-01-07 00:26:54 +00:00
|
|
|
if settings['verbose']:
|
|
|
|
handler_msg(traceback.format_exc())
|
2010-09-10 19:05:48 +01:00
|
|
|
|
|
|
|
if pid == 0:
|
2010-05-06 16:32:07 +01:00
|
|
|
if csock: csock.close()
|
2010-06-17 22:06:18 +01:00
|
|
|
if startsock and startsock != csock: startsock.close()
|
2010-09-11 21:10:54 +01:00
|
|
|
break # Child process exits
|