K i,kNddlmZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddlmZmZddlmZddlmZmZmZmZddlmZddlmZdd lmZdd lmZdd l m!Z!m"Z"m#Z#dd l$m%Z%m&Z&m'Z'dd l(m)Z)m*Z*m+Z+ddl,m-Z-ddlm.Z.m/Z/m0Z0m1Z1ddl2m3Z3ddl4m5Z5gdZ6Gdde3Z7GddZ8d#dZ9 d$ddddddddde%ddddddddd d%dZ: d& d'd Z;d(d!Z< d) d*d"Z=y)+) annotationsN)IterableSequence) TracebackType)AnyCallableMappingcast) InvalidHeader)ServerExtensionFactory) enable_server_permessage_deflate) CloseCode)build_www_authenticate_basicparse_authorization_basicvalidate_subprotocols)SERVERRequestResponse) CONNECTINGOPENEvent)ServerProtocol) LoggerLikeOrigin StatusLike Subprotocol) Connection)Deadline)serve unix_serveServerConnectionServer basic_authceZdZdZddddd d fdZd dZddedf dd Zdfd Zdfd Z xZ S)r#a/ :mod:`threading` implementation of a WebSocket server connection. :class:`ServerConnection` provides :meth:`recv` and :meth:`send` methods for receiving and sending messages. It supports iteration to receive messages:: for message in websocket: process(message) The iterator exits normally when the connection is closed with close code 1000 (OK) or 1001 (going away) or without a close code. It raises a :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is closed with any other code. The ``ping_interval``, ``ping_timeout``, ``close_timeout``, and ``max_queue`` arguments have the same meaning as in :func:`serve`. Args: socket: Socket connected to a WebSocket client. protocol: Sans-I/O connection.   ping_interval ping_timeout close_timeout max_queuecr|tj|_t||||||||||y)Nr*) threadingr request_rcvdsuper__init__)selfsocketprotocolr+r,r-r. __class__s \/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/websockets/sync/server.pyr3zServerConnection.__init__@sF %OO-   '%'     c:|jj||S)a Create a plain text HTTP response. ``process_request`` and ``process_response`` may call this method to return an HTTP response instead of performing the WebSocket opening handshake. You can modify the response before returning it, for example by changing HTTP headers. Args: status: HTTP status code. text: HTTP response body; it will be encoded to UTF-8. Returns: HTTP response to send to the client. )r6reject)r4statustexts r8respondzServerConnection.respondXs&}}##FD11r9Nc|jj|s td|j|j t 5d}| |||j}|+|jj|j|_n||_|r||jjd<d}|( |||j|j}|||_|jj!|jddd|jj|jjy#t $rP}||j_|jjtjjd}Yd}~)d}~wwxYw#t $rP}||j_|jjtjjd}Yd}~d}~wwxYw#1swYxYw)z1 Perform the opening handshake. z-timed out while waiting for handshake requestN)expected_statezLFailed to open a WebSocket connection. See server log for more information. r$)r1wait TimeoutErrorrequest send_contextr Exceptionr6 handshake_excr;http HTTPStatusINTERNAL_SERVER_ERRORacceptresponseheaders send_response)r4process_requestprocess_response server_headertimeoutrKexcs r8 handshakezServerConnection.handshakems.  %%g.NO O << #""*"=* ;". #24#F#$(MM$8$8$FDM$,DM 6CDMM))(3#/ #3D$,, #V +(0  ++DMM:U* ;h == & & 2---- - 3]%69 3#'==#7#7 OOAA!I$.%69 3#'==#7#7 OOAA!I$;* ;* ;sc G/D7"AG/6F.G/7 FAF G/ FG/ G,AG'!G/'G,,G//G8c|j4t|tsJ||_|jj yt ||y)z. Process one incoming event. N)rC isinstancerr1setr2 process_event)r4eventr7s r8rWzServerConnection.process_eventsG << eW- -- DL    ! ! # G !% (r9c t||jjy#|jjwxYw)zI Read incoming data from the socket and process events. N)r2 recv_eventsr1rV)r4r7s r8rZzServerConnection.recv_eventss:  $ G  !    ! ! #D   ! ! #s ,A)r5 socket.socketr6rr+ float | Noner,r\r-r\r.*int | None | tuple[int | None, int | None]returnNone)r<rr=strr^r) rN=Callable[[ServerConnection, Request], Response | None] | NonerOGCallable[[ServerConnection, Request, Response], Response | None] | NonerP str | NonerQr\r^r_)rXrr^r_r^r_) __name__ __module__ __qualname____doc__r3r>rrSrWrZ __classcell__)r7s@r8r#r#&s<')%'&(@B//!/ $ / # /$/>/ /02:  $* $#P. P. P. "!P."#P.$ %P.d ) $ $r9r#cbeZdZdZ d d dZd dZd dZd dZd dZ ddZ y)r$a WebSocket server returned by :func:`serve`. This class mirrors the API of :class:`~socketserver.BaseServer`, notably the :meth:`~socketserver.BaseServer.serve_forever` and :meth:`~socketserver.BaseServer.shutdown` methods, as well as the context manager protocol. Args: socket: Server socket listening for new connections. handler: Handler for one connection. Receives the socket and address returned by :meth:`~socket.socket.accept`. logger: Logger for this server. It defaults to ``logging.getLogger("websockets.server")``. See the :doc:`logging guide <../../topics/logging>` for details. Nc||_||_|tjd}||_t j dk7r"tj\|_ |_ yy)Nzwebsockets.serverwin32) r5handlerlogging getLoggerloggersysplatformospipeshutdown_watchershutdown_notifier)r4r5rmrps r8r3zServer.__init__sV   >&&':;F <<7 "<>GGI 9D !4#9 #r9ctj} |j|jtjt jdk7r*|j|jtj |j |jj\}}tj|j||f}|jb#t $rYywxYw#t$rYywxYw)a See :meth:`socketserver.BaseServer.serve_forever`. This method doesn't return. Calling :meth:`shutdown` from another thread stops the server. Typical use:: with serve(...) as server: server.serve_forever() Nrl)targetargs) selectorsDefaultSelectorregisterr5 EVENT_READ ValueErrorrqrrruselectrJOSErrorr0Threadrmstart)r4pollersockaddrthreads r8 serve_foreverzServer.serve_forevers**,  OODKK)=)= > <<7 " OOD1193G3G H MMO "[[//1 d %%T\\t MF LLN      s#*C C/ C,+C,/ C;:C;c|jjtjdk7r!t j |j dyy)z@ See :meth:`socketserver.BaseServer.shutdown`. rlxN)r5closerqrrrswritervr4s r8shutdownzServer.shutdown s9  <<7 " HHT++T 2 #r9c6|jjS)z> See :meth:`socketserver.BaseServer.fileno`. )r5filenors r8rz Server.fileno)s {{!!##r9c|SNrs r8 __enter__zServer.__enter__0s r9c$|jyr)r)r4exc_type exc_value tracebacks r8__exit__zServer.__exit__3s r9r)r5r[rmz$Callable[[socket.socket, Any], None]rpLoggerLike | Noner^r_rd)r^int)r^r$)rztype[BaseException] | NonerzBaseException | NonerzTracebackType | Noner^r_) rerfrgrhr3rrrrrrr9r8r$r$s|,%) F F6 F" F  F$L3$,((   r9r$cv|dk(r tjdttSt dt d|)NWebSocketServerz%WebSocketServer was renamed to Serverzmodule z has no attribute )warningswarnDeprecationWarningr$AttributeErrorre)names r8 __getattr__r<s=    3   78,.@I JJr9deflater(r'ir))rsslorigins extensions subprotocolsselect_subprotocol compressionrNrOrP open_timeoutr+r,r-max_sizer.rpcreate_connectionc  /d|vr+|jdtjdt t | dk(r t n| t d| t|jdd|jdd}|_rD| t d |jd tjtj|fi|}n&tj||ffi|}n | t d j|d d }d   fd }t||S)a Create a WebSocket server listening on ``host`` and ``port``. Whenever a client connects, the server creates a :class:`ServerConnection`, performs the opening handshake, and delegates to the ``handler``. The handler receives the :class:`ServerConnection` instance, which you can use to send and receive messages. Once the handler completes, either normally or with an exception, the server performs the closing handshake and closes the connection. This function returns a :class:`Server` whose API mirrors :class:`~socketserver.BaseServer`. Treat it as a context manager to ensure that it will be closed and call :meth:`~Server.serve_forever` to serve requests:: from websockets.sync.server import serve def handler(websocket): ... with serve(handler, ...) as server: server.serve_forever() Args: handler: Connection handler. It receives the WebSocket connection, which is a :class:`ServerConnection`, in argument. host: Network interfaces the server binds to. See :func:`~socket.create_server` for details. port: TCP port the server listens on. See :func:`~socket.create_server` for details. sock: Preexisting TCP socket. ``sock`` replaces ``host`` and ``port``. You may call :func:`socket.create_server` to create a suitable TCP socket. ssl: Configuration for enabling TLS on the connection. origins: Acceptable values of the ``Origin`` header, for defending against Cross-Site WebSocket Hijacking attacks. Values can be :class:`str` to test for an exact match or regular expressions compiled by :func:`re.compile` to test against a pattern. Include :obj:`None` in the list if the lack of an origin is acceptable. extensions: List of supported extensions, in order in which they should be negotiated and run. subprotocols: List of supported subprotocols, in order of decreasing preference. select_subprotocol: Callback for selecting a subprotocol among those supported by the client and the server. It receives a :class:`ServerConnection` (not a :class:`~websockets.server.ServerProtocol`!) instance and a list of subprotocols offered by the client. Other than the first argument, it has the same behavior as the :meth:`ServerProtocol.select_subprotocol ` method. compression: The "permessage-deflate" extension is enabled by default. Set ``compression`` to :obj:`None` to disable it. See the :doc:`compression guide <../../topics/compression>` for details. process_request: Intercept the request during the opening handshake. Return an HTTP response to force the response. Return :obj:`None` to continue normally. When you force an HTTP 101 Continue response, the handshake is successful. Else, the connection is aborted. process_response: Intercept the response during the opening handshake. Modify the response or return a new HTTP response to force the response. Return :obj:`None` to continue normally. When you force an HTTP 101 Continue response, the handshake is successful. Else, the connection is aborted. server_header: Value of the ``Server`` response header. It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to :obj:`None` removes the header. open_timeout: Timeout for opening connections in seconds. :obj:`None` disables the timeout. ping_interval: Interval between keepalive pings in seconds. :obj:`None` disables keepalive. ping_timeout: Timeout for keepalive pings in seconds. :obj:`None` disables timeouts. close_timeout: Timeout for closing connections in seconds. :obj:`None` disables the timeout. max_size: Maximum size of incoming messages in bytes. :obj:`None` disables the limit. max_queue: High-water mark of the buffer where frames are received. It defaults to 16 frames. The low-water mark defaults to ``max_queue // 4``. You may pass a ``(high, low)`` tuple to set the high-water and low-water marks. If you want to disable flow control entirely, you may set it to ``None``, although that's a bad idea. logger: Logger for this server. It defaults to ``logging.getLogger("websockets.server")``. See the :doc:`logging guide <../../topics/logging>` for details. create_connection: Factory for the :class:`ServerConnection` managing the connection. Set it to a wrapper or a subclass to customize connection handling. Any other keyword arguments are passed to :func:`~socket.create_server`. N ssl_contextzssl_context was renamed to sslrzunsupported compression: unixFpathzmissing path argumentfamilyz(path and sock arguments are incompatibleT) server_sidedo_handshake_on_connectct } s/|jtjtjd\|j |j t|tjsJ|j|j dd} dfd }t| }J||  j|j j*j,t.usJ j1 jy#t$r|jYywxYw#t$r-j!j"j%Yyt$rJj&j)ddj!j"j%YywxYw#t$r?j&j)ddjt2j4YywxYw#t$r|jYywxYw) NTc>J|jusJ|Sr)r6)r6r connectionrs r8protocol_select_subprotocolz@serve..conn_handler..protocol_select_subprotocol(s2 .999#z':'::::-j,GGr9)rrrrrrpr*zopening handshake failed)exc_infozconnection handler failed)r6rrzSequence[Subprotocol]r^zSubprotocol | None)r setsockoptr5 IPPROTO_TCP TCP_NODELAY settimeoutrQrU ssl_module SSLSocket do_handshakerrErrSrB close_socketrecv_events_threadjoinrperrorr6staterstart_keepaliverINTERNAL_ERROR)rrdeadlinerr6rr-rrrmrpr.rrrr+r,rNrOrrPrrrs @r8 conn_handlerzserve..conn_handler sTL);  2 2F4F4FM 0 0 23!$ (<(<===!!#% ("-H,H"7H(H&%)#>! H%0 00*+)+# J  $$#$!$$&  &&,,4 44 #**, #   "=  JJL    '')--224 !!''(BT'R'')--224   ;!!''(Cd'S  !9!9: ;   JJL stCD>"E6H2G'-H2>EE3G$H2AG$!H2#G$$H2'AH/,H2.H//H22I I)rr[rrr^r_)poprrrrrr~r# setdefaultr5AF_UNIX create_server wrap_socketr$)rmhostportrrrrrrrrNrOrPrr+r,r-rr.rprkwargsrrrs` ````` ``````````` @r8r!r!FsQf {}.jj' ,  l+i5jA  4[MBCC , FE*Dzz&$/D | | !899   h 7''77D''t ??D  GH H  $)  aaaJ $ f --r9c  t|fd|d|S)a Create a WebSocket server listening on a Unix socket. This function accepts the same keyword arguments as :func:`serve`. It's only available on Unix. It's useful for deploying a server behind a reverse proxy such as nginx. Args: handler: Connection handler. It receives the WebSocket connection, which is a :class:`ServerConnection`, in argument. path: File system path to the Unix socket. T)rr)r!)rmrrs r8r"r"qs(  9t$ 9& 99r9c| |\}}t|txrt|tS#ttf$rYywxYwNF)rUr` TypeErrorr~) credentialsusernamepasswords r8is_credentialsrsFG(((C(FZ#-FF z "s );;c|duduk(r td|t|rttttf|g}nkt |t rMttt tttf|}td|Dstd|td|t|dfd J dfd }|S) ah Factory for ``process_request`` to enforce HTTP Basic Authentication. :func:`basic_auth` is designed to integrate with :func:`serve` as follows:: from websockets.sync.server import basic_auth, serve with serve( ..., process_request=basic_auth( realm="my dev server", credentials=("hello", "iloveyou"), ), ): If authentication succeeds, the connection's ``username`` attribute is set. If it fails, the server responds with an HTTP 401 Unauthorized status. One of ``credentials`` or ``check_credentials`` must be provided; not both. Args: realm: Scope of protection. It should contain only ASCII characters because the encoding of non-ASCII characters is undefined. Refer to section 2.2 of :rfc:`7235` for details. credentials: Hard coded authorized credentials. It can be a ``(username, password)`` pair or a list of such pairs. check_credentials: Function that verifies credentials. It receives ``username`` and ``password`` arguments and returns whether they're valid. Raises: TypeError: If ``credentials`` or ``check_credentials`` is wrong. ValueError: If ``credentials`` and ``check_credentials`` are both provided or both not provided. Nz/provide either credentials or check_credentialsc32K|]}t|ywr)r).0items r8 zbasic_auth..sI~d+Iszinvalid credentials argument: cZ |}tj||S#t$rYywxYwr)KeyErrorhmaccompare_digest)rrexpected_passwordcredentials_dicts r8check_credentialsz%basic_auth..check_credentialss= $4X$>!&&'8(C C  s  **c8 |jd} t|\}}||sD|jtjj d}t |jd<|S||_ y#t$rG|jtjj d}t |jd<|cYSwxYw#t$rG|jtjj d}t |jd<|cYSwxYw)z Perform HTTP Basic Authentication. If it succeeds, set the connection's ``username`` attribute and return :obj:`None`. If it fails, return an HTTP 401 Unauthorized responss. AuthorizationzMissing credentials zWWW-AuthenticatezUnsupported credentials zInvalid credentials N) rLrr>rGrH UNAUTHORIZEDrrr r)rrC authorizationrKrrrrealms r8rNz#basic_auth..process_requests #OOO __future__rrrGrnrsrerzr5rrrqr0rcollections.abcrrtypesrtypingrrr r exceptionsr extensions.baser extensions.permessage_deflaterframesrrLrrrhttp11rrrr6rrrserverrrrrrrrutilsr __all__r#r$rr!r"rr%rr9r8rsb"    .//&4L /...#@@" Np$zp$f``FKh. "&(,@D:>15 '  &!#"$!#"$ <> $7;_h. /h. h. h.  h. &h.>h.8h./h. h.&'h., -h.: ;h.FGh.JKh.L Mh.NOh.P Qh.TUh.V:Wh.Z [h.^5_h.`ah.b ch.Z : /: :: :.GFJ;?j jCj9j< jr9