Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add websocket subprotocol support #150

Merged
merged 3 commits into from
Oct 9, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CONTRIBUTORS.txt
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,4 @@ Sebastian Hanula
Simon Kennedy
Vaibhav Sagar
Vitaly Haritonsky
Philipp A.
41 changes: 33 additions & 8 deletions aiohttp/websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

WS_KEY = b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
WS_HDRS = ('UPGRADE', 'CONNECTION',
'SEC-WEBSOCKET-VERSION', 'SEC-WEBSOCKET-KEY')
'SEC-WEBSOCKET-VERSION', 'SEC-WEBSOCKET-KEY', 'SEC-WEBSOCKET-PROTOCOL')

Message = collections.namedtuple('Message', ['tp', 'data', 'extra'])

Expand Down Expand Up @@ -182,10 +182,14 @@ def close(self, code=1000, message=b''):
opcode=OPCODE_CLOSE)


def do_handshake(method, headers, transport):
def do_handshake(method, headers, transport, protocols=()):
"""Prepare WebSocket handshake. It return http response code,
response headers, websocket parser, websocket writer. It does not
perform any IO."""
perform any IO.

`protocols` is a sequence of known protocols. On successful handshake,
the returned response headers contain the first protocol in this list
which the server also knows."""

# WebSocket accepts only GET
if method.upper() != 'GET':
Expand All @@ -201,6 +205,21 @@ def do_handshake(method, headers, transport):
raise errors.HttpBadRequest(
'No CONNECTION upgrade hdr: {}'.format(
headers.get('CONNECTION')))

# find common sub-protocol between client and server
protocol = None
if 'SEC-WEBSOCKET-PROTOCOL' in headers:
req_protocols = {str(proto.strip()) for proto in
headers['SEC-WEBSOCKET-PROTOCOL'].split(',')}

for proto in protocols:
if proto in req_protocols:
protocol = proto
break
else:
raise errors.HttpBadRequest(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HttpBadRequest case is not test-covered as far as I see

'Client protocols {!r} don’t overlap server-known ones {!r}'
.format(protocols, req_protocols))

# check supported version
version = headers.get('SEC-WEBSOCKET-VERSION')
Expand All @@ -218,12 +237,18 @@ def do_handshake(method, headers, transport):
raise errors.HttpBadRequest(
'Handshake error: {!r}'.format(key)) from None

# response code, headers, parser, writer
return (101,
(('UPGRADE', 'websocket'),
response_headers = [('UPGRADE', 'websocket'),
('CONNECTION', 'upgrade'),
('TRANSFER-ENCODING', 'chunked'),
('SEC-WEBSOCKET-ACCEPT', base64.b64encode(
hashlib.sha1(key.encode() + WS_KEY).digest()).decode())),
hashlib.sha1(key.encode() + WS_KEY).digest()).decode())]

if protocol:
response_headers.append(('SEC-WEBSOCKET-PROTOCOL', protocol))

# response code, headers, parser, writer, protocol
return (101,
response_headers,
WebSocketParser,
WebSocketWriter(transport))
WebSocketWriter(transport),
protocol)
48 changes: 42 additions & 6 deletions tests/test_websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,18 +419,54 @@ def test_protocol_key(self):
websocket.do_handshake,
self.message.method, self.message.headers, self.transport)

def gen_ws_headers(self, protocols=''):
key = base64.b64encode(os.urandom(16)).decode()
hdrs = [('UPGRADE', 'websocket'),
('CONNECTION', 'upgrade'),
('SEC-WEBSOCKET-VERSION', '13'),
('SEC-WEBSOCKET-KEY', key)]
if protocols:
hdrs += [('SEC-WEBSOCKET-PROTOCOL', protocols)]
return hdrs, key

def test_handshake(self):
sec_key = base64.b64encode(os.urandom(16)).decode()
hdrs, sec_key = self.gen_ws_headers()

self.headers.extend([('UPGRADE', 'websocket'),
('CONNECTION', 'upgrade'),
('SEC-WEBSOCKET-VERSION', '13'),
('SEC-WEBSOCKET-KEY', sec_key)])
status, headers, parser, writer = websocket.do_handshake(
self.headers.extend(hdrs)
status, headers, parser, writer, protocol = websocket.do_handshake(
self.message.method, self.message.headers, self.transport)
self.assertEqual(status, 101)
self.assertIsNone(protocol)

key = base64.b64encode(
hashlib.sha1(sec_key.encode() + websocket.WS_KEY).digest())
headers = dict(headers)
self.assertEqual(headers['SEC-WEBSOCKET-ACCEPT'], key.decode())

def test_handshake_protocol(self):
'''Tests if one protocol is returned by do_handshake'''
proto = 'chat'

self.headers.extend(self.gen_ws_headers(proto)[0])
_, resp_headers, _, _, protocol = websocket.do_handshake(
self.message.method, self.message.headers, self.transport,
protocols=[proto])

self.assertEqual(protocol, proto)

#also test if we reply with the protocol
resp_headers = dict(resp_headers)
self.assertEqual(resp_headers['SEC-WEBSOCKET-PROTOCOL'], proto)

def test_handshake_protocol_agreement(self):
'''Tests if the right protocol is selected given multiple'''
best_proto = 'chat'
wanted_protos = ['best', 'chat', 'worse_proto']
server_protos = 'worse_proto,chat'

self.headers.extend(self.gen_ws_headers(server_protos)[0])
_, resp_headers, _, _, protocol = websocket.do_handshake(
self.message.method, self.message.headers, self.transport,
protocols=wanted_protos)

self.assertEqual(protocol, best_proto)