michael@0: # Copyright 2011, Google Inc. michael@0: # All rights reserved. michael@0: # michael@0: # Redistribution and use in source and binary forms, with or without michael@0: # modification, are permitted provided that the following conditions are michael@0: # met: michael@0: # michael@0: # * Redistributions of source code must retain the above copyright michael@0: # notice, this list of conditions and the following disclaimer. michael@0: # * Redistributions in binary form must reproduce the above michael@0: # copyright notice, this list of conditions and the following disclaimer michael@0: # in the documentation and/or other materials provided with the michael@0: # distribution. michael@0: # * Neither the name of Google Inc. nor the names of its michael@0: # contributors may be used to endorse or promote products derived from michael@0: # this software without specific prior written permission. michael@0: # michael@0: # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS michael@0: # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT michael@0: # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR michael@0: # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT michael@0: # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, michael@0: # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT michael@0: # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, michael@0: # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY michael@0: # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT michael@0: # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE michael@0: # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. michael@0: michael@0: michael@0: """This file provides the opening handshake processor for the WebSocket michael@0: protocol version HyBi 00. michael@0: michael@0: Specification: michael@0: http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00 michael@0: """ michael@0: michael@0: michael@0: # Note: request.connection.write/read are used in this module, even though michael@0: # mod_python document says that they should be used only in connection michael@0: # handlers. Unfortunately, we have no other options. For example, michael@0: # request.write/read are not suitable because they don't allow direct raw bytes michael@0: # writing/reading. michael@0: michael@0: michael@0: import logging michael@0: import re michael@0: import struct michael@0: michael@0: from mod_pywebsocket import common michael@0: from mod_pywebsocket.stream import StreamHixie75 michael@0: from mod_pywebsocket import util michael@0: from mod_pywebsocket.handshake._base import HandshakeException michael@0: from mod_pywebsocket.handshake._base import build_location michael@0: from mod_pywebsocket.handshake._base import check_header_lines michael@0: from mod_pywebsocket.handshake._base import format_header michael@0: from mod_pywebsocket.handshake._base import get_mandatory_header michael@0: from mod_pywebsocket.handshake._base import validate_subprotocol michael@0: michael@0: michael@0: _MANDATORY_HEADERS = [ michael@0: # key, expected value or None michael@0: [common.UPGRADE_HEADER, common.WEBSOCKET_UPGRADE_TYPE_HIXIE75], michael@0: [common.CONNECTION_HEADER, common.UPGRADE_CONNECTION_TYPE], michael@0: ] michael@0: michael@0: michael@0: class Handshaker(object): michael@0: """Opening handshake processor for the WebSocket protocol version HyBi 00. michael@0: """ michael@0: michael@0: def __init__(self, request, dispatcher): michael@0: """Construct an instance. michael@0: michael@0: Args: michael@0: request: mod_python request. michael@0: dispatcher: Dispatcher (dispatch.Dispatcher). michael@0: michael@0: Handshaker will add attributes such as ws_resource in performing michael@0: handshake. michael@0: """ michael@0: michael@0: self._logger = util.get_class_logger(self) michael@0: michael@0: self._request = request michael@0: self._dispatcher = dispatcher michael@0: michael@0: def do_handshake(self): michael@0: """Perform WebSocket Handshake. michael@0: michael@0: On _request, we set michael@0: ws_resource, ws_protocol, ws_location, ws_origin, ws_challenge, michael@0: ws_challenge_md5: WebSocket handshake information. michael@0: ws_stream: Frame generation/parsing class. michael@0: ws_version: Protocol version. michael@0: michael@0: Raises: michael@0: HandshakeException: when any error happened in parsing the opening michael@0: handshake request. michael@0: """ michael@0: michael@0: # 5.1 Reading the client's opening handshake. michael@0: # dispatcher sets it in self._request. michael@0: check_header_lines(self._request, _MANDATORY_HEADERS) michael@0: self._set_resource() michael@0: self._set_subprotocol() michael@0: self._set_location() michael@0: self._set_origin() michael@0: self._set_challenge_response() michael@0: self._set_protocol_version() michael@0: michael@0: self._dispatcher.do_extra_handshake(self._request) michael@0: michael@0: self._send_handshake() michael@0: michael@0: def _set_resource(self): michael@0: self._request.ws_resource = self._request.uri michael@0: michael@0: def _set_subprotocol(self): michael@0: # |Sec-WebSocket-Protocol| michael@0: subprotocol = self._request.headers_in.get( michael@0: common.SEC_WEBSOCKET_PROTOCOL_HEADER) michael@0: if subprotocol is not None: michael@0: validate_subprotocol(subprotocol, hixie=True) michael@0: self._request.ws_protocol = subprotocol michael@0: michael@0: def _set_location(self): michael@0: # |Host| michael@0: host = self._request.headers_in.get(common.HOST_HEADER) michael@0: if host is not None: michael@0: self._request.ws_location = build_location(self._request) michael@0: # TODO(ukai): check host is this host. michael@0: michael@0: def _set_origin(self): michael@0: # |Origin| michael@0: origin = self._request.headers_in.get(common.ORIGIN_HEADER) michael@0: if origin is not None: michael@0: self._request.ws_origin = origin michael@0: michael@0: def _set_protocol_version(self): michael@0: # |Sec-WebSocket-Draft| michael@0: draft = self._request.headers_in.get(common.SEC_WEBSOCKET_DRAFT_HEADER) michael@0: if draft is not None and draft != '0': michael@0: raise HandshakeException('Illegal value for %s: %s' % michael@0: (common.SEC_WEBSOCKET_DRAFT_HEADER, michael@0: draft)) michael@0: michael@0: self._logger.debug('Protocol version is HyBi 00') michael@0: self._request.ws_version = common.VERSION_HYBI00 michael@0: self._request.ws_stream = StreamHixie75(self._request, True) michael@0: michael@0: def _set_challenge_response(self): michael@0: # 5.2 4-8. michael@0: self._request.ws_challenge = self._get_challenge() michael@0: # 5.2 9. let /response/ be the MD5 finterprint of /challenge/ michael@0: self._request.ws_challenge_md5 = util.md5_hash( michael@0: self._request.ws_challenge).digest() michael@0: self._logger.debug( michael@0: 'Challenge: %r (%s)', michael@0: self._request.ws_challenge, michael@0: util.hexify(self._request.ws_challenge)) michael@0: self._logger.debug( michael@0: 'Challenge response: %r (%s)', michael@0: self._request.ws_challenge_md5, michael@0: util.hexify(self._request.ws_challenge_md5)) michael@0: michael@0: def _get_key_value(self, key_field): michael@0: key_value = get_mandatory_header(self._request, key_field) michael@0: michael@0: self._logger.debug('%s: %r', key_field, key_value) michael@0: michael@0: # 5.2 4. let /key-number_n/ be the digits (characters in the range michael@0: # U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9)) in /key_n/, michael@0: # interpreted as a base ten integer, ignoring all other characters michael@0: # in /key_n/. michael@0: try: michael@0: key_number = int(re.sub("\\D", "", key_value)) michael@0: except: michael@0: raise HandshakeException('%s field contains no digit' % key_field) michael@0: # 5.2 5. let /spaces_n/ be the number of U+0020 SPACE characters michael@0: # in /key_n/. michael@0: spaces = re.subn(" ", "", key_value)[1] michael@0: if spaces == 0: michael@0: raise HandshakeException('%s field contains no space' % key_field) michael@0: michael@0: self._logger.debug( michael@0: '%s: Key-number is %d and number of spaces is %d', michael@0: key_field, key_number, spaces) michael@0: michael@0: # 5.2 6. if /key-number_n/ is not an integral multiple of /spaces_n/ michael@0: # then abort the WebSocket connection. michael@0: if key_number % spaces != 0: michael@0: raise HandshakeException( michael@0: '%s: Key-number (%d) is not an integral multiple of spaces ' michael@0: '(%d)' % (key_field, key_number, spaces)) michael@0: # 5.2 7. let /part_n/ be /key-number_n/ divided by /spaces_n/. michael@0: part = key_number / spaces michael@0: self._logger.debug('%s: Part is %d', key_field, part) michael@0: return part michael@0: michael@0: def _get_challenge(self): michael@0: # 5.2 4-7. michael@0: key1 = self._get_key_value(common.SEC_WEBSOCKET_KEY1_HEADER) michael@0: key2 = self._get_key_value(common.SEC_WEBSOCKET_KEY2_HEADER) michael@0: # 5.2 8. let /challenge/ be the concatenation of /part_1/, michael@0: challenge = '' michael@0: challenge += struct.pack('!I', key1) # network byteorder int michael@0: challenge += struct.pack('!I', key2) # network byteorder int michael@0: challenge += self._request.connection.read(8) michael@0: return challenge michael@0: michael@0: def _send_handshake(self): michael@0: response = [] michael@0: michael@0: # 5.2 10. send the following line. michael@0: response.append('HTTP/1.1 101 WebSocket Protocol Handshake\r\n') michael@0: michael@0: # 5.2 11. send the following fields to the client. michael@0: response.append(format_header( michael@0: common.UPGRADE_HEADER, common.WEBSOCKET_UPGRADE_TYPE_HIXIE75)) michael@0: response.append(format_header( michael@0: common.CONNECTION_HEADER, common.UPGRADE_CONNECTION_TYPE)) michael@0: response.append(format_header( michael@0: common.SEC_WEBSOCKET_LOCATION_HEADER, self._request.ws_location)) michael@0: response.append(format_header( michael@0: common.SEC_WEBSOCKET_ORIGIN_HEADER, self._request.ws_origin)) michael@0: if self._request.ws_protocol: michael@0: response.append(format_header( michael@0: common.SEC_WEBSOCKET_PROTOCOL_HEADER, michael@0: self._request.ws_protocol)) michael@0: # 5.2 12. send two bytes 0x0D 0x0A. michael@0: response.append('\r\n') michael@0: # 5.2 13. send /response/ michael@0: response.append(self._request.ws_challenge_md5) michael@0: michael@0: raw_response = ''.join(response) michael@0: self._request.connection.write(raw_response) michael@0: self._logger.debug('Sent server\'s opening handshake: %r', michael@0: raw_response) michael@0: michael@0: michael@0: # vi:sts=4 sw=4 et