1 # Copyright 2009, Google Inc.
4 # Redistribution and use in source and binary forms, with or without
5 # modification, are permitted provided that the following conditions are
8 # * Redistributions of source code must retain the above copyright
9 # notice, this list of conditions and the following disclaimer.
10 # * Redistributions in binary form must reproduce the above
11 # copyright notice, this list of conditions and the following disclaimer
12 # in the documentation and/or other materials provided with the
14 # * Neither the name of Google Inc. nor the names of its
15 # contributors may be used to endorse or promote products derived from
16 # this software without specific prior written permission.
18 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 """Web Socket handshaking.
33 Note: request.connection.write/read are used in this module, even though
34 mod_python document says that they should be used only in connection handlers.
35 Unfortunately, we have no other options. For example, request.write/read are
36 not suitable because they don't allow direct raw bytes writing/reading.
43 _DEFAULT_WEB_SOCKET_PORT = 80
44 _DEFAULT_WEB_SOCKET_SECURE_PORT = 443
45 _WEB_SOCKET_SCHEME = 'ws'
46 _WEB_SOCKET_SECURE_SCHEME = 'wss'
48 _METHOD_LINE = re.compile(r'^GET ([^ ]+) HTTP/1.1\r\n$')
50 _MANDATORY_HEADERS = [
51 # key, expected value or None
52 ['Upgrade', 'WebSocket'],
53 ['Connection', 'Upgrade'],
59 def _default_port(is_secure):
61 return _DEFAULT_WEB_SOCKET_SECURE_PORT
63 return _DEFAULT_WEB_SOCKET_PORT
66 class HandshakeError(Exception):
67 """Exception in Web Socket Handshake."""
72 def _validate_protocol(protocol):
73 """Validate WebSocket-Protocol string."""
76 raise HandshakeError('Invalid WebSocket-Protocol: empty')
78 if not 0x21 <= ord(c) <= 0x7e:
79 raise HandshakeError('Illegal character in protocol: %r' % c)
82 class Handshaker(object):
83 """This class performs Web Socket handshake."""
85 def __init__(self, request, dispatcher):
86 """Construct an instance.
89 request: mod_python request.
90 dispatcher: Dispatcher (dispatch.Dispatcher).
92 Handshaker will add attributes such as ws_resource in performing
96 self._request = request
97 self._dispatcher = dispatcher
99 def do_handshake(self):
100 """Perform Web Socket Handshake."""
102 self._check_header_lines()
107 self._dispatcher.do_extra_handshake(self._request)
108 self._send_handshake()
110 def _set_resource(self):
111 self._request.ws_resource = self._request.uri
113 def _set_origin(self):
114 self._request.ws_origin = self._request.headers_in['Origin']
116 def _set_location(self):
118 if self._request.is_https():
119 location_parts.append(_WEB_SOCKET_SECURE_SCHEME)
121 location_parts.append(_WEB_SOCKET_SCHEME)
122 location_parts.append('://')
123 host, port = self._parse_host_header()
124 connection_port = self._request.connection.local_addr[1]
125 if port != connection_port:
126 raise HandshakeError('Header/connection port mismatch: %d/%d' %
127 (port, connection_port))
128 location_parts.append(host)
129 if (port != _default_port(self._request.is_https())):
130 location_parts.append(':')
131 location_parts.append(str(port))
132 location_parts.append(self._request.uri)
133 self._request.ws_location = ''.join(location_parts)
135 def _parse_host_header(self):
136 fields = self._request.headers_in['Host'].split(':', 1)
138 return fields[0], _default_port(self._request.is_https())
140 return fields[0], int(fields[1])
141 except ValueError, e:
142 raise HandshakeError('Invalid port number format: %r' % e)
144 def _set_protocol(self):
145 protocol = self._request.headers_in.get('WebSocket-Protocol')
146 if protocol is not None:
147 _validate_protocol(protocol)
148 self._request.ws_protocol = protocol
150 def _send_handshake(self):
151 self._request.connection.write(
152 'HTTP/1.1 101 Web Socket Protocol Handshake\r\n')
153 self._request.connection.write('Upgrade: WebSocket\r\n')
154 self._request.connection.write('Connection: Upgrade\r\n')
155 self._request.connection.write('WebSocket-Origin: ')
156 self._request.connection.write(self._request.ws_origin)
157 self._request.connection.write('\r\n')
158 self._request.connection.write('WebSocket-Location: ')
159 self._request.connection.write(self._request.ws_location)
160 self._request.connection.write('\r\n')
161 if self._request.ws_protocol:
162 self._request.connection.write('WebSocket-Protocol: ')
163 self._request.connection.write(self._request.ws_protocol)
164 self._request.connection.write('\r\n')
165 self._request.connection.write('\r\n')
167 def _check_header_lines(self):
168 for key, expected_value in _MANDATORY_HEADERS:
169 actual_value = self._request.headers_in.get(key)
171 raise HandshakeError('Header %s is not defined' % key)
173 if actual_value != expected_value:
174 raise HandshakeError('Illegal value for header %s: %s' %