How to use the h11.RemoteProtocolError function in h11

To help you get started, we’ve selected a few h11 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 dismantl / CaseHarvester / src / mjcs / db.py View on Github external
def db_session():
    """Provide a transactional scope around a series of operations."""
    db_factory = sessionmaker(bind = config.db_engine)
    db = db_factory()
    try:
        yield db
        try:
            db.commit()
        except h11.RemoteProtocolError: # happens sometimes, try again
            db.commit()
    except:
        db.rollback()
        raise
    finally:
        db.close()
github python-hyper / h11 / fuzz / afl-server.py View on Github external
server1.receive_data(data)
    process_all(server1)
    server1.receive_data(b"")
    process_all(server1)
except h11.RemoteProtocolError:
    pass

# byte at a time
server2 = h11.Connection(h11.SERVER)
try:
    for i in range(len(data)):
        server2.receive_data(data[i:i + 1])
        process_all(server2)
    server2.receive_data(b"")
    process_all(server2)
except h11.RemoteProtocolError:
    pass

# Suggested by the afl-python docs -- this substantially speeds up fuzzing, at
# the risk of missing bugs that would cause the interpreter to crash on
# exit. h11 is pure python, so I'm pretty sure h11 doesn't have any bugs that
# would cause the interpreter to crash on exit.
os._exit(0)
github pgjones / quart / quart / serving.py View on Github external
def _handle_events(self) -> None:
        if self.connection.they_are_waiting_for_100_continue:
            self._send(
                h11.InformationalResponse(status_code=100, headers=self.response_headers),
            )
        while True:
            try:
                event = self.connection.next_event()
            except h11.RemoteProtocolError:
                self._handle_error()
                self.close()
                break
            else:
                if isinstance(event, h11.Request):
                    headers = CIMultiDict()
                    for name, value in event.headers:
                        headers.add(name.decode().title(), value.decode())
                    self.handle_request(
                        0, event.method.decode().upper(), event.target.decode(), headers,
                    )
                elif isinstance(event, h11.EndOfMessage):
                    self.streams[0].complete()
                elif isinstance(event, h11.Data):
                    self.streams[0].append(event.data)
                elif event is h11.NEED_DATA or event is h11.PAUSED:
github dismantl / CaseHarvester / src / mjcs / session.py View on Github external
async def request(self, *args, **kwargs):
        try:
            response = await self.session.request(
                *args, 
                **kwargs,
                timeout=config.QUERY_TIMEOUT,
                retries=1
            )
        except (asks.errors.BadHttpResponse, h11.RemoteProtocolError, 
                    OSError, asks.errors.RequestTimeout) as e:
            await trio.sleep(30)
            logger.warning(f'{type(e).__name__}: {e}')
            # Replace current asks session object
            self.session = asks.Session(connections=1, persist_cookies=True)
            # Try once more
            response = await self.session.request(
                *args,
                **kwargs,
                timeout=config.QUERY_TIMEOUT,
                retries=1
            )
        if (response.history and response.history[0].status_code == 302 \
                    and response.history[0].headers['location'] == 'http://casesearch.courts.state.md.us/casesearch/inquiry-index.jsp') \
                or "Acceptance of the following agreement is" in response.text:
            logger.debug("Renewing session...")
github sorcio / trio-asgi / trio_web / h11server.py View on Github external
async def maybe_send_error_response(wrapper, exc):
    # If we can't send an error, oh well, nothing to be done
    wrapper.info("trying to send error response...")
    if wrapper.conn.our_state not in {h11.IDLE, h11.SEND_RESPONSE}:
        wrapper.info("...but I can't, because our state is",
                     wrapper.conn.our_state)
        return
    try:
        if isinstance(exc, h11.RemoteProtocolError):
            status_code = exc.error_status_hint
        else:
            status_code = 500
        body = str(exc).encode("utf-8")
        await send_simple_response(wrapper,
                                   status_code,
                                   "text/plain; charset=utf-8",
                                   body)
    except Exception as exc:
        wrapper.info("error while sending error response:", exc)
