Thu, 22 Jan 2015 13:21:57 +0100
Incorporate requested changes from Mozilla in review:
https://bugzilla.mozilla.org/show_bug.cgi?id=1123480#c6
michael@0 | 1 | # Copyright 2011, Google Inc. |
michael@0 | 2 | # All rights reserved. |
michael@0 | 3 | # |
michael@0 | 4 | # Redistribution and use in source and binary forms, with or without |
michael@0 | 5 | # modification, are permitted provided that the following conditions are |
michael@0 | 6 | # met: |
michael@0 | 7 | # |
michael@0 | 8 | # * Redistributions of source code must retain the above copyright |
michael@0 | 9 | # notice, this list of conditions and the following disclaimer. |
michael@0 | 10 | # * Redistributions in binary form must reproduce the above |
michael@0 | 11 | # copyright notice, this list of conditions and the following disclaimer |
michael@0 | 12 | # in the documentation and/or other materials provided with the |
michael@0 | 13 | # distribution. |
michael@0 | 14 | # * Neither the name of Google Inc. nor the names of its |
michael@0 | 15 | # contributors may be used to endorse or promote products derived from |
michael@0 | 16 | # this software without specific prior written permission. |
michael@0 | 17 | # |
michael@0 | 18 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
michael@0 | 19 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
michael@0 | 20 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
michael@0 | 21 | # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
michael@0 | 22 | # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
michael@0 | 23 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
michael@0 | 24 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
michael@0 | 25 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
michael@0 | 26 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
michael@0 | 27 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
michael@0 | 28 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
michael@0 | 29 | |
michael@0 | 30 | |
michael@0 | 31 | """WebSocket handshaking defined in draft-hixie-thewebsocketprotocol-75.""" |
michael@0 | 32 | |
michael@0 | 33 | |
michael@0 | 34 | # Note: request.connection.write is used in this module, even though mod_python |
michael@0 | 35 | # document says that it should be used only in connection handlers. |
michael@0 | 36 | # Unfortunately, we have no other options. For example, request.write is not |
michael@0 | 37 | # suitable because it doesn't allow direct raw bytes writing. |
michael@0 | 38 | |
michael@0 | 39 | |
michael@0 | 40 | import logging |
michael@0 | 41 | import re |
michael@0 | 42 | |
michael@0 | 43 | from mod_pywebsocket import common |
michael@0 | 44 | from mod_pywebsocket.stream import StreamHixie75 |
michael@0 | 45 | from mod_pywebsocket import util |
michael@0 | 46 | from mod_pywebsocket.handshake._base import HandshakeException |
michael@0 | 47 | from mod_pywebsocket.handshake._base import build_location |
michael@0 | 48 | from mod_pywebsocket.handshake._base import validate_subprotocol |
michael@0 | 49 | |
michael@0 | 50 | |
michael@0 | 51 | _MANDATORY_HEADERS = [ |
michael@0 | 52 | # key, expected value or None |
michael@0 | 53 | ['Upgrade', 'WebSocket'], |
michael@0 | 54 | ['Connection', 'Upgrade'], |
michael@0 | 55 | ['Host', None], |
michael@0 | 56 | ['Origin', None], |
michael@0 | 57 | ] |
michael@0 | 58 | |
michael@0 | 59 | _FIRST_FIVE_LINES = map(re.compile, [ |
michael@0 | 60 | r'^GET /[\S]* HTTP/1.1\r\n$', |
michael@0 | 61 | r'^Upgrade: WebSocket\r\n$', |
michael@0 | 62 | r'^Connection: Upgrade\r\n$', |
michael@0 | 63 | r'^Host: [\S]+\r\n$', |
michael@0 | 64 | r'^Origin: [\S]+\r\n$', |
michael@0 | 65 | ]) |
michael@0 | 66 | |
michael@0 | 67 | _SIXTH_AND_LATER = re.compile( |
michael@0 | 68 | r'^' |
michael@0 | 69 | r'(WebSocket-Protocol: [\x20-\x7e]+\r\n)?' |
michael@0 | 70 | r'(Cookie: [^\r]*\r\n)*' |
michael@0 | 71 | r'(Cookie2: [^\r]*\r\n)?' |
michael@0 | 72 | r'(Cookie: [^\r]*\r\n)*' |
michael@0 | 73 | r'\r\n') |
michael@0 | 74 | |
michael@0 | 75 | |
michael@0 | 76 | class Handshaker(object): |
michael@0 | 77 | """This class performs WebSocket handshake.""" |
michael@0 | 78 | |
michael@0 | 79 | def __init__(self, request, dispatcher, strict=False): |
michael@0 | 80 | """Construct an instance. |
michael@0 | 81 | |
michael@0 | 82 | Args: |
michael@0 | 83 | request: mod_python request. |
michael@0 | 84 | dispatcher: Dispatcher (dispatch.Dispatcher). |
michael@0 | 85 | strict: Strictly check handshake request. Default: False. |
michael@0 | 86 | If True, request.connection must provide get_memorized_lines |
michael@0 | 87 | method. |
michael@0 | 88 | |
michael@0 | 89 | Handshaker will add attributes such as ws_resource in performing |
michael@0 | 90 | handshake. |
michael@0 | 91 | """ |
michael@0 | 92 | |
michael@0 | 93 | self._logger = util.get_class_logger(self) |
michael@0 | 94 | |
michael@0 | 95 | self._request = request |
michael@0 | 96 | self._dispatcher = dispatcher |
michael@0 | 97 | self._strict = strict |
michael@0 | 98 | |
michael@0 | 99 | def do_handshake(self): |
michael@0 | 100 | """Perform WebSocket Handshake. |
michael@0 | 101 | |
michael@0 | 102 | On _request, we set |
michael@0 | 103 | ws_resource, ws_origin, ws_location, ws_protocol |
michael@0 | 104 | ws_challenge_md5: WebSocket handshake information. |
michael@0 | 105 | ws_stream: Frame generation/parsing class. |
michael@0 | 106 | ws_version: Protocol version. |
michael@0 | 107 | """ |
michael@0 | 108 | |
michael@0 | 109 | self._check_header_lines() |
michael@0 | 110 | self._set_resource() |
michael@0 | 111 | self._set_origin() |
michael@0 | 112 | self._set_location() |
michael@0 | 113 | self._set_subprotocol() |
michael@0 | 114 | self._set_protocol_version() |
michael@0 | 115 | |
michael@0 | 116 | self._dispatcher.do_extra_handshake(self._request) |
michael@0 | 117 | |
michael@0 | 118 | self._send_handshake() |
michael@0 | 119 | |
michael@0 | 120 | self._logger.debug('Sent opening handshake response') |
michael@0 | 121 | |
michael@0 | 122 | def _set_resource(self): |
michael@0 | 123 | self._request.ws_resource = self._request.uri |
michael@0 | 124 | |
michael@0 | 125 | def _set_origin(self): |
michael@0 | 126 | self._request.ws_origin = self._request.headers_in['Origin'] |
michael@0 | 127 | |
michael@0 | 128 | def _set_location(self): |
michael@0 | 129 | self._request.ws_location = build_location(self._request) |
michael@0 | 130 | |
michael@0 | 131 | def _set_subprotocol(self): |
michael@0 | 132 | subprotocol = self._request.headers_in.get('WebSocket-Protocol') |
michael@0 | 133 | if subprotocol is not None: |
michael@0 | 134 | validate_subprotocol(subprotocol, hixie=True) |
michael@0 | 135 | self._request.ws_protocol = subprotocol |
michael@0 | 136 | |
michael@0 | 137 | def _set_protocol_version(self): |
michael@0 | 138 | self._logger.debug('IETF Hixie 75 protocol') |
michael@0 | 139 | self._request.ws_version = common.VERSION_HIXIE75 |
michael@0 | 140 | self._request.ws_stream = StreamHixie75(self._request) |
michael@0 | 141 | |
michael@0 | 142 | def _sendall(self, data): |
michael@0 | 143 | self._request.connection.write(data) |
michael@0 | 144 | |
michael@0 | 145 | def _send_handshake(self): |
michael@0 | 146 | self._sendall('HTTP/1.1 101 Web Socket Protocol Handshake\r\n') |
michael@0 | 147 | self._sendall('Upgrade: WebSocket\r\n') |
michael@0 | 148 | self._sendall('Connection: Upgrade\r\n') |
michael@0 | 149 | self._sendall('WebSocket-Origin: %s\r\n' % self._request.ws_origin) |
michael@0 | 150 | self._sendall('WebSocket-Location: %s\r\n' % self._request.ws_location) |
michael@0 | 151 | if self._request.ws_protocol: |
michael@0 | 152 | self._sendall( |
michael@0 | 153 | 'WebSocket-Protocol: %s\r\n' % self._request.ws_protocol) |
michael@0 | 154 | self._sendall('\r\n') |
michael@0 | 155 | |
michael@0 | 156 | def _check_header_lines(self): |
michael@0 | 157 | for key, expected_value in _MANDATORY_HEADERS: |
michael@0 | 158 | actual_value = self._request.headers_in.get(key) |
michael@0 | 159 | if not actual_value: |
michael@0 | 160 | raise HandshakeException('Header %s is not defined' % key) |
michael@0 | 161 | if expected_value: |
michael@0 | 162 | if actual_value != expected_value: |
michael@0 | 163 | raise HandshakeException( |
michael@0 | 164 | 'Expected %r for header %s but found %r' % |
michael@0 | 165 | (expected_value, key, actual_value)) |
michael@0 | 166 | if self._strict: |
michael@0 | 167 | try: |
michael@0 | 168 | lines = self._request.connection.get_memorized_lines() |
michael@0 | 169 | except AttributeError, e: |
michael@0 | 170 | raise AttributeError( |
michael@0 | 171 | 'Strict handshake is specified but the connection ' |
michael@0 | 172 | 'doesn\'t provide get_memorized_lines()') |
michael@0 | 173 | self._check_first_lines(lines) |
michael@0 | 174 | |
michael@0 | 175 | def _check_first_lines(self, lines): |
michael@0 | 176 | if len(lines) < len(_FIRST_FIVE_LINES): |
michael@0 | 177 | raise HandshakeException('Too few header lines: %d' % len(lines)) |
michael@0 | 178 | for line, regexp in zip(lines, _FIRST_FIVE_LINES): |
michael@0 | 179 | if not regexp.search(line): |
michael@0 | 180 | raise HandshakeException( |
michael@0 | 181 | 'Unexpected header: %r doesn\'t match %r' |
michael@0 | 182 | % (line, regexp.pattern)) |
michael@0 | 183 | sixth_and_later = ''.join(lines[5:]) |
michael@0 | 184 | if not _SIXTH_AND_LATER.search(sixth_and_later): |
michael@0 | 185 | raise HandshakeException( |
michael@0 | 186 | 'Unexpected header: %r doesn\'t match %r' |
michael@0 | 187 | % (sixth_and_later, _SIXTH_AND_LATER.pattern)) |
michael@0 | 188 | |
michael@0 | 189 | |
michael@0 | 190 | # vi:sts=4 sw=4 et |