Ejemplo n.º 1
0
async def client_sock(sock: WebSocket):
    await sock.accept()
    client_id = generate_id()
    async with client_sock_lock:
        clients[client_id] = sock
    
    try:
        while True:
            try:
                data = await sock.receive_json()
                event = data["event"]

                if event == "CLOSE":
                    await sock.send_json({"event": "CLOSE"})
                    sock.close()
                    break
                elif event == "CONNECT":
                    await sock.send_json({"event": "CONNECT"})
                elif event == "UPD_SLIDER":
                    print(f"NEW VAL FOR SLIDER <{data['name']}>: {data['value']}")
                elif event == "SONG":
                    async with now_playing_sock_lock:
                        for i in socks.values():
                            await i.send_json(data["song"])

            except json.JSONDecodeError:
                await sock.send_json({"event": "F**k you"})
                continue
    except starlette.websockets.WebSocketDisconnect:
        print("Socket Disconnected")
    finally:
        async with client_sock_lock:
            clients.pop(client_id)
Ejemplo n.º 2
0
async def websocket_test(websocket: WebSocket): # $ requestHandler routedParameter=websocket
    await websocket.accept()

    ensure_tainted(
        websocket, # $ tainted

        websocket.url, # $ tainted

        websocket.url.netloc, # $ tainted
        websocket.url.path, # $ tainted
        websocket.url.query, # $ tainted
        websocket.url.fragment, # $ tainted
        websocket.url.username, # $ tainted
        websocket.url.password, # $ tainted
        websocket.url.hostname, # $ tainted
        websocket.url.port, # $ tainted

        websocket.url.components, # $ tainted
        websocket.url.components.netloc, # $ tainted
        websocket.url.components.path, # $ tainted
        websocket.url.components.query, # $ tainted
        websocket.url.components.fragment, # $ tainted
        websocket.url.components.username, # $ tainted
        websocket.url.components.password, # $ tainted
        websocket.url.components.hostname, # $ tainted
        websocket.url.components.port, # $ tainted

        websocket.headers, # $ tainted
        websocket.headers["key"], # $ tainted

        websocket.query_params, # $ tainted
        websocket.query_params["key"], # $ tainted

        websocket.cookies, # $ tainted
        websocket.cookies["key"], # $ tainted

        await websocket.receive(), # $ tainted
        await websocket.receive_bytes(), # $ tainted
        await websocket.receive_text(), # $ tainted
        await websocket.receive_json(), # $ tainted
    )

    # scheme seems very unlikely to give interesting results, but very likely to give FPs.
    ensure_not_tainted(
        websocket.url.scheme,
        websocket.url.components.scheme,
    )

    async for data in  websocket.iter_bytes():
        ensure_tainted(data) # $ tainted

    async for data in  websocket.iter_text():
        ensure_tainted(data) # $ tainted

    async for data in  websocket.iter_json():
        ensure_tainted(data) # $ tainted
Ejemplo n.º 3
0
    async def __call__(self, ws: WebSocket) -> WebSocket:
        authorization: str = ws.headers.get("Authorization")
        scheme, credentials = get_authorization_scheme_param(authorization)
        if not (authorization and scheme and credentials):
            if self.auto_error:
                raise HTTPException(
                    status_code=status.HTTP_403_FORBIDDEN, detail="Not authenticated"
                )
            else:
                return None
        if scheme.lower() != "bearer":
            if self.auto_error:
                raise HTTPException(
                    status_code=status.HTTP_403_FORBIDDEN,
                    detail="Invalid authentication credentials",
                )
            else:
                return None
        try:
            data = base64.b64decode(credentials).decode("ascii")
        except (ValueError, UnicodeDecodeError, binascii.Error):
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN, detail="Not authenticated"
            )
        username, separator, password = data.partition(":")
        if not separator:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN, detail="Not authenticated"
            )

        ws.scope["user"] = UserModel(username=username, password=password)
        return ws
Ejemplo n.º 4
0
    async def __call__(self,
                       websocket: WebSocket) -> WebSocket:  # type: ignore
        authorization: str = websocket.headers.get("Authorization")
        scheme, param = get_authorization_scheme_param(authorization)
        if self.realm:
            unauthorized_headers = {
                "WWW-Authenticate": f'Basic realm="{self.realm}"'
            }
        else:
            unauthorized_headers = {"WWW-Authenticate": "Basic"}
        invalid_user_credentials_exc = HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid authentication credentials",
            headers=unauthorized_headers,
        )
        if not authorization or scheme.lower() != "basic":
            if self.auto_error:
                raise HTTPException(
                    status_code=status.HTTP_401_UNAUTHORIZED,
                    detail="Not authenticated",
                    headers=unauthorized_headers,
                )
            else:
                return None
        try:
            data = base64.b64decode(param).decode("ascii")
        except (ValueError, UnicodeDecodeError, binascii.Error):
            raise invalid_user_credentials_exc
        username, separator, password = data.partition(":")
        if not separator:
            raise invalid_user_credentials_exc

        websocket.scope["user"] = UserModel(username=username,
                                            password=password)
        return websocket
Ejemplo n.º 5
0
async def visa_status_notification_sender(websocket: WebSocket):
    """ The websocket connection from notifier.Notifier will be send a JSON string
        handled by this function. The JSON string contains new visa status update
        which will be dispatched into the broadcast channel.
    """
    async for new_visa_status in websocket.iter_json():
        await BROADCASTER.publish(**new_visa_status)
Ejemplo n.º 6
0
async def websocket_chatting_send(websocket: WebSocket, client_id: str):
    websocket.session['client_id'] = client_id
    await manager.connect(websocket)
    try:
        while True:
            data = await websocket.receive_json()
            if data.get('keepalive'):
                await manager.send_personal_message({'type': 'keepalive'},
                                                    websocket)
            if data.get('message') or data.get('whisper'):
                await manager.broadcast({
                    "type": data.get('type'),
                    "sender": data.get('sender'),
                    "message": data.get('message'),
                    "receiver": data.get('receiver'),
                    "detail": data.get('detail')
                })

            await asyncio.sleep(0.01)

    except WebSocketDisconnect:
        await manager.disconnect(websocket)
        await manager.broadcast({
            'type': 'alert',
            'detail': 'enter',
            'sender': client_id,
            'message': "leave the chatting room."
        })
Ejemplo n.º 7
0
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    try:
        async for action in websocket.iter_json():
            await websocket.send_json(await process_action(websocket, action))
    except WebSocketDisconnect:
        pass
Ejemplo n.º 8
0
        async def dispatch(self) -> None:
            """Awaits on concurrent tasks :meth:`handle_receive()` & :meth:`handle_send()`"""
            websocket = WebSocket(self.scope, receive=self.receive, send=self.send)
            await self.on_connect(websocket)
            close_code = status.WS_1000_NORMAL_CLOSURE

            await asyncio.gather(
                self.handle_receive(websocket=websocket, close_code=close_code),
            )
Ejemplo n.º 9
0
async def websocket_endpoint(websocket: WebSocket):
    websocket.accept()

    try:
        while True:
            data = await websocket.receive_text()

            if data == "97":
                ser.write("a".encode())
                print("a")
            elif data == "98":
                ser.write("b".encode())
                print("b")
            else:
                print("[another commend]", data)

    except WebSocketDisconnect as e:
        print("disconnect", e)
Ejemplo n.º 10
0
Archivo: app.py Proyecto: trtin/jina
        async def dispatch(self) -> None:
            websocket = WebSocket(self.scope,
                                  receive=self.receive,
                                  send=self.send)
            await self.on_connect(websocket)
            close_code = status.WS_1000_NORMAL_CLOSURE

            await asyncio.gather(
                self.handle_receive(websocket=websocket,
                                    close_code=close_code), )
Ejemplo n.º 11
0
async def message_updates(ws: WebSocket, username: str):
    await ws.accept()
    challenge = pyotp.random_base32()
    await ws.send_json({"type": "CHALLENGE", "payload": challenge})
    # TODO CHECK THIS SHIT
    # resp = await ws.receive_text()
    # print(f"RESP: {resp}")
    async with lock:
        sessions[username] = ws
        print(sessions.keys())
    # valid = verify_signature(username, challenge, resp)
    valid = True
    if not valid:
        ws.send_text("thats not cool bro")
        ws.close()
        return

    while True:
        data = await ws.receive_text()
