How to use the httptools.HttpParserUpgrade function in httptools

To help you get started, we’ve selected a few httptools examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github MagicStack / httptools / tests / test_parser.py View on Github external
def test_parser_upgrade_response_1(self):
        m = mock.Mock()

        headers = {}
        m.on_header.side_effect = headers.__setitem__

        p = httptools.HttpResponseParser(m)
        try:
            p.feed_data(UPGRADE_RESPONSE1)
        except httptools.HttpParserUpgrade as ex:
            offset = ex.args[0]
        else:
            self.fail('HttpParserUpgrade was not raised')

        self.assertEqual(UPGRADE_RESPONSE1[offset:], b'data')

        self.assertEqual(p.get_http_version(), '1.1')
        self.assertEqual(p.get_status_code(), 101)

        m.on_status.assert_called_once_with(b'Switching Protocols')

        m.on_headers_complete.assert_called_once_with()
        self.assertEqual(m.on_header.call_count, 6)
        self.assertEqual(len(headers), 6)

        m.on_message_complete.assert_called_once_with()
github trollfot / trinket / src / trinket / request.py View on Github external
def data_received(self, data: bytes):
        try:
            self.parser.feed_data(data)
        except HttpParserUpgrade:
            self.request.upgrade = True
        except (HttpParserError, HttpParserInvalidMethodError) as exc:
            # We should log the exc.
            raise HTTPError(
                HTTPStatus.BAD_REQUEST, 'Unparsable request.')
github encode / uvicorn / uvicorn / protocols / http / httptools_impl.py View on Github external
def data_received(self, data):
        if self.timeout_keep_alive_task is not None:
            self.timeout_keep_alive_task.cancel()
            self.timeout_keep_alive_task = None

        try:
            self.parser.feed_data(data)
        except httptools.parser.errors.HttpParserError as exc:
            msg = "Invalid HTTP request received."
            self.logger.warning(msg)
            self.transport.close()
        except httptools.HttpParserUpgrade as exc:
            self.handle_upgrade()
github pyrates / roll / roll / protocols.py View on Github external
def data_received(self, data):
        if self.websocket is not None:
            # pass the data to the websocket protocol
            self.websocket.data_received(data)
        else:
            try:
                super().data_received(data)
            except HttpParserUpgrade:
                # Upgrade request
                pass
github dwpy / alita / alita / serve / server.py View on Github external
def data_received(self, data):
        self.cancel_timeout_keep_alive_task()
        try:
            if self.parser is None:
                self.headers = []
                self.parser = httptools.HttpRequestParser(self)
            self.parser.feed_data(data)
        except httptools.parser.errors.HttpParserError as exc:
            msg = "Invalid HTTP request received."
            if self.debug:
                msg += "\n" + traceback.format_exc()
            self.logger.error(msg)
            self.on_response(msg)
        except httptools.HttpParserUpgrade as exc:
            #self.handle_upgrade()
            pass
github guyingbo / shadowproxy / legency / shadowproxy_v0_2_5.py View on Github external
async def interact(self, client):
        protocol = HTTPProxyProtocol()
        parser = httptools.HttpRequestParser(protocol)
        s = b""

        while protocol.need_proxy_data:
            data = await client.recv(65536)
            if not data:
                break
            s += data
            try:
                parser.feed_data(data)
            except httptools.HttpParserUpgrade as e:
                break

        version = parser.get_http_version()
        if version == "0.0":
            return
        if self.auth:
            pauth = protocol.headers_dict.get(b"Proxy-Authenticate", None)
            httpauth = b"Basic " + base64.b64encode(b":".join(self.auth))
            if httpauth != pauth:
                await client.sendall(
                    version.encode() + b" 407 Proxy Authentication Required\r\n"
                    b"Connection: close\r\n"
                    b'Proxy-Authenticate: Basic realm="simple"\r\n\r\n'
                )
                raise Exception("Unauthorized HTTP Required")
github Fuyukai / Kyoukai / kyoukai / backends / httptools_.py View on Github external
def handle_parser_exception(self, exc: Exception):
        """
        Handles an exception when parsing.

        This will not call into the app (hence why it is a normal function, and not a coroutine).
        It will also close the connection when it's done.

        :param exc: The exception to handle.
        """
        if isinstance(exc, httptools.HttpParserInvalidMethodError):
            # 405 method not allowed
            r = MethodNotAllowed()
        elif isinstance(exc, httptools.HttpParserError):
            # 400 bad request
            r = BadRequest()
        elif isinstance(exc, httptools.HttpParserUpgrade):
            r = BadRequest(description="Invalid upgrade header.")
        else:
            # internal server error
            r = InternalServerError()

        # Make a fake environment.
        new_environ = to_wsgi_environment(headers=self.headers, method="", path="/",
                                          http_version="1.0", body=None)
        new_environ["SERVER_NAME"] = self.component.get_server_name()
        new_environ["SERVER_PORT"] = str(self.server_port)
        new_environ["REMOTE_ADDR"] = self.ip

        self.raw_write(get_formatted_response(r, new_environ))
        self.parser = httptools.HttpRequestParser(self)
        self.close()
github encode / uvicorn / uvicorn / protocols / http.py View on Github external
def data_received(self, data):
        try:
            self.request_parser.feed_data(data)
        except httptools.HttpParserUpgrade:
            websocket_upgrade(self)
github pyrates / roll / roll / http.py View on Github external
def data_received(self, data: bytes):
        try:
            self.parser.feed_data(data)
        except HttpParserUpgrade:
            # The upgrade raise is done after all the on_x
            # We acted upon the upgrade earlier, so we just pass.
            pass
        except HttpParserError as error:
            # If the parsing failed before on_message_begin, we don't have a
            # response.
            self.response = self.app.Response(self.app, self)
            # Original error stored by httptools.
            if isinstance(error.__context__, HttpError):
                error = error.__context__
                self.response.status = error.status
                self.response.body = error.message
            else:
                self.response.status = HTTPStatus.BAD_REQUEST
                self.response.body = b'Unparsable request:' + str(error.__context__).encode()
            self.task = self.app.loop.create_task(self.write())
github huge-success / sanic / sanic / websocket.py View on Github external
def data_received(self, data):
        if self.websocket is not None:
            # pass the data to the websocket protocol
            self.websocket.data_received(data)
        else:
            try:
                super().data_received(data)
            except HttpParserUpgrade:
                # this is okay, it just indicates we've got an upgrade request
                pass