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 (RFC 6455). michael@0: michael@0: Specification: michael@0: http://tools.ietf.org/html/rfc6455 michael@0: """ michael@0: michael@0: michael@0: # Note: request.connection.write is used in this module, even though mod_python michael@0: # document says that it should be used only in connection handlers. michael@0: # Unfortunately, we have no other options. For example, request.write is not michael@0: # suitable because it doesn't allow direct raw bytes writing. michael@0: michael@0: michael@0: import base64 michael@0: import logging michael@0: import os michael@0: import re michael@0: michael@0: from mod_pywebsocket import common michael@0: from mod_pywebsocket.extensions import get_extension_processor michael@0: from mod_pywebsocket.handshake._base import check_request_line michael@0: from mod_pywebsocket.handshake._base import format_extensions 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 HandshakeException michael@0: from mod_pywebsocket.handshake._base import parse_extensions michael@0: from mod_pywebsocket.handshake._base import parse_token_list michael@0: from mod_pywebsocket.handshake._base import validate_mandatory_header michael@0: from mod_pywebsocket.handshake._base import validate_subprotocol michael@0: from mod_pywebsocket.handshake._base import VersionException michael@0: from mod_pywebsocket.stream import Stream michael@0: from mod_pywebsocket.stream import StreamOptions michael@0: from mod_pywebsocket import util michael@0: michael@0: michael@0: # Used to validate the value in the Sec-WebSocket-Key header strictly. RFC 4648 michael@0: # disallows non-zero padding, so the character right before == must be any of michael@0: # A, Q, g and w. michael@0: _SEC_WEBSOCKET_KEY_REGEX = re.compile('^[+/0-9A-Za-z]{21}[AQgw]==$') michael@0: michael@0: # Defining aliases for values used frequently. michael@0: _VERSION_HYBI08 = common.VERSION_HYBI08 michael@0: _VERSION_HYBI08_STRING = str(_VERSION_HYBI08) michael@0: _VERSION_LATEST = common.VERSION_HYBI_LATEST michael@0: _VERSION_LATEST_STRING = str(_VERSION_LATEST) michael@0: _SUPPORTED_VERSIONS = [ michael@0: _VERSION_LATEST, michael@0: _VERSION_HYBI08, michael@0: ] michael@0: michael@0: michael@0: def compute_accept(key): michael@0: """Computes value for the Sec-WebSocket-Accept header from value of the michael@0: Sec-WebSocket-Key header. michael@0: """ michael@0: michael@0: accept_binary = util.sha1_hash( michael@0: key + common.WEBSOCKET_ACCEPT_UUID).digest() michael@0: accept = base64.b64encode(accept_binary) michael@0: michael@0: return (accept, accept_binary) michael@0: michael@0: michael@0: class Handshaker(object): michael@0: """Opening handshake processor for the WebSocket protocol (RFC 6455).""" 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 during 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 _validate_connection_header(self): michael@0: connection = get_mandatory_header( michael@0: self._request, common.CONNECTION_HEADER) michael@0: michael@0: try: michael@0: connection_tokens = parse_token_list(connection) michael@0: except HandshakeException, e: michael@0: raise HandshakeException( michael@0: 'Failed to parse %s: %s' % (common.CONNECTION_HEADER, e)) michael@0: michael@0: connection_is_valid = False michael@0: for token in connection_tokens: michael@0: if token.lower() == common.UPGRADE_CONNECTION_TYPE.lower(): michael@0: connection_is_valid = True michael@0: break michael@0: if not connection_is_valid: michael@0: raise HandshakeException( michael@0: '%s header doesn\'t contain "%s"' % michael@0: (common.CONNECTION_HEADER, common.UPGRADE_CONNECTION_TYPE)) michael@0: michael@0: def do_handshake(self): michael@0: self._request.ws_close_code = None michael@0: self._request.ws_close_reason = None michael@0: michael@0: # Parsing. michael@0: michael@0: check_request_line(self._request) michael@0: michael@0: validate_mandatory_header( michael@0: self._request, michael@0: common.UPGRADE_HEADER, michael@0: common.WEBSOCKET_UPGRADE_TYPE) michael@0: michael@0: self._validate_connection_header() michael@0: michael@0: self._request.ws_resource = self._request.uri michael@0: michael@0: unused_host = get_mandatory_header(self._request, common.HOST_HEADER) michael@0: michael@0: self._request.ws_version = self._check_version() michael@0: michael@0: # This handshake must be based on latest hybi. We are responsible to michael@0: # fallback to HTTP on handshake failure as latest hybi handshake michael@0: # specifies. michael@0: try: michael@0: self._get_origin() michael@0: self._set_protocol() michael@0: self._parse_extensions() michael@0: michael@0: # Key validation, response generation. michael@0: michael@0: key = self._get_key() michael@0: (accept, accept_binary) = compute_accept(key) michael@0: self._logger.debug( michael@0: '%s: %r (%s)', michael@0: common.SEC_WEBSOCKET_ACCEPT_HEADER, michael@0: accept, michael@0: util.hexify(accept_binary)) michael@0: michael@0: self._logger.debug('Protocol version is RFC 6455') michael@0: michael@0: # Setup extension processors. michael@0: michael@0: processors = [] michael@0: if self._request.ws_requested_extensions is not None: michael@0: for extension_request in self._request.ws_requested_extensions: michael@0: processor = get_extension_processor(extension_request) michael@0: # Unknown extension requests are just ignored. michael@0: if processor is not None: michael@0: processors.append(processor) michael@0: self._request.ws_extension_processors = processors michael@0: michael@0: # Extra handshake handler may modify/remove processors. michael@0: self._dispatcher.do_extra_handshake(self._request) michael@0: michael@0: stream_options = StreamOptions() michael@0: michael@0: self._request.ws_extensions = None michael@0: for processor in self._request.ws_extension_processors: michael@0: if processor is None: michael@0: # Some processors may be removed by extra handshake michael@0: # handler. michael@0: continue michael@0: michael@0: extension_response = processor.get_extension_response() michael@0: if extension_response is None: michael@0: # Rejected. michael@0: continue michael@0: michael@0: if self._request.ws_extensions is None: michael@0: self._request.ws_extensions = [] michael@0: self._request.ws_extensions.append(extension_response) michael@0: michael@0: processor.setup_stream_options(stream_options) michael@0: michael@0: if self._request.ws_extensions is not None: michael@0: self._logger.debug( michael@0: 'Extensions accepted: %r', michael@0: map(common.ExtensionParameter.name, michael@0: self._request.ws_extensions)) michael@0: michael@0: self._request.ws_stream = Stream(self._request, stream_options) michael@0: michael@0: if self._request.ws_requested_protocols is not None: michael@0: if self._request.ws_protocol is None: michael@0: raise HandshakeException( michael@0: 'do_extra_handshake must choose one subprotocol from ' michael@0: 'ws_requested_protocols and set it to ws_protocol') michael@0: validate_subprotocol(self._request.ws_protocol, hixie=False) michael@0: michael@0: self._logger.debug( michael@0: 'Subprotocol accepted: %r', michael@0: self._request.ws_protocol) michael@0: else: michael@0: if self._request.ws_protocol is not None: michael@0: raise HandshakeException( michael@0: 'ws_protocol must be None when the client didn\'t ' michael@0: 'request any subprotocol') michael@0: michael@0: self._send_handshake(accept) michael@0: except HandshakeException, e: michael@0: if not e.status: michael@0: # Fallback to 400 bad request by default. michael@0: e.status = common.HTTP_STATUS_BAD_REQUEST michael@0: raise e michael@0: michael@0: def _get_origin(self): michael@0: if self._request.ws_version is _VERSION_HYBI08: michael@0: origin_header = common.SEC_WEBSOCKET_ORIGIN_HEADER michael@0: else: michael@0: origin_header = common.ORIGIN_HEADER michael@0: origin = self._request.headers_in.get(origin_header) michael@0: if origin is None: michael@0: self._logger.debug('Client request does not have origin header') michael@0: self._request.ws_origin = origin michael@0: michael@0: def _check_version(self): michael@0: version = get_mandatory_header(self._request, michael@0: common.SEC_WEBSOCKET_VERSION_HEADER) michael@0: if version == _VERSION_HYBI08_STRING: michael@0: return _VERSION_HYBI08 michael@0: if version == _VERSION_LATEST_STRING: michael@0: return _VERSION_LATEST michael@0: michael@0: if version.find(',') >= 0: michael@0: raise HandshakeException( michael@0: 'Multiple versions (%r) are not allowed for header %s' % michael@0: (version, common.SEC_WEBSOCKET_VERSION_HEADER), michael@0: status=common.HTTP_STATUS_BAD_REQUEST) michael@0: raise VersionException( michael@0: 'Unsupported version %r for header %s' % michael@0: (version, common.SEC_WEBSOCKET_VERSION_HEADER), michael@0: supported_versions=', '.join(map(str, _SUPPORTED_VERSIONS))) michael@0: michael@0: def _set_protocol(self): michael@0: self._request.ws_protocol = None michael@0: # MOZILLA michael@0: self._request.sts = None michael@0: # /MOZILLA michael@0: michael@0: protocol_header = self._request.headers_in.get( michael@0: common.SEC_WEBSOCKET_PROTOCOL_HEADER) michael@0: michael@0: if not protocol_header: michael@0: self._request.ws_requested_protocols = None michael@0: return michael@0: michael@0: self._request.ws_requested_protocols = parse_token_list( michael@0: protocol_header) michael@0: self._logger.debug('Subprotocols requested: %r', michael@0: self._request.ws_requested_protocols) michael@0: michael@0: def _parse_extensions(self): michael@0: extensions_header = self._request.headers_in.get( michael@0: common.SEC_WEBSOCKET_EXTENSIONS_HEADER) michael@0: if not extensions_header: michael@0: self._request.ws_requested_extensions = None michael@0: return michael@0: michael@0: if self._request.ws_version is common.VERSION_HYBI08: michael@0: allow_quoted_string=False michael@0: else: michael@0: allow_quoted_string=True michael@0: self._request.ws_requested_extensions = parse_extensions( michael@0: extensions_header, allow_quoted_string=allow_quoted_string) michael@0: michael@0: self._logger.debug( michael@0: 'Extensions requested: %r', michael@0: map(common.ExtensionParameter.name, michael@0: self._request.ws_requested_extensions)) michael@0: michael@0: def _validate_key(self, key): michael@0: if key.find(',') >= 0: michael@0: raise HandshakeException('Request has multiple %s header lines or ' michael@0: 'contains illegal character \',\': %r' % michael@0: (common.SEC_WEBSOCKET_KEY_HEADER, key)) michael@0: michael@0: # Validate michael@0: key_is_valid = False michael@0: try: michael@0: # Validate key by quick regex match before parsing by base64 michael@0: # module. Because base64 module skips invalid characters, we have michael@0: # to do this in advance to make this server strictly reject illegal michael@0: # keys. michael@0: if _SEC_WEBSOCKET_KEY_REGEX.match(key): michael@0: decoded_key = base64.b64decode(key) michael@0: if len(decoded_key) == 16: michael@0: key_is_valid = True michael@0: except TypeError, e: michael@0: pass michael@0: michael@0: if not key_is_valid: michael@0: raise HandshakeException( michael@0: 'Illegal value for header %s: %r' % michael@0: (common.SEC_WEBSOCKET_KEY_HEADER, key)) michael@0: michael@0: return decoded_key michael@0: michael@0: def _get_key(self): michael@0: key = get_mandatory_header( michael@0: self._request, common.SEC_WEBSOCKET_KEY_HEADER) michael@0: michael@0: decoded_key = self._validate_key(key) michael@0: michael@0: self._logger.debug( michael@0: '%s: %r (%s)', michael@0: common.SEC_WEBSOCKET_KEY_HEADER, michael@0: key, michael@0: util.hexify(decoded_key)) michael@0: michael@0: return key michael@0: michael@0: def _send_handshake(self, accept): michael@0: response = [] michael@0: michael@0: response.append('HTTP/1.1 101 Switching Protocols\r\n') michael@0: michael@0: response.append(format_header( michael@0: common.UPGRADE_HEADER, common.WEBSOCKET_UPGRADE_TYPE)) 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_ACCEPT_HEADER, accept)) michael@0: if self._request.ws_protocol is not None: michael@0: response.append(format_header( michael@0: common.SEC_WEBSOCKET_PROTOCOL_HEADER, michael@0: self._request.ws_protocol)) michael@0: if (self._request.ws_extensions is not None and michael@0: len(self._request.ws_extensions) != 0): michael@0: response.append(format_header( michael@0: common.SEC_WEBSOCKET_EXTENSIONS_HEADER, michael@0: format_extensions(self._request.ws_extensions))) michael@0: # MOZILLA: Add HSTS header if requested to michael@0: if self._request.sts is not None: michael@0: response.append(format_header("Strict-Transport-Security", michael@0: self._request.sts)) michael@0: # /MOZILLA michael@0: response.append('\r\n') 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