github pgjones / quart / quart / serving / h11.py View on Github external
def _handle_events(self) -> None:
        while True:
            if self.connection.they_are_waiting_for_100_continue:
                self._send(
                    h11.InformationalResponse(status_code=100, headers=self.response_headers()),
                )
            try:
                event = self.connection.next_event()
            except h11.RemoteProtocolError:
                self._handle_error()
                self.close()
                break
            else:
                if isinstance(event, h11.Request):
                    headers = CIMultiDict()
                    if event.http_version < b'1.1':
                        headers.setdefault('host', self.app.config['SERVER_NAME'] or '')
                    for name, value in event.headers:
                        headers.add(name.decode().title(), value.decode())
                    if 'Upgrade' in headers:
                        self._handle_upgrade_request(headers, event)
                    self.handle_request(
                        0, event.method.decode().upper(), event.target.decode(), headers,
                    )
                elif isinstance(event, h11.EndOfMessage):
github encode / uvicorn / uvicorn / protocols / http / h11_impl.py View on Github external
def handle_events(self):
        while True:
            try:
                event = self.conn.next_event()
            except h11.RemoteProtocolError as exc:
                msg = "Invalid HTTP request received."
                self.logger.warning(msg)
                self.transport.close()
                return
            event_type = type(event)

            if event_type is h11.NEED_DATA:
                break

            elif event_type is h11.PAUSED:
                # This case can occur in HTTP pipelining, so we need to
                # stop reading any more data, and ensure that at the end
                # of the active request/response cycle we handle any
                # events that have been buffered up.
                self.flow.pause_reading()
                break
github encode / httpx / httpx / dispatch / http11.py View on Github external
async def _receive_event(self, timeout: Timeout) -> H11Event:
        """
        Read a single `h11` event, reading more data from the network if needed.
        """
        while True:
            try:
                event = self.h11_state.next_event()
            except h11.RemoteProtocolError as e:
                logger.debug(
                    "h11.RemoteProtocolError exception "
                    + f"their_state={self.h11_state.their_state} "
                    + f"error_status_hint={e.error_status_hint}"
                )
                if self.socket.is_connection_dropped():
                    raise ConnectionClosed(e)
                raise ProtocolError(e)

            if isinstance(event, h11.Data):
                logger.trace(f"receive_event event=Data(<{len(event.data)} bytes>)")
            else:
                logger.trace(f"receive_event event={event!r}")

            if event is h11.NEED_DATA:
                try:
github poljar / matrix-nio / nio / client / http_client.py View on Github external
def receive(self, data):
        # type: (bytes) -> None
        """Pass received data to the client"""
        assert self.connection

        try:
            response = self.connection.receive(data)
        except (h11.RemoteProtocolError, h2.exceptions.ProtocolError) as e:
            raise RemoteTransportError(e)

        if response:
            try:
                request_info = self.requests_made.pop(response.uuid)
            except KeyError:
                logger.error("{}".format(pprint.pformat(self.requests_made)))
                raise

            if response.is_ok:
                logger.info(
                    "Received response of type: {}".format(
                        request_info.request_class
                    )
                )
            else:
github pgjones / hypercorn / hypercorn / trio / h11.py View on Github external
async def read_body(self) -> None:
        while True:
            try:
                event = self.connection.next_event()
            except h11.RemoteProtocolError:
                await self.send_error()
                await self.asgi_put({"type": "http.disconnect"})
                raise MustCloseError()
            else:
                if event is h11.NEED_DATA:
                    await self.read_data()
                elif isinstance(event, h11.EndOfMessage):
                    await self.asgi_put({"type": "http.request", "body": b"", "more_body": False})
                    return
                elif isinstance(event, h11.Data):
                    await self.asgi_put(
                        {"type": "http.request", "body": event.data, "more_body": True}
                    )
                elif isinstance(event, h11.ConnectionClosed) or event is h11.PAUSED:
                    break