K i ddlmZddlZddlZddlZddlZddlZddlZddlZddl m Z m Z m Z m Z ddlmZddlmZmZmZmZddlmZddlmZdd lmZdd lmZdd lmZmZm Z dd l!m"Z"m#Z#m$Z$dd l%m&Z&m'Z'm(Z(ddl)m*Z*ddlm+Z+m,Z,m-Z-m.Z.ddl/m0Z0ddl1m2Z2m3Z3gdZ4Gdde2Z5GddZ6GddZ7 d ddZ8ddZ9 d d!dZ:y)") annotationsN) Awaitable GeneratorIterableSequence) TracebackType)AnyCallableMappingcast) InvalidHeader)ServerExtensionFactory) enable_server_permessage_deflate) CloseCode)build_www_authenticate_basicparse_authorization_basicvalidate_subprotocols)SERVERRequestResponse) CONNECTINGOPENEvent)ServerProtocol) LoggerLikeOrigin StatusLike Subprotocol)asyncio_timeout) Connection broadcast)r#serve unix_serveServerConnectionServer basic_authceZdZdZdddddd d fdZddZd d ef dd Zdfd Zdfd Z xZ S)r&aT :mod:`asyncio` implementation of a WebSocket server connection. :class:`ServerConnection` provides :meth:`recv` and :meth:`send` methods for receiving and sending messages. It supports asynchronous iteration to receive messages:: async for message in websocket: await 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``, ``max_queue``, and ``write_limit`` arguments have the same meaning as in :func:`serve`. Args: protocol: Sans-I/O connection. server: Server that manages this connection.   ping_interval ping_timeout close_timeout max_queue write_limitc|t|||||||||_|jj |_|||y)Nr.)super__init__serverloop create_future request_rcvd) selfprotocolr7r/r0r1r2r3 __class__s _/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/websockets/asyncio/server.pyr6zServerConnection.__init__CsS   '%'#   26))2I2I2K   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. )r<reject)r;statustexts r>respondzServerConnection.respond]s&}}##FD11r?NcKtj|j|jgtjd{|j |j t4d{d}|. |||j }t|tr |d{}||j"j%r+|jj'|j |_nS|jjtjj*d|_nt|t,sJ||_|r||j(j.d<d}|9 |||j |j(}t|tr |d{}|t|t,sJ||_|jj1|j(dddd{|jj|jjy777z#t$rP}||j_ |jjtjj d}Yd}~d}~wwxYw7#t$rP}||j_ |jjtjj d}Yd}~8d}~wwxYw7#1d{7swYxYww)z1 Perform the opening handshake. ) return_whenN)expected_statezLFailed to open a WebSocket connection. See server log for more information. zServer is shutting down. r')asynciowaitr:connection_lost_waiterFIRST_COMPLETEDrequest send_contextr isinstancer Exceptionr< handshake_excrAhttp HTTPStatusINTERNAL_SERVER_ERRORr7 is_servingacceptresponseSERVICE_UNAVAILABLErheaders send_response)r;process_requestprocess_response server_headerrVexcs r> handshakezServerConnection.handshakersm,ll    ; ; <//   << #(( (C6 ;6 ;". #24#F%h :-5~H#{{--/(, (<((6$69 3#'==#7#7 OOAA!I$Q6 ;6 ;6 ;6 ;s?K.H+K.-H.K.1K7(HH H$B9K3I:I8I:AK K.!K"2K.K.H I5%AI0*K0I55K8I:: KAKKKKK.K+K! K+&K.c|j5t|tsJ||_|jj dyt ||y)z. Process one incoming event. N)rLrNrr: set_resultr5 process_event)r;eventr=s r>razServerConnection.process_eventsI << eW- -- DL    ( ( . G !% (r?cZt|||jj|yN)r5connection_mader7start_connection_handler)r; transportr=s r>rez ServerConnection.connection_mades"  * ,,T2r?)r<rr7r'r/ float | Noner0rhr1rhr2*int | None | tuple[int | None, int | None]r3int | tuple[int, int | None]returnNone)rBrrCstrrkr)rZZCallable[[ServerConnection, Request], Awaitable[Response | None] | Response | None] | Noner[dCallable[[ServerConnection, Request, Response], Awaitable[Response | None] | Response | None] | Noner\ str | Nonerkrl)rbrrkrl)rgzasyncio.BaseTransportrkrl) __name__ __module__ __qualname____doc__r6rDrr^rare __classcell__)r=s@r>r&r&)s<')%'&(@B49/ // $ / # /$/>/2/ /42:  $*!]. ]. ]. "!]." #].~ )33r?r&ceZdZdZddeddd ddZeddZddZddZ dd Z ddd Z dd Z dd Z dd ZddZddZddZeddZddZ ddZy) r'ah WebSocket server returned by :func:`serve`. This class mirrors the API of :class:`asyncio.Server`. It keeps track of WebSocket connections in order to close them properly when shutting down. Args: handler: Connection handler. It receives the WebSocket connection, which is a :class:`ServerConnection`, in argument. 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_request`` may be a function or a coroutine. 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. ``process_response`` may be a function or a coroutine. 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. logger: Logger for this server. It defaults to ``logging.getLogger("websockets.server")``. See the :doc:`logging guide <../../topics/logging>` for details. Nr+rZr[r\ open_timeoutloggerctj|_||_||_||_||_||_|tjd}||_ i|_ d|_ |jj|_y)Nzwebsockets.server)rHget_running_loopr8handlerrZr[r\rxlogging getLoggerryhandlers close_taskr9 closed_waiter)r;r|rZr[r\rxrys r>r6zServer.__init__s,,,.  . 0*( >&&':;F EG 6:48993J3J3Lr?cf|jDchc]}|jtus|c}Scc}w)a Set of active connections. This property contains all connections that completed the opening handshake successfully and didn't start the closing handshake yet. It can be useful in combination with :func:`~broadcast`. )rstaterr; connections r> connectionszServer.connections/s*.2]]Wzj>N>NRV>V WWWs..c||_|jD]}|jtjk(rd|j z}n{|jtj k(rd|j ddz}nG|jtjk(r|j }nt|j }|jjd|y)a Attach to a given :class:`asyncio.Server`. Since :meth:`~asyncio.loop.create_server` doesn't support injecting a custom ``Server`` class, the easiest solution that doesn't rely on private :mod:`asyncio` APIs is to: - instantiate a :class:`Server` - give the protocol factory a reference to that instance - call :meth:`~asyncio.loop.create_server` with the factory - attach the resulting :class:`asyncio.Server` with this method z%s:%dz[%s]:%dNr zserver listening on %s) r7socketsfamilysocketAF_INET getsocknameAF_INET6AF_UNIXrmryinfo)r;r7socknames r>wrapz Server.wrap;s NN =D{{fnn,!1!1!33/ 4#3#3#5bq#99.'')4++-. KK  5t < =r?cK t|j4d{ |j|j|j|j d{dddd{|jjt ur)|jj |j|=y |j#|j%|d{|j'd{|j|=y77#t j$r|jjt$rX|jjdd|jjYdddd{7|j|=ywxYw7/#1d{7swY@xYw77#t$rI|jjdd|j't(j*d{7YwxYw#t,$rY!t$r|jjYFwxYw#|j|=wxYww)a Handle the lifecycle of a WebSocket connection. Since this method doesn't have a caller that can handle exceptions, it attempts to log relevant ones. It guarantees that the TCP connection is closed before exiting. Nzopening handshake failedT)exc_infozconnection handler failed)r!rxr^rZr[r\rHCancelledErrorrgabortrOryerrorrr<rrstart_keepaliver|closerINTERNAL_ERROR TimeoutErrorrs r> conn_handlerzServer.conn_handlerWs* *&t'8'89   $..,,--**  ""((4$$**,. j)+ )**,ll:... !&&((( j)S  --((..0 %%++,FQU+V((..0   R j)?    ,/ )  A!!''(Cd'S &&y'?'?@@@ A    )  & & ( ) j)s(IHDHF4DDD H'F(:H#I2$F3F/F3H.F1/H3IHDA-F2F3 H>F?HIFFHF,F" F,'H/F31H3AH;G><HHHH H:H="H:6H=9H::H==I  Icr|jj|j||j|<y)z: Register a connection with this server. N)r8 create_taskrrrs r>rfzServer.start_connection_handlers,%)II$9$9$:K:KJ:W$X j!r?c|j4|jj|j||_yy)av Close the server. * Close the underlying :class:`asyncio.Server`. * When ``close_connections`` is :obj:`True`, which is the default, close existing connections. Specifically: * Reject opening WebSocket connections with an HTTP 503 (service unavailable) error. This happens when the server accepted the TCP connection but didn't complete the opening handshake before closing. * Close open WebSocket connections with close code 1001 (going away). * Wait until all connection handlers terminate. :meth:`close` is idempotent. N)rget_loopr_close)r;close_connectionss r>rz Server.closes8$ ?? ""mmo99 -.DO #r?cK|jjd|jjt j dd{|rv|j Dcgc]B}|jjtur$t j|jdD}}|rt j|d{|jjd{|j r5t j|j jd{|jjd|jjdy7cc}w777Gw)z Implementation of :meth:`close`. This calls :meth:`~asyncio.Server.close` on the underlying :class:`asyncio.Server` object to stop accepting new connections and then closes open connections with close code 1001. zserver closingrNiz server closed)ryrr7rrHsleeprr<rrrrI wait_closedvaluesrr`)r;rr close_taskss r>rz Server._closes+ )*  mmA  #'--&&,,J>##J$4$4T$:;K ll;///kk%%''' ==,,t}}3356 6 6 %%d+ )3  0 ( 7sVAE5E'E5%AE*,E5E/ !E5*E1+AE5+E3,rzServer.wait_closeds &nnT//000s #-+-c6|jjS)z7 See :meth:`asyncio.Server.get_loop`. )r7rrs r>rzServer.get_loops {{##%%r?c6|jjS)z9 See :meth:`asyncio.Server.is_serving`. )r7rTrs r>rTzServer.is_servings {{%%''r?cTK|jjd{y7w)a See :meth:`asyncio.Server.start_serving`. Typical use:: server = await serve(..., start_serving=False) # perform additional setup here... # ... then start the server await server.start_serving() N)r7 start_servingrs r>rzServer.start_servingskk''))) (&(cTK|jjd{y7w)a See :meth:`asyncio.Server.serve_forever`. Typical use:: server = await serve(...) # this coroutine doesn't return # canceling it stops the server await server.serve_forever() This is an alternative to using :func:`serve` as an asynchronous context manager. Shutdown is triggered by canceling :meth:`serve_forever` instead of exiting a :func:`serve` context. N)r7 serve_foreverrs r>rzServer.serve_forever s kk'')))rc.|jjS)z6 See :attr:`asyncio.Server.sockets`. )r7rrs r>rzServer.socketss {{"""r?cK|Swrdrs r> __aenter__zServer.__aenter__&s  sc`K|j|jd{y7wrd)rrr;exc_type exc_value tracebacks r> __aexit__zServer.__aexit__)s#    s $.,.)r|-Callable[[ServerConnection], Awaitable[None]]rZrnr[ror\rprxrhryLoggerLike | Nonerkrl)rkzset[ServerConnection])r7zasyncio.Serverrkrl)rr&rkrl)T)rboolrkrl)rkrl)rkzasyncio.AbstractEventLoop)rkr)rkzIterable[socket.socket]rkr'rztype[BaseException] | NonerzBaseException | NonerzTracebackType | Nonerkrl)rqrrrsrtrr6propertyrrrrfrrrrrTrrrrrrr?r>r'r'sV  $*%'$()'M>'M   'M 'M$"%'M&#''M(")'M* +'MR X X=84*l Y.**X1*&( **$##!,!(!( !  !r?r'ceZdZdZ ddddddddedddddddddd  dd Zdd Z dd Zdd ZddZ eZ y)r$u 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`` coroutine. 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 coroutine returns a :class:`Server` whose API mirrors :class:`asyncio.Server`. Treat it as an asynchronous context manager to ensure that the server will be closed:: from websockets.asyncio.server import serve def handler(websocket): ... # set this future to exit the server stop = asyncio.get_running_loop().create_future() async with serve(handler, host, port): await stop Alternatively, call :meth:`~Server.serve_forever` to serve requests and cancel it to stop the server:: server = await serve(handler, host, port) await 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 :meth:`~asyncio.loop.create_server` for details. port: TCP port the server listens on. See :meth:`~asyncio.loop.create_server` for details. 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 or :obj:`None` to continue normally. When you force an HTTP 101 Continue response, the handshake is successful. Else, the connection is aborted. ``process_request`` may be a function or a coroutine. process_response: Intercept the response during the opening handshake. Return an HTTP response to force the response or :obj:`None` to continue normally. When you force an HTTP 101 Continue response, the handshake is successful. Else, the connection is aborted. ``process_response`` may be a function or a coroutine. 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. write_limit: High-water mark of write buffer in bytes. It is passed to :meth:`~asyncio.WriteTransport.set_write_buffer_limits`. It defaults to 32 KiB. You may pass a ``(high, low)`` tuple to set the high-water and low-water marks. 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 the event loop's :meth:`~asyncio.loop.create_server` method. For example: * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enable TLS. * You can set ``sock`` to provide a preexisting TCP socket. You may call :func:`socket.create_server` (not to be confused with the event loop's :meth:`~asyncio.loop.create_server` method) to create a suitable server socket and customize it. * You can set ``start_serving`` to ``False`` to start accepting connections only after you call :meth:`~Server.start_serving()` or :meth:`~Server.serve_forever()`. Ndeflater+r*ir,r-)origins extensions subprotocolsselect_subprotocol compressionrZr[r\rxr/r0r1max_sizer2r3rycreate_connectionc "  t|dk(r tn|td|tt || | | | _|j d:|jd| tjdddk\r|jdd  f d }tj}|jd d r|j|fi|_y|j|||fi|_y) Nrzunsupported compression: rwsslssl_handshake_timeoutr ) ssl_shutdown_timeoutc  d} d fd }t |}| j S)zZ Create an asyncio protocol for managing a WebSocket connection. Nc>J|jusJ|Srd)r<)r<rrrs r>protocol_select_subprotocolzDserve.__init__..factory..protocol_select_subprotocols2 .999#z':'::::-j,GGr?)rrrrrryr.)r<rrzSequence[Subprotocol]rkzSubprotocol | None)rr7)rr<rr1rrryr2rrr/r0rr;rr3s @r>factoryzserve.__init__..factorys ("-H,H"7H(H&%)#>! H+ +)+#'J r?unixF)rkr&)rr ValueErrorr&r'r7get setdefaultsys version_inforHr{popcreate_unix_server create_server)r;r|hostportrrrrrrZr[r\rxr/r0r1rr2r3ryrkwargsrr8s` ```` ```````` r>r6zserve.__init__sd  # !, / ) #9*EJ  $8 FG G  $ 0  +-'%    ::e  (   5| D#w.!!"8-H, , , \'') ::fe $!8!8!8!KF!KD "4!3!3GT4!R6!RD r?c"K|d{S7wrdrrs r>rzserve.__aenter__,szzs  cK|jj|jjd{y7wrd)r7rrrs r>rzserve.__aexit__/s. kk%%'''s8AAAc>|jjSrd)__await_impl__ __await__rs r>rzserve.__await__:s""$..00r?cK|jd{}|jj||jS7+wrd)rr7r)r;r7s r>rzserve.__await_impl__>s5)))  {{*sA>,A)NN),r|rrrpr int | Nonerz0Sequence[Origin | re.Pattern[str] | None] | Nonerz'Sequence[ServerExtensionFactory] | NonerzSequence[Subprotocol] | NonerzNCallable[[ServerConnection, Sequence[Subprotocol]], Subprotocol | None] | NonerrprZrnr[ror\rprxrhr/rhr0rhr1rhrrr2rir3rjryrrztype[ServerConnection] | Nonerr rkrlrr)rkzGenerator[Any, None, Server]) rqrrrsrtrr6rrrr__iter__rr?r>r$r$4ssp  ~SEI>B59 "+  $*%'&(%'&($@B49$(;?]~S>~S~S ~SB~S<~S3~S ~S" #~S( )~S6 7~SB"C~SF#G~SH$I~SJ#K~SL$M~SPQ~SR>S~ST2U~SX"Y~S\9]~S`a~Sb c~SD(,(((( (  (1Hr?r$c  t|fd|d|S)a Create a WebSocket server listening on a Unix socket. This function is identical to :func:`serve`, except the ``host`` and ``port`` arguments are replaced by ``path``. 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)rpath)r$)r|rrs r>r%r%Hs&  9t$ 9& 99r?c| |\}}t|txrt|tS#ttf$rYywxYwNF)rNrm TypeErrorr) credentialsusernamepasswords r>is_credentialsr^sFG(((C(FZ#-FF z "s );;c|duduk(r td|t|rttttf|g}nkt |t rMttt tttf|}td|Dstd|td|t|dfd J dfd }|S) a~ Factory for ``process_request`` to enforce HTTP Basic Authentication. :func:`basic_auth` is designed to integrate with :func:`serve` as follows:: from websockets.asyncio.server import basic_auth, serve async 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 or coroutine 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|ywrd)r).0items r> zbasic_auth..sI~d+Iszinvalid credentials argument: cZ |}tj||S#t$rYywxYwr)KeyErrorhmaccompare_digest)rrexpected_passwordcredentials_dicts r>check_credentialsz%basic_auth..check_credentialss= $4X$>!&&'8(C C  s  **c|K |jd} t|\}}||}t|tr |d{}|sD|jtjj d}t |jd<|S||_ y#t$rG|jtjj d}t |jd<|cYSwxYw#t$rG|jtjj d}t |jd<|cYSwxYw7w)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 NzInvalid credentials ) rXrrDrQrR UNAUTHORIZEDrrrrNrr) rrL authorizationrVrrvalid_credentialsrrealms r>rZz#basic_auth..process_requestsB #OOOr(r(gsP t!2d!:;JKK + & $U38_k BC   X .#D%S/)BK$PQ I8HII"@ NOO<[MJK K 01 D  (( (,$,, ,\ r?rd)r|rrrprr rkzAwaitable[Server])rr rkr)NN)rrmrz2tuple[str, str] | Iterable[tuple[str, str]] | Nonerz3Callable[[str, str], Awaitable[bool] | bool] | NonerkzACallable[[ServerConnection, Request], Awaitable[Response | None]]); __future__rrHrrQr}rerrcollections.abcrrrrtypesrtypingr r r r exceptionsrextensions.baserextensions.permessage_deflaterframesrrXrrrhttp11rrrr<rrrr7rrrrr compatibilityr!rr"r#__all__r&r'r$r%rr(rr?r>rs"  DD//&4L /...#@@*- x3zx3vL!L!` QQl: :: :: :,GFJMQn nCnKnG nr?