Ejemplo n.º 12
0
 def connect(
     self,
     websocket: WebSocket,
     filter_id: Optional[UUID] = None,
     loop: asyncio.AbstractEventLoop = asyncio.get_event_loop(),
 ) -> UUID:
     connection_id = super().connect(websocket, filter_id=filter_id, loop=loop)
     if filter_id is not None and filter_id in self._last_events:
         loop.create_task(websocket.send_json(self._last_events[filter_id]))
     return connection_id
Ejemplo n.º 13
0
async def start(websocket: WebSocket, username: str):
    print(f"{get_current_time()} connected")

    if not username:
        await send(websocket, -1, "unauthenticated")
    else:
        await websocket.accept()

        websocket.username = username
        users[username] = websocket

    await handle_receive(websocket)
Ejemplo n.º 14
0
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    id = uuid.uuid4()
    open_sockets[id] = websocket
    fake_png = create_fake_file()
    await websocket.send_bytes(fake_png.getvalue())
    fake_png.close()

    with get_hardware() as (vid, relay):
        read_task = asyncio.create_task(websocket.receive_text())

        while True:
            try:
                write_task = asyncio.create_task(
                    send_video_frame(vid, websocket))

                done, pending = await asyncio.wait(
                    [read_task, write_task],
                    return_when=asyncio.FIRST_COMPLETED)

                if read_task in done:
                    # if the read task is finished, process the result and start a new read and wait for the current write
                    # otherwise, the write is done and just loop again on the same read
                    result = read_task.result()
                    resource, action = tuple(result.split('|'))
                    if resource == 'light':
                        if action == 'on':
                            relay.on()
                        else:
                            relay.off()
                    read_task = asyncio.create_task(websocket.receive_text())
                    if pending:
                        await asyncio.wait(pending)

            except Exception as e:
                print(e)
                break

    print('Websocket disconnected')
    del open_sockets[id]
Ejemplo n.º 15
0
async def ws_stream_iracing_data(
    websocket: WebSocket, ws_connection_manager=Depends(get_ws_manager)):
    """
    Stream current iRacing data over a websocket connection. 
    TODO Get framerate from user config.
    """
    await ws_connection_manager.connect(websocket)

    try:
        while True:
            websocket.receive_text()

            data = get_iracing_data(raw=True)

            if data:
                await ws_connection_manager.send_json(data, websocket)

            await asyncio.sleep(0.03)
    except (WebSocketDisconnect, ConnectionClosedError, ConnectionClosedOK,
            RuntimeError):
        await ws_connection_manager.disconnect(websocket)
        return
Ejemplo n.º 16
0
async def ping_task(
        ws: WebSocket):  # ping task to find crit disconected clients
    while True:
        try:
            await asyncio.wait_for(
                ws.send_text(
                    Answer(None, ACTION_LIST["ping"]).get_ret_object()),
                timeout=5,
            )
            await asyncio.sleep(30)

        except BaseException:
            try:
                await ws.close()
            except BaseException:
                pass
            return
Ejemplo n.º 17
0
async def websocket_chatting_receive(websocket: WebSocket, client_id: str):
    before_len = 10000000
    websocket.session['client_id'] = client_id
    await manager.connect(websocket)
    try:
        await manager.send_connections(websocket)
        await manager.broadcast({
            'type': 'alert',
            'detail': 'enter',
            'sender': client_id,
            'message': "enter the chatting room."
        })

        while True:
            if await redis_connection.sismember("users",
                                                client_id.encode()) is False:
                break
            msg_list = await redis_connection.lrange("chat", 0, -1)
            send_msg_list = msg_list[:len(msg_list) - before_len]
            if before_len != len(msg_list) and send_msg_list:
                for data in send_msg_list:
                    data = json.loads(data.decode())
                    if data.get('type') == 'whisper':
                        if data.get('receiver') == client_id:
                            await manager.send_personal_message(
                                data, websocket)

                    elif data.get('type') == 'message' or data.get(
                            'type') == 'alert':
                        await manager.send_personal_message(data, websocket)

            await asyncio.sleep(0.01)
            before_len = len(msg_list)
    except WebSocketDisconnect:
        await manager.disconnect(websocket)
        await manager.broadcast({
            'type': 'alert',
            'detail': 'enter',
            'sender': client_id,
            'receiver': 'all',
            'message': "leave the chatting room."
        })
