def connect(self, host, port, resource): self._socket = socket.socket() self.dictionary['server_port'] = port self.dictionary['server_host'] = host self.dictionary['resource'] = resource self._socket.settimeout(int(self.dictionary.get('socket_timeout'))) try: self._socket.connect((host, int(port))) self.isConnected = True if self.dictionary.get('use_tls') == 'True': self._socket = _TLSSocket(self._socket) version = self.dictionary.get('protocol_version') self._handshake = ClientHandshakeProcessor( self._socket, self.dictionary) self._handshake.handshake() request = ClientRequest(self._socket) version_map = { _PROTOCOL_VERSION_HYBI13: common.VERSION_HYBI13} request.ws_version = version_map[version] stream_option = StreamOptions() stream_option.mask_send = True stream_option.unmask_receive = False self._stream = Stream(request, stream_option) return OK_FLAG except Exception, e: self.isConnected = False print(e.message) return ERROR_FLAG
def run(self): """Run the client. Shake hands and then repeat sending message and receiving its echo. """ self._socket = socket.socket() self._socket.settimeout(self._options.socket_timeout) try: self._socket.connect( (self._options.server_host, self._options.server_port)) if self._options.use_tls: self._socket = _TLSSocket(self._socket) self._handshake = ClientHandshakeProcessor(self._socket, self._options) self._handshake.handshake() self._logger.info('Connection established') request = ClientRequest(self._socket) stream_option = StreamOptions() stream_option.mask_send = True stream_option.unmask_receive = False if self._options.use_permessage_deflate is not False: framer = self._options.use_permessage_deflate framer.setup_stream_options(stream_option) self._stream = Stream(request, stream_option) for line in self._options.message.split(','): self._stream.send_message(line) if self._options.verbose: print('Send: %s' % line) try: received = self._stream.receive_message() if self._options.verbose: print('Recv: %s' % received) except Exception as e: if self._options.verbose: print('Error: %s' % e) raise self._do_closing_handshake() finally: self._socket.close()
def _create_request_from_rawdata( read_data, deflate_stream=False, deflate_frame_request=None): req = mock.MockRequest(connection=mock.MockConn(''.join(read_data))) req.ws_version = common.VERSION_HYBI_LATEST stream_options = StreamOptions() stream_options.deflate_stream = deflate_stream req.ws_extension_processors = [] if deflate_frame_request is not None: processor = DeflateFrameExtensionProcessor(deflate_frame_request) response = processor.get_extension_response() if response is not None: processor.setup_stream_options(stream_options) req.ws_extension_processors.append(processor) req.ws_stream = Stream(req, stream_options) return req
def _prepare_stream(self, host, port, which): self._stream_name = which; self._socket = socket.create_connection(address=(host, port), timeout=self._options.socket_timeout) uri = '/%d/%s' % (self._options.tstamp, which) handshake = ClientHandshakeProcessor(self._socket, host, port) handshake.handshake(uri) request = ClientRequest(self._socket) request.ws_version = mod_pywebsocket.common.VERSION_HYBI13 stream_option = StreamOptions() stream_option.mask_send = True stream_option.unmask_receive = False self._stream = Stream(request, stream_option)
def __init__(self, uri=None, headers_in={}, connection=None, method='GET', protocol='HTTP/1.1', is_https=False): """Construct an instance. Arguments: uri: URI of the request. headers_in: Request headers. connection: Connection used for the request. method: request method. is_https: Whether this request is over SSL. See the document of mod_python Request for details. """ self.uri = uri self.unparsed_uri = uri self.connection = connection self.method = method self.protocol = protocol self.headers_in = MockTable(headers_in) # self.is_https_ needs to be accessible from tests. To avoid name # conflict with self.is_https(), it is named as such. self.is_https_ = is_https self.ws_stream = Stream(self, StreamOptions()) self.ws_close_code = None self.ws_close_reason = None self.ws_version = common.VERSION_HYBI_LATEST self.ws_deflate = False
def do_handshake(self): check_header_lines(self._request, _MANDATORY_HEADERS) self._request.ws_resource = self._request.uri unused_host = get_mandatory_header(self._request, common.HOST_HEADER) self._get_origin() self._check_version() self._set_protocol() self._set_extensions() key = self._get_key() (accept, accept_binary) = compute_accept(key) self._logger.debug('Sec-WebSocket-Accept: %r (%s)', accept, util.hexify(accept_binary)) self._logger.debug('IETF HyBi 07 protocol') self._request.ws_version = common.VERSION_HYBI07 stream_options = StreamOptions() stream_options.deflate = self._request.ws_deflate self._request.ws_stream = Stream(self._request, stream_options) self._request.ws_close_code = None self._request.ws_close_reason = None self._dispatcher.do_extra_handshake(self._request) if self._request.ws_requested_protocols is not None: if self._request.ws_protocol is None: raise HandshakeError( 'do_extra_handshake must choose one subprotocol from ' 'ws_requested_protocols and set it to ws_protocol') # TODO(tyoshino): Validate selected subprotocol value. self._logger.debug('Subprotocol accepted: %r', self._request.ws_protocol) else: if self._request.ws_protocol is not None: raise HandshakeError( 'ws_protocol must be None when the client didn\'t request ' 'any subprotocol') self._send_handshake(accept) self._logger.debug('Sent opening handshake response')
def do_handshake(self): self._request.ws_close_code = None self._request.ws_close_reason = None # Parsing. self._validate_request() self._request.ws_resource = self._request.uri self._request.ws_version = self._check_version() try: self._get_origin() self._set_protocol() self._parse_extensions() self._set_accept() self._logger.debug('Protocol version is ' + self._protocol_rfc()) # Setup extension processors. self._request.ws_extension_processors = self._get_extension_processors_requested( ) # List of extra headers. The extra handshake handler may add header # data as name/value pairs to this list and pywebsocket appends # them to the WebSocket handshake. self._request.extra_headers = [] # Extra handshake handler may modify/remove processors. self._dispatcher.do_extra_handshake(self._request) stream_options = StreamOptions() self._process_extensions(stream_options) self._request.ws_stream = Stream(self._request, stream_options) if self._request.ws_requested_protocols is not None: if self._request.ws_protocol is None: raise HandshakeException( 'do_extra_handshake must choose one subprotocol from ' 'ws_requested_protocols and set it to ws_protocol') validate_subprotocol(self._request.ws_protocol) self._logger.debug('Subprotocol accepted: %r', self._request.ws_protocol) else: if self._request.ws_protocol is not None: raise HandshakeException( 'ws_protocol must be None when the client didn\'t ' 'request any subprotocol') self._send_handshake() except HandshakeException as e: if not e.status: # Fallback to 400 bad request by default. e.status = common.HTTP_STATUS_BAD_REQUEST raise e
def connect(self): self._socket = socket.socket() self._socket.settimeout(int(self.dictionary.get('socket_timeout'))) try: self._socket.connect((self.dictionary.get('server_host'), int(self.dictionary.get('server_port')))) if self.dictionary.get('use_tls') == 'True': self._socket = _TLSSocket(self._socket) version = self.dictionary.get('protocol_version') self._handshake = ClientHandshakeProcessor( self._socket, self.dictionary) self._handshake.handshake() self._logger.info('Connection established') request = ClientRequest(self._socket) version_map = { _PROTOCOL_VERSION_HYBI13: common.VERSION_HYBI13} request.ws_version = version_map[version] stream_option = StreamOptions() stream_option.mask_send = True stream_option.unmask_receive = False if self.dictionary.get('deflate_stream') == 'True': stream_option.deflate_stream = True if self.dictionary.get('deflate_frame') == 'True': processor = True processor.setup_stream_options(stream_option) self._stream = Stream(request, stream_option) listen = ListenSocket(self, self.received) write = WriteSocket(self, self.toSend) listen.start() write.start() finally: print "po powitaniu, serwer oczekuje na dane"
def _prepare_stream(self, host, port, which): import mod_pywebsocket.common from mod_pywebsocket.stream import Stream from mod_pywebsocket.stream import StreamOptions self._socket = socket.socket() self._socket.settimeout(10) # self._socket.settimeout(float(self._options[13])) self._socket.connect((host, port)) uri = '/%d/%s' % (int(time.time()), which) handshake = wsclient.ClientHandshakeProcessor(self._socket, host, port) handshake.handshake(uri) request = wsclient.ClientRequest(self._socket) request.ws_version = mod_pywebsocket.common.VERSION_HYBI13 stream_option = StreamOptions() stream_option.mask_send = True stream_option.unmask_receive = False self._stream = Stream(request, stream_option)
def _create_blocking_request(): """Creates MockRequest. Data written to a MockRequest can be read out by calling request.connection.written_data(). """ req = mock.MockRequest(connection=mock.MockBlockingConn()) req.ws_version = common.VERSION_HYBI_LATEST stream_options = StreamOptions() req.ws_stream = Stream(req, stream_options) return req
def _create_request_from_rawdata( read_data, deflate_stream=False, deflate_frame_request=None, perframe_compression_request=None, permessage_compression_request=None): req = mock.MockRequest(connection=mock.MockConn(''.join(read_data))) req.ws_version = common.VERSION_HYBI_LATEST stream_options = StreamOptions() stream_options.deflate_stream = deflate_stream req.ws_extension_processors = [] if deflate_frame_request is not None: processor = DeflateFrameExtensionProcessor(deflate_frame_request) _install_extension_processor(processor, req, stream_options) elif perframe_compression_request is not None: processor = PerFrameCompressionExtensionProcessor( perframe_compression_request) _install_extension_processor(processor, req, stream_options) elif permessage_compression_request is not None: processor = PerMessageCompressionExtensionProcessor( permessage_compression_request) _install_extension_processor(processor, req, stream_options) req.ws_stream = Stream(req, stream_options) return req
def connect(self, host, port, resource): self._socket = socket.socket() self.dictionary['server_port'] = port self.dictionary['server_host'] = host self.dictionary['resource'] = resource self._socket.settimeout(int(self.dictionary.get('socket_timeout'))) try: logger.logInfo(NAME + "connecting to " + host + ":" + str(port) + resource ) self._socket.connect((host, int(port))) if self.dictionary.get('use_tls') == 'True': self._socket = _TLSSocket(self._socket) version = self.dictionary.get('protocol_version') self._handshake = ClientHandshakeProcessor( self._socket, self.dictionary) self._handshake.handshake() logger.logInfo(NAME + 'Nawiazano polaczenie z ' + host+":"+str(port)) request = ClientRequest(self._socket) version_map = { _PROTOCOL_VERSION_HYBI13: common.VERSION_HYBI13} request.ws_version = version_map[version] stream_option = StreamOptions() stream_option.mask_send = True stream_option.unmask_receive = False self._stream = Stream(request, stream_option) return OK_FLAG except Exception, e: logger.logError(NAME+"Wystapil problem") logger.logError(NAME + e.message) print(e.message) return ERROR_FLAG
def connect(self, host, port, resource): self.dictionary['server_port'] = port self.dictionary['server_host'] = host self.dictionary['resource'] = resource self._socket = socket.socket() self._socket.settimeout(int(self.dictionary.get('socket_timeout'))) try: logging.info(NAME + "connecting to " + host + ":" + str(port) + resource ) self._socket.connect((host,int(port))) if self.dictionary.get('use_tls') == 'True': self._socket = _TLSSocket(self._socket) version = self.dictionary.get('protocol_version') self._handshake = ClientHandshakeProcessor( self._socket, self.dictionary) self._handshake.handshake() request = ClientRequest(self._socket) version_map = { _PROTOCOL_VERSION_HYBI13: common.VERSION_HYBI13} request.ws_version = version_map[version] stream_option = StreamOptions() stream_option.mask_send = True stream_option.unmask_receive = False self._stream = Stream(request, stream_option) logging.info(NAME+ "Polaczenie nawiazane") return CONNECTION_OK_FLAG except Exception, e: self._socket.close() logging.error(NAME+ "Nie mozna nawiazac polaczenia") logging.error(NAME + e.message) return CONNECTION_PROBLEM_FLAG
def _create_request_from_rawdata(read_data, deflate_stream=False, deflate_frame_request=None, perframe_compression_request=None, permessage_compression_request=None): req = mock.MockRequest(connection=mock.MockConn(''.join(read_data))) req.ws_version = common.VERSION_HYBI_LATEST stream_options = StreamOptions() stream_options.deflate_stream = deflate_stream req.ws_extension_processors = [] if deflate_frame_request is not None: processor = DeflateFrameExtensionProcessor(deflate_frame_request) _install_extension_processor(processor, req, stream_options) elif perframe_compression_request is not None: processor = PerFrameCompressionExtensionProcessor( perframe_compression_request) _install_extension_processor(processor, req, stream_options) elif permessage_compression_request is not None: processor = PerMessageCompressionExtensionProcessor( permessage_compression_request) _install_extension_processor(processor, req, stream_options) req.ws_stream = Stream(req, stream_options) return req
def _create_request_from_rawdata(read_data, permessage_deflate_request=None): req = mock.MockRequest(connection=mock.MockConn(read_data)) req.ws_version = common.VERSION_HYBI_LATEST req.ws_extension_processors = [] processor = None if permessage_deflate_request is not None: processor = PerMessageDeflateExtensionProcessor( permessage_deflate_request) stream_options = StreamOptions() if processor is not None: _install_extension_processor(processor, req, stream_options) req.ws_stream = Stream(req, stream_options) return req
def run(self): """Run the client. Shake hands and then repeat sending message and receiving its echo. """ self._socket = socket.socket() self._socket.settimeout(self._options.socket_timeout) try: self._socket.connect((self._options.server_host, self._options.server_port)) if self._options.use_tls: self._socket = _TLSSocket( self._socket, self._options.tls_module, self._options.tls_version, self._options.disable_tls_compression) version = self._options.protocol_version if (version == _PROTOCOL_VERSION_HYBI08 or version == _PROTOCOL_VERSION_HYBI13): self._handshake = ClientHandshakeProcessor( self._socket, self._options) elif version == _PROTOCOL_VERSION_HYBI00: self._handshake = ClientHandshakeProcessorHybi00( self._socket, self._options) else: raise ValueError( 'Invalid --protocol-version flag: %r' % version) self._handshake.handshake() self._logger.info('Connection established') request = ClientRequest(self._socket) version_map = { _PROTOCOL_VERSION_HYBI08: common.VERSION_HYBI08, _PROTOCOL_VERSION_HYBI13: common.VERSION_HYBI13, _PROTOCOL_VERSION_HYBI00: common.VERSION_HYBI00} request.ws_version = version_map[version] if (version == _PROTOCOL_VERSION_HYBI08 or version == _PROTOCOL_VERSION_HYBI13): stream_option = StreamOptions() stream_option.mask_send = True stream_option.unmask_receive = False if self._options.deflate_frame is not False: processor = self._options.deflate_frame processor.setup_stream_options(stream_option) if self._options.use_permessage_deflate is not False: framer = self._options.use_permessage_deflate framer.setup_stream_options(stream_option) self._stream = Stream(request, stream_option) elif version == _PROTOCOL_VERSION_HYBI00: self._stream = StreamHixie75(request, True) for line in self._options.message.split(','): self._stream.send_message(line) if self._options.verbose: print('Send: %s' % line) try: received = self._stream.receive_message() if self._options.verbose: print('Recv: %s' % received) except Exception, e: if self._options.verbose: print('Error: %s' % e) raise self._do_closing_handshake()
def do_handshake(self): self._request.ws_close_code = None self._request.ws_close_reason = None # Parsing. check_connect_method(self._request) validate_mandatory_header(self._request, ':protocol', 'websocket') self._request.ws_resource = self._request.uri get_mandatory_header(self._request, 'authority') self._request.ws_version = self._check_version() try: self._get_origin() self._set_protocol() self._parse_extensions() # Setup extension processors. self._request.ws_extension_processors = self._get_extension_processors_requested() # List of extra headers. The extra handshake handler may add header # data as name/value pairs to this list and pywebsocket appends # them to the WebSocket handshake. self._request.extra_headers = [] # Extra handshake handler may modify/remove processors. self._dispatcher.do_extra_handshake(self._request) processors = [ processor for processor in self._request.ws_extension_processors if processor is not None ] # Ask each processor if there are extensions on the request which # cannot co-exist. When processor decided other processors cannot # co-exist with it, the processor marks them (or itself) as # "inactive". The first extension processor has the right to # make the final call. for processor in reversed(processors): if processor.is_active(): processor.check_consistency_with_other_processors( processors) processors = [ processor for processor in processors if processor.is_active() ] accepted_extensions = [] stream_options = StreamOptions() for index, processor in enumerate(processors): if not processor.is_active(): continue extension_response = processor.get_extension_response() if extension_response is None: # Rejected. continue accepted_extensions.append(extension_response) processor.setup_stream_options(stream_options) # Inactivate all of the following compression extensions. for j in range(index + 1, len(processors)): processors[j].set_active(False) if len(accepted_extensions) > 0: self._request.ws_extensions = accepted_extensions self._logger.debug( 'Extensions accepted: %r', list( map(common.ExtensionParameter.name, accepted_extensions))) else: self._request.ws_extensions = None self._request.ws_stream = self._create_stream(stream_options) if self._request.ws_requested_protocols is not None: if self._request.ws_protocol is None: raise HandshakeException( 'do_extra_handshake must choose one subprotocol from ' 'ws_requested_protocols and set it to ws_protocol') validate_subprotocol(self._request.ws_protocol) self._logger.debug('Subprotocol accepted: %r', self._request.ws_protocol) else: if self._request.ws_protocol is not None: raise HandshakeException( 'ws_protocol must be None when the client didn\'t ' 'request any subprotocol') self._prepare_handshake_response() except HandshakeException as e: if not e.status: # Fallback to 400 bad request by default. e.status = common.HTTP_STATUS_BAD_REQUEST raise e
def run(self): """Run the client. Shake hands and then repeat sending message and receiving its echo. """ self._socket = socket.socket() self._socket.settimeout(self._options.socket_timeout) try: self._socket.connect((self._options.server_host, self._options.server_port)) if self._options.use_tls: self._socket = _TLSSocket(self._socket) version = self._options.protocol_version if version == _PROTOCOL_VERSION_HYBI08 or version == _PROTOCOL_VERSION_HYBI13: self._handshake = ClientHandshakeProcessor(self._socket, self._options) elif version == _PROTOCOL_VERSION_HYBI00: self._handshake = ClientHandshakeProcessorHybi00(self._socket, self._options) elif version == _PROTOCOL_VERSION_HIXIE75: self._handshake = ClientHandshakeProcessorHixie75(self._socket, self._options) else: raise ValueError("Invalid --protocol-version flag: %r" % version) self._handshake.handshake() self._logger.info("Connection established") request = ClientRequest(self._socket) version_map = { _PROTOCOL_VERSION_HYBI08: common.VERSION_HYBI08, _PROTOCOL_VERSION_HYBI13: common.VERSION_HYBI13, _PROTOCOL_VERSION_HYBI00: common.VERSION_HYBI00, _PROTOCOL_VERSION_HIXIE75: common.VERSION_HIXIE75, } request.ws_version = version_map[version] if version == _PROTOCOL_VERSION_HYBI08 or version == _PROTOCOL_VERSION_HYBI13: stream_option = StreamOptions() stream_option.mask_send = True stream_option.unmask_receive = False if self._options.deflate_stream: stream_option.deflate_stream = True if self._options.deflate_frame is not False: processor = self._options.deflate_frame processor.setup_stream_options(stream_option) self._stream = Stream(request, stream_option) elif version == _PROTOCOL_VERSION_HYBI00: self._stream = StreamHixie75(request, True) elif version == _PROTOCOL_VERSION_HIXIE75: self._stream = StreamHixie75(request) for line in self._options.message.split(","): self._stream.send_message(line) if self._options.verbose: print "Send: %s" % line try: received = self._stream.receive_message() if self._options.verbose: print "Recv: %s" % received except Exception, e: if self._options.verbose: print "Error: %s" % e raise if version != _PROTOCOL_VERSION_HIXIE75: self._do_closing_handshake()
# connect to kiwi server print ("Trying to contact server...") try: kiwisocket = socket.socket() kiwisocket.connect((kiwihost, kiwiport)) except: print ("Failed to connect") exit() print ("Socket open...") uri = '/%d/%s' % (int(time.time()), 'W/F') handshake_wf = wsclient.ClientHandshakeProcessor(kiwisocket, kiwihost, kiwiport) handshake_wf.handshake(uri) request_wf = wsclient.ClientRequest(kiwisocket) request_wf.ws_version = mod_pywebsocket.common.VERSION_HYBI13 stream_option_wf = StreamOptions() stream_option_wf.mask_send = True stream_option_wf.unmask_receive = False wf_stream = Stream(request_wf, stream_option_wf) print ("Waterfall data stream active...") # send a sequence of messages to the server, hardcoded for now # max wf speed, no compression msg_list = ['SET auth t=kiwi p=%s'%kiwi_password, 'SET zoom=%d start=%d'%(zoom,cnt),\ 'SET maxdb=0 mindb=-100', 'SET wf_speed=4', 'SET wf_comp=0', 'SET maxdb=-10 mindb=-110'] for msg in msg_list: wf_stream.send_message(msg) print ("Starting to retrieve waterfall data...") ########################### SND connection
class Handshaker(object): """This class performs WebSocket handshake.""" def __init__(self, request, dispatcher): """Construct an instance. Args: request: mod_python request. dispatcher: Dispatcher (dispatch.Dispatcher). Handshaker will add attributes such as ws_resource during handshake. """ self._logger = util.get_class_logger(self) self._request = request self._dispatcher = dispatcher def do_handshake(self): check_request_line(self._request) validate_mandatory_header(self._request, common.UPGRADE_HEADER, common.WEBSOCKET_UPGRADE_TYPE) connection = get_mandatory_header(self._request, common.CONNECTION_HEADER) try: connection_tokens = parse_token_list(connection) except HandshakeError, e: raise HandshakeError('Failed to parse %s: %s' % (common.CONNECTION_HEADER, e)) connection_is_valid = False for token in connection_tokens: if token.lower() == common.UPGRADE_CONNECTION_TYPE.lower(): connection_is_valid = True break if not connection_is_valid: raise HandshakeError( '%s header doesn\'t contain "%s"' % (common.CONNECTION_HEADER, common.UPGRADE_CONNECTION_TYPE)) self._request.ws_resource = self._request.uri unused_host = get_mandatory_header(self._request, common.HOST_HEADER) self._get_origin() self._check_version() self._set_protocol() self._set_extensions() key = self._get_key() (accept, accept_binary) = compute_accept(key) self._logger.debug('Sec-WebSocket-Accept: %r (%s)', accept, util.hexify(accept_binary)) self._logger.debug('IETF HyBi 07 protocol') self._request.ws_version = common.VERSION_HYBI07 stream_options = StreamOptions() stream_options.deflate = self._request.ws_deflate self._request.ws_stream = Stream(self._request, stream_options) self._request.ws_close_code = None self._request.ws_close_reason = None self._dispatcher.do_extra_handshake(self._request) if self._request.ws_requested_protocols is not None: if self._request.ws_protocol is None: raise HandshakeError( 'do_extra_handshake must choose one subprotocol from ' 'ws_requested_protocols and set it to ws_protocol') # TODO(tyoshino): Validate selected subprotocol value. self._logger.debug('Subprotocol accepted: %r', self._request.ws_protocol) else: if self._request.ws_protocol is not None: raise HandshakeError( 'ws_protocol must be None when the client didn\'t request ' 'any subprotocol') self._send_handshake(accept) self._logger.debug('Sent opening handshake response')
try: mysocket = socket.socket() mysocket.connect((host, port)) except: print "Failed to connect, sleeping and reconnecting" exit() print "Socket open..." uri = '/%d/%s' % (int(time.time()), 'W/F') handshake = wsclient.ClientHandshakeProcessor(mysocket, host, port) handshake.handshake(uri) request = wsclient.ClientRequest(mysocket) request.ws_version = mod_pywebsocket.common.VERSION_HYBI13 stream_option = StreamOptions() stream_option.mask_send = True stream_option.unmask_receive = False mystream = Stream(request, stream_option) print "Data stream active..." # send a sequence of messages to the server, hardcoded for now msg_list = ['SET auth t=kiwi p=', 'SET zoom=%d start=%d'%(zoom,offset),\ 'SET maxdb=0 mindb=-100', 'SET wf_speed=4', 'SET wf_comp=0'] for msg in msg_list: mystream.send_message(msg) print "Starting to retrieve waterfall data..." # number of samples to draw from server length = options['length']
def do_handshake(self): self._request.ws_close_code = None self._request.ws_close_reason = None # Parsing. check_request_line(self._request) validate_mandatory_header(self._request, common.UPGRADE_HEADER, common.WEBSOCKET_UPGRADE_TYPE) self._validate_connection_header() self._request.ws_resource = self._request.uri unused_host = get_mandatory_header(self._request, common.HOST_HEADER) self._request.ws_version = self._check_version() try: self._get_origin() self._set_protocol() self._parse_extensions() # Key validation, response generation. key = self._get_key() accept = compute_accept(key) self._logger.debug('%s: %r (%s)', common.SEC_WEBSOCKET_ACCEPT_HEADER, accept, util.hexify(base64.b64decode(accept))) self._logger.debug('Protocol version is RFC 6455') # Setup extension processors. processors = [] if self._request.ws_requested_extensions is not None: for extension_request in self._request.ws_requested_extensions: processor = get_extension_processor(extension_request) # Unknown extension requests are just ignored. if processor is not None: processors.append(processor) self._request.ws_extension_processors = processors # List of extra headers. The extra handshake handler may add header # data as name/value pairs to this list and pywebsocket appends # them to the WebSocket handshake. self._request.extra_headers = [] # Extra handshake handler may modify/remove processors. self._dispatcher.do_extra_handshake(self._request) processors = [ processor for processor in self._request.ws_extension_processors if processor is not None ] # Ask each processor if there are extensions on the request which # cannot co-exist. When processor decided other processors cannot # co-exist with it, the processor marks them (or itself) as # "inactive". The first extension processor has the right to # make the final call. for processor in reversed(processors): if processor.is_active(): processor.check_consistency_with_other_processors( processors) processors = [ processor for processor in processors if processor.is_active() ] accepted_extensions = [] stream_options = StreamOptions() for index, processor in enumerate(processors): if not processor.is_active(): continue extension_response = processor.get_extension_response() if extension_response is None: # Rejected. continue accepted_extensions.append(extension_response) processor.setup_stream_options(stream_options) # Inactivate all of the following compression extensions. for j in range(index + 1, len(processors)): processors[j].set_active(False) if len(accepted_extensions) > 0: self._request.ws_extensions = accepted_extensions self._logger.debug( 'Extensions accepted: %r', list( map(common.ExtensionParameter.name, accepted_extensions))) else: self._request.ws_extensions = None self._request.ws_stream = self._create_stream(stream_options) if self._request.ws_requested_protocols is not None: if self._request.ws_protocol is None: raise HandshakeException( 'do_extra_handshake must choose one subprotocol from ' 'ws_requested_protocols and set it to ws_protocol') validate_subprotocol(self._request.ws_protocol) self._logger.debug('Subprotocol accepted: %r', self._request.ws_protocol) else: if self._request.ws_protocol is not None: raise HandshakeException( 'ws_protocol must be None when the client didn\'t ' 'request any subprotocol') self._send_handshake(accept) except HandshakeException as e: if not e.status: # Fallback to 400 bad request by default. e.status = common.HTTP_STATUS_BAD_REQUEST raise e
def do_handshake(self): self._request.ws_close_code = None self._request.ws_close_reason = None # Parsing. check_request_line(self._request) validate_mandatory_header( self._request, common.UPGRADE_HEADER, common.WEBSOCKET_UPGRADE_TYPE) self._validate_connection_header() self._request.ws_resource = self._request.uri unused_host = get_mandatory_header(self._request, common.HOST_HEADER) self._request.ws_version = self._check_version() # This handshake must be based on latest hybi. We are responsible to # fallback to HTTP on handshake failure as latest hybi handshake # specifies. try: self._get_origin() self._set_protocol() self._parse_extensions() # Key validation, response generation. key = self._get_key() (accept, accept_binary) = compute_accept(key) self._logger.debug( '%s: %r (%s)', common.SEC_WEBSOCKET_ACCEPT_HEADER, accept, util.hexify(accept_binary)) self._logger.debug('Protocol version is RFC 6455') # Setup extension processors. processors = [] if self._request.ws_requested_extensions is not None: for extension_request in self._request.ws_requested_extensions: processor = get_extension_processor(extension_request) # Unknown extension requests are just ignored. if processor is not None: processors.append(processor) self._request.ws_extension_processors = processors # Extra handshake handler may modify/remove processors. self._dispatcher.do_extra_handshake(self._request) processors = filter(lambda processor: processor is not None, self._request.ws_extension_processors) accepted_extensions = [] # We need to take care of mux extension here. Extensions that # are placed before mux should be applied to logical channels. mux_index = -1 for i, processor in enumerate(processors): if processor.name() == common.MUX_EXTENSION: mux_index = i break if mux_index >= 0: mux_processor = processors[mux_index] logical_channel_processors = processors[:mux_index] processors = processors[mux_index+1:] for processor in logical_channel_processors: extension_response = processor.get_extension_response() if extension_response is None: # Rejected. continue accepted_extensions.append(extension_response) # Pass a shallow copy of accepted_extensions as extensions for # logical channels. mux_response = mux_processor.get_extension_response( self._request, accepted_extensions[:]) if mux_response is not None: accepted_extensions.append(mux_response) stream_options = StreamOptions() # When there is mux extension, here, |processors| contain only # prosessors for extensions placed after mux. for processor in processors: extension_response = processor.get_extension_response() if extension_response is None: # Rejected. continue accepted_extensions.append(extension_response) processor.setup_stream_options(stream_options) if len(accepted_extensions) > 0: self._request.ws_extensions = accepted_extensions self._logger.debug( 'Extensions accepted: %r', map(common.ExtensionParameter.name, accepted_extensions)) else: self._request.ws_extensions = None self._request.ws_stream = self._create_stream(stream_options) if self._request.ws_requested_protocols is not None: if self._request.ws_protocol is None: raise HandshakeException( 'do_extra_handshake must choose one subprotocol from ' 'ws_requested_protocols and set it to ws_protocol') validate_subprotocol(self._request.ws_protocol, hixie=False) self._logger.debug( 'Subprotocol accepted: %r', self._request.ws_protocol) else: if self._request.ws_protocol is not None: raise HandshakeException( 'ws_protocol must be None when the client didn\'t ' 'request any subprotocol') self._send_handshake(accept) except HandshakeException, e: if not e.status: # Fallback to 400 bad request by default. e.status = common.HTTP_STATUS_BAD_REQUEST raise e
def do_handshake(self): self._request.ws_close_code = None self._request.ws_close_reason = None # Parsing. check_request_line(self._request) validate_mandatory_header(self._request, common.UPGRADE_HEADER, common.WEBSOCKET_UPGRADE_TYPE) self._validate_connection_header() self._request.ws_resource = self._request.uri unused_host = get_mandatory_header(self._request, common.HOST_HEADER) self._request.ws_version = self._check_version() # This handshake must be based on latest hybi. We are responsible to # fallback to HTTP on handshake failure as latest hybi handshake # specifies. try: self._get_origin() self._set_protocol() self._parse_extensions() # Key validation, response generation. key = self._get_key() (accept, accept_binary) = compute_accept(key) self._logger.debug('%s: %r (%s)', common.SEC_WEBSOCKET_ACCEPT_HEADER, accept, util.hexify(accept_binary)) self._logger.debug('Protocol version is RFC 6455') # Setup extension processors. processors = [] if self._request.ws_requested_extensions is not None: for extension_request in self._request.ws_requested_extensions: processor = get_extension_processor(extension_request) # Unknown extension requests are just ignored. if processor is not None: processors.append(processor) self._request.ws_extension_processors = processors # List of extra headers. The extra handshake handler may add header # data as name/value pairs to this list and pywebsocket appends # them to the WebSocket handshake. self._request.extra_headers = [] # Extra handshake handler may modify/remove processors. self._dispatcher.do_extra_handshake(self._request) processors = filter(lambda processor: processor is not None, self._request.ws_extension_processors) # Ask each processor if there are extensions on the request which # cannot co-exist. When processor decided other processors cannot # co-exist with it, the processor marks them (or itself) as # "inactive". The first extension processor has the right to # make the final call. for processor in reversed(processors): if processor.is_active(): processor.check_consistency_with_other_processors( processors) processors = filter(lambda processor: processor.is_active(), processors) accepted_extensions = [] # We need to take into account of mux extension here. # If mux extension exists: # - Remove processors of extensions for logical channel, # which are processors located before the mux processor # - Pass extension requests for logical channel to mux processor # - Attach the mux processor to the request. It will be referred # by dispatcher to see whether the dispatcher should use mux # handler or not. mux_index = -1 for i, processor in enumerate(processors): if processor.name() == common.MUX_EXTENSION: mux_index = i break if mux_index >= 0: logical_channel_extensions = [] for processor in processors[:mux_index]: logical_channel_extensions.append(processor.request()) processor.set_active(False) self._request.mux_processor = processors[mux_index] self._request.mux_processor.set_extensions( logical_channel_extensions) processors = filter(lambda processor: processor.is_active(), processors) stream_options = StreamOptions() for index, processor in enumerate(processors): if not processor.is_active(): continue extension_response = processor.get_extension_response() if extension_response is None: # Rejected. continue accepted_extensions.append(extension_response) processor.setup_stream_options(stream_options) if not is_compression_extension(processor.name()): continue # Inactivate all of the following compression extensions. for j in xrange(index + 1, len(processors)): if is_compression_extension(processors[j].name()): processors[j].set_active(False) if len(accepted_extensions) > 0: self._request.ws_extensions = accepted_extensions self._logger.debug( 'Extensions accepted: %r', map(common.ExtensionParameter.name, accepted_extensions)) else: self._request.ws_extensions = None self._request.ws_stream = self._create_stream(stream_options) if self._request.ws_requested_protocols is not None: if self._request.ws_protocol is None: raise HandshakeException( 'do_extra_handshake must choose one subprotocol from ' 'ws_requested_protocols and set it to ws_protocol') validate_subprotocol(self._request.ws_protocol) self._logger.debug('Subprotocol accepted: %r', self._request.ws_protocol) else: if self._request.ws_protocol is not None: raise HandshakeException( 'ws_protocol must be None when the client didn\'t ' 'request any subprotocol') self._send_handshake(accept) except HandshakeException, e: if not e.status: # Fallback to 400 bad request by default. e.status = common.HTTP_STATUS_BAD_REQUEST raise e
def do_handshake(self): self._request.ws_close_code = None self._request.ws_close_reason = None # Parsing. check_request_line(self._request) validate_mandatory_header(self._request, common.UPGRADE_HEADER, common.WEBSOCKET_UPGRADE_TYPE) self._validate_connection_header() self._request.ws_resource = self._request.uri unused_host = get_mandatory_header(self._request, common.HOST_HEADER) self._request.ws_version = self._check_version() # This handshake must be based on latest hybi. We are responsible to # fallback to HTTP on handshake failure as latest hybi handshake # specifies. try: self._get_origin() self._set_protocol() self._parse_extensions() # Key validation, response generation. key = self._get_key() (accept, accept_binary) = compute_accept(key) self._logger.debug('%s: %r (%s)', common.SEC_WEBSOCKET_ACCEPT_HEADER, accept, util.hexify(accept_binary)) self._logger.debug('IETF HyBi protocol') # Setup extension processors. processors = [] if self._request.ws_requested_extensions is not None: for extension_request in self._request.ws_requested_extensions: processor = get_extension_processor(extension_request) # Unknown extension requests are just ignored. if processor is not None: processors.append(processor) self._request.ws_extension_processors = processors # Extra handshake handler may modify/remove processors. self._dispatcher.do_extra_handshake(self._request) stream_options = StreamOptions() self._request.ws_extensions = None for processor in self._request.ws_extension_processors: if processor is None: # Some processors may be removed by extra handshake # handler. continue extension_response = processor.get_extension_response() if extension_response is None: # Rejected. continue if self._request.ws_extensions is None: self._request.ws_extensions = [] self._request.ws_extensions.append(extension_response) processor.setup_stream_options(stream_options) if self._request.ws_extensions is not None: self._logger.debug( 'Extensions accepted: %r', map(common.ExtensionParameter.name, self._request.ws_extensions)) self._request.ws_stream = Stream(self._request, stream_options) if self._request.ws_requested_protocols is not None: if self._request.ws_protocol is None: raise HandshakeException( 'do_extra_handshake must choose one subprotocol from ' 'ws_requested_protocols and set it to ws_protocol') validate_subprotocol(self._request.ws_protocol, hixie=False) self._logger.debug('Subprotocol accepted: %r', self._request.ws_protocol) else: if self._request.ws_protocol is not None: raise HandshakeException( 'ws_protocol must be None when the client didn\'t ' 'request any subprotocol') self._send_handshake(accept) except HandshakeException, e: if not e.status: # Fallback to 400 bad request by default. e.status = common.HTTP_STATUS_BAD_REQUEST raise e