How to use the websockets.InvalidHandshake function in websockets

To help you get started, we’ve selected a few websockets 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 Fitblip / wsstat / test / test_coros.py View on Github external
def bad_websocket_handshake(*args, **kwargs):
        raise InvalidHandshake("Bad status code: 200")
github huge-success / sanic / sanic / websocket.py View on Github external
async def websocket_handshake(self, request, subprotocols=None):
        # let the websockets package do the handshake with the client
        headers = {}

        try:
            key = handshake.check_request(request.headers)
            handshake.build_response(headers, key)
        except InvalidHandshake:
            raise InvalidUsage("Invalid websocket request")

        subprotocol = None
        if subprotocols and "Sec-Websocket-Protocol" in request.headers:
            # select a subprotocol
            client_subprotocols = [
                p.strip()
                for p in request.headers["Sec-Websocket-Protocol"].split(",")
            ]
            for p in client_subprotocols:
                if p in subprotocols:
                    subprotocol = p
                    headers["Sec-Websocket-Protocol"] = subprotocol
                    break

        # write the 101 response back to the client
github pyrates / roll / roll / protocols.py View on Github external
def websocket_handshake(self, request, subprotocols: set=None):
        """Websocket handshake, handled by `websockets`
        """
        headers = []

        def get_header(k):
            return request.headers.get(k.upper(), '')

        def set_header(k, v):
            headers.append((k, v))

        try:
            key = handshake.check_request(get_header)
            handshake.build_response(set_header, key)
        except InvalidHandshake:
            raise RuntimeError('Invalid websocket request')

        subprotocol = None
        ws_protocol = get_header('Sec-Websocket-Protocol')
        if subprotocols and ws_protocol:
            # select a subprotocol
            client_subprotocols = tuple(
                (p.strip() for p in ws_protocol.split(',')))
            for p in client_subprotocols:
                if p in subprotocols:
                    subprotocol = p
                    set_header('Sec-Websocket-Protocol', subprotocol)
                    break

        # write the 101 response back to the client
        rv = b'HTTP/1.1 101 Switching Protocols\r\n'
github encode / uvicorn / uvicorn / protocols / websockets / websockets.py View on Github external
def websocket_upgrade(http):
    request_headers = dict([
        (key.decode('latin-1'), value.decode('latin-1'))
        for key, value in http.headers
    ])
    response_headers = {}

    try:
        key = websockets.handshake.check_request(request_headers)
        websockets.handshake.build_response(response_headers, key)
    except websockets.InvalidHandshake:
        rv = b"HTTP/1.1 403 Forbidden\r\n\r\n"
        http.transport.write(rv)
        http.transport.close()
        return

    # Retrieve any subprotocols to be negotiated with the consumer later
    subprotocols = [
        subprotocol.strip() for subprotocol in
        request_headers.get("sec-websocket-protocol", "").split(",")
    ]
    http.scope.update({"type": "websocket", "subprotocols": subprotocols})
    asgi_instance = http.app(http.scope)
    request = WebSocketRequest(http, response_headers)
    http.loop.create_task(asgi_instance(request.receive, request.send))
    request.put_message({"type": "websocket.connect", "order": 0})
github dwpy / alita / alita / serve / server.py View on Github external
async def websocket_handshake(self, request, subprotocols=None):
        headers = {}

        try:
            key = handshake.check_request(request.headers)
            handshake.build_response(headers, key)
        except InvalidHandshake:
            msg = "Invalid websocket request received."
            if self.debug:
                msg += "\n" + traceback.format_exc()
            self.logger.error(msg)
            self.on_response(msg)
            raise RuntimeError(msg)

        subprotocol = None
        if subprotocols and "Sec-Websocket-Protocol" in request.headers:
            # select a subprotocol
            client_subprotocols = [
                p.strip()
                for p in request.headers["Sec-Websocket-Protocol"].split(",")
            ]
            for p in client_subprotocols:
                if p in subprotocols:
github monospacedmagic / discord-hero / hero / utils.py View on Github external
if pause is not None:
                    await maybe_coroutine(pause)
                return await coro(*args, **kwargs)
            except asyncio.CancelledError:
                if restart_check is not None and (await maybe_coroutine(restart_check)):
                    await wrapped(*args, **kwargs)
                else:
                    raise
                # catch connection issues
            except (OSError,
                    HTTPException,
                    GatewayNotFound,
                    ConnectionClosed,
                    aiohttp.ClientError,
                    asyncio.TimeoutError,
                    websockets.InvalidHandshake,
                    websockets.WebSocketProtocolError) as e:
                if any((isinstance(e, ConnectionClosed) and e.code == 1000,  # clean disconnect
                        not isinstance(e, ConnectionClosed))):
                    await wrapped(*args, **kwargs)
                else:
                    raise
github bibanon / itabashi / itabashi / discord.py View on Github external
yield from asyncio.sleep(retry.delay())
                else:
                    break

            # connect to Discord and reconnect when necessary
            while self.client.is_logged_in:
                if self.client.is_closed:
                    self.client._closed.clear()
                    self.client.http.recreate()

                try:
                    yield from self.client.connect()

                except (discord.HTTPException, aiohttp.ClientError,
                        discord.GatewayNotFound, discord.ConnectionClosed,
                        websockets.InvalidHandshake,
                        websockets.WebSocketProtocolError) as e:
                    if isinstance(e, discord.ConnectionClosed) and e.code == 4004:
                        raise # Do not reconnect on authentication failure
                    logging.exception("discord.py disconnected, waiting and reconnecting")
                    yield from asyncio.sleep(retry.delay())
github Rapptz / discord.py / discord / client.py View on Github external
is thrown then there is a Discord API outage.
        :exc:`.ConnectionClosed`
            The websocket connection has been terminated.
        """

        backoff = ExponentialBackoff()
        while not self.is_closed():
            try:
                await self._connect()
            except (OSError,
                    HTTPException,
                    GatewayNotFound,
                    ConnectionClosed,
                    aiohttp.ClientError,
                    asyncio.TimeoutError,
                    websockets.InvalidHandshake,
                    websockets.WebSocketProtocolError) as exc:

                self.dispatch('disconnect')
                if not reconnect:
                    await self.close()
                    if isinstance(exc, ConnectionClosed) and exc.code == 1000:
                        # clean close, don't re-raise this
                        return
                    raise

                if self.is_closed():
                    return

                # We should only get this when an unhandled close code happens,
                # such as a clean disconnect (1000) or a bad state (bad token, no sharding, etc)
                # sometimes, discord sends us 1000 for unknown reasons so we should reconnect
github Deivedux / Quote / discord / client.py View on Github external
is thrown then there is a discord API outage.
        ConnectionClosed
            The websocket connection has been terminated.
        """

        backoff = ExponentialBackoff()
        while not self.is_closed():
            try:
                await self._connect()
            except (OSError,
                    HTTPException,
                    GatewayNotFound,
                    ConnectionClosed,
                    aiohttp.ClientError,
                    asyncio.TimeoutError,
                    websockets.InvalidHandshake,
                    websockets.WebSocketProtocolError) as exc:

                if not reconnect:
                    await self.close()
                    if isinstance(exc, ConnectionClosed) and exc.code == 1000:
                        # clean close, don't re-raise this
                        return
                    raise

                if self.is_closed():
                    return

                # We should only get this when an unhandled close code happens,
                # such as a clean disconnect (1000) or a bad state (bad token, no sharding, etc)
                # sometimes, discord sends us 1000 for unknown reasons so we should reconnect
                # regardless and rely on is_closed instead
github OnGridSystems / CATEd / tradeBOT / tasks.py View on Github external
price = update[2]
                                side = 'bid' if update[1] == 1 else 'ask'
                                size = update[3]
                                # this mean remove
                                market = self.order_books.get_market_by_id(data[0])
                                if size == '0.00000000':
                                    # print('\033[96mthis mean remove\033[0m')
                                    if market is not None:
                                        market.remove_item(side=side, price=str(price))
                                # this mean add or change
                                else:
                                    # print('\033[96mthis mean add or change\033[0m')
                                    if market is not None:
                                        market.add_or_change(side=side, price=price, size=size)
                        self._last_seq_dic[ticker_id] = seq
        except websockets.InvalidHandshake:
            WampTickerPoloniex.apply_async(queue='high', countdown=10)
            return True
        except gaierror:
            WampTickerPoloniex.apply_async(queue='high', countdown=10)
            return True