Ejemplo n.º 18
0
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    try:
        if app.camera is None:
            app.camera = cv.VideoCapture(0)
            if app.camera.isOpened():
                # create tracker with chosen algorithm
                app.tracker = Tracker(app.camera)
                await websocket.send_text("LookingFor")
        while app.camera.isOpened():
            # read frame and run step of algorithm
            start = time.time()
            _, frame = app.camera.read()
            gesture = app.tracker.algorithm.run(frame)
            # if the glove is lost
            if gesture is None:
                app.tracker.update_init_loc(app.camera)
            color = app.tracker.color.convert_gesture(gesture)
            # send color | "LookingFor"
            await websocket.send_text(color)
            # confirmation that client recived data, if there is no answer program stopped
            data = await asyncio.wait_for(websocket.receive_text(), timeout=5)
            if data == "FindMyGlove":
                app.tracker.update_init_loc(app.camera)
            elif data != "Received":
                app.tracker.change_algorithm(data, app.camera)
            if app.debug:
                app.tracker.algorithm.draw(frame)
                cv.waitKey(50)
    except Exception:
        print("Connection closed")
    finally:
        # close the websocket and the camera
        await websocket.close()
        if app.camera is None:
            app.camera.release()
            app.camera = None
        if app.debug:
            cv.destroyAllWindows()
Ejemplo n.º 19
0
async def chat(websocket: WebSocket,
               user: User = Depends(deps.user_from_websocket)):
    if user is None:
        await websocket.close()
        return
    chat_manager: Optional[ChatManager] = websocket.get("chat_manager")
    if chat_manager is None:
        raise RuntimeError("Chat manager is unavailable")
    manager_endpoint = ChatManagerEndpoint(chat_manager)
    websocket.state.user = user
    await manager_endpoint.on_connect(websocket)
    try:
        while True:
            message: Message = await websocket.receive()
            if message["type"] == "websocket.receive":
                data = await manager_endpoint.decode(websocket, message)
                await manager_endpoint.on_receive(websocket, data)
            elif message["type"] == "websocket.disconnect":
                break
    except Exception as exc:
        raise exc from None
    finally:
        await manager_endpoint.on_disconnect(websocket)
Ejemplo n.º 20
0
 async def receiver(self, websocket: WebSocket, channel: str) -> None:
     async for message in websocket.iter_text():
         if message == "__ping__":
             await websocket.send_text("__pong__")
Ejemplo n.º 21
0
async def lobby_ws_receiver(websocket: WebSocket):
    async for message in websocket.iter_text():
        await broadcast.publish(channel="lobby", message=message)
Ejemplo n.º 22
0
async def chatroom_ws_receiver(websocket: WebSocket, game_id: int):
    async for message in websocket.iter_text():
        await broadcast.publish(channel=f"game-{game_id}", message=message)
Ejemplo n.º 23
0
async def channel_ws_receiver(websocket: WebSocket, channel: str):
    async for message in websocket.iter_text():
        await broadcast.publish(channel=channel,
                                message=await handle_message(channel, message))
Ejemplo n.º 24
0
 def _uuid_converter(ws: fastapi.WebSocket, id: str):
     return ws.url_for(handler, id=id)
Ejemplo n.º 25
0
 async def receive_message(websocket: WebSocket):
     nonlocal json_data
     async for message in websocket.iter_json():
         print('received a new message from client')
         json_data = message
Ejemplo n.º 26
0
async def events_ws_receiver(websocket: WebSocket, game_uuid: UUID):
    async for message in websocket.iter_text():
        await broadcast.publish(channel=f"game-{game_uuid}", message=message)
Ejemplo n.º 27
0
async def websocket_endpoint(websocket: WebSocket):
    websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(f"Message was {data}")