K i=T ddlmZddlZddlZddlZddlZddlZddlZddl m Z m Z ddl m Z mZmZddlmZmZddlmZmZmZmZmZmZmZddlmZmZdd lmZm Z m!Z!m"Z"m#Z#dd l$m%Z%m&Z&dd l'm(Z(dd l)m*Z*m+Z+m,Z,m-Z-m.Z.dd l m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5ddl6m7Z7dgZ8Gdde-Z9Gdde9Z:e(e;ddddddy)) annotationsN) GeneratorSequence)AnyCallablecast)HeadersMultipleValuesError)InvalidHandshake InvalidHeaderInvalidHeaderValueInvalidMessage InvalidOriginInvalidUpgradeNegotiationError) ExtensionServerExtensionFactory)build_extensionparse_connectionparse_extensionparse_subprotocol parse_upgrade)RequestResponse) lazy_import) CONNECTINGOPENSERVERProtocolState)ConnectionOptionExtensionHeader LoggerLikeOrigin StatusLike SubprotocolUpgradeProtocol) accept_keyServerProtocolceZdZdZddddeddd dfdZddZ ddZddZ dd Z dd Z dd Z dd Z dd Z dfd ZxZS)r*a- Sans-I/O implementation of a WebSocket server connection. Args: origins: Acceptable values of the ``Origin`` header. 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. This is useful for defending against Cross-Site WebSocket Hijacking attacks. extensions: List of supported extensions, in order in which they should be tried. 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 has the same signature as the :meth:`select_subprotocol` method, including a :class:`ServerProtocol` instance as first argument. state: Initial state of the WebSocket connection. max_size: Maximum size of incoming messages in bytes; :obj:`None` disables the limit. logger: Logger for this connection; defaults to ``logging.getLogger("websockets.server")``; see the :doc:`logging guide <../../topics/logging>` for details. Ni)origins extensions subprotocolsselect_subprotocolstatemax_sizeloggerct|t|||||_||_||_|(t |d|j||jyy)N)sider0r1r2r/) super__init__rr,available_extensionsavailable_subprotocolssetattr__get__ __class__) selfr,r-r.r/r0r1r2r;s W/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/websockets/server.pyr6zServerProtocol.__init__Lsk"    $.!&2#  ) $"**4@  *c |j|\}}}t+} t,j.j1d| d<d | d <d | d<|| d<||| d<||| d<t3dd| S#t$ro}||_||_|jr|j j dd|j tjjd|dcYd}~Sd}~wt$r}||_||_|jr|j j dd|j tjjd|d}d |jd <|cYd}~Sd}~wt$r}||_||_|jr|j j d dtt|}|}|j !|j }|d |z }|j !|j tjj"d|dcYd}~Sd}~wt$$r_}||_||_|j j'd d|j tjj(dcYd}~Sd}~wwxYw)a Create a handshake response to accept the connection. If the handshake request is valid and the handshake successful, :meth:`accept` returns an HTTP response with status code 101. Else, it returns an HTTP response with another status code. This rejects the connection, like :meth:`reject` would. You must send the handshake response with :meth:`send_response`. You may modify the response before sending it, typically by adding HTTP headers. Args: request: WebSocket handshake request received from the client. Returns: WebSocket handshake response or HTTP response to send to the client. z! invalid originT)exc_infoz'Failed to open a WebSocket connection: z. Nz! invalid upgradez^. You cannot access a WebSocket server directly with a browser. You need a WebSocket client. websocketUpgradez! invalid handshakez; zopening handshake failedzLFailed to open a WebSocket connection. See server log for more information. usegmtDate ConnectionzSec-WebSocket-AcceptSec-WebSocket-ExtensionsSec-WebSocket-ProtocolezSwitching Protocols)process_requestr _exception handshake_excdebugr2rejecthttp HTTPStatus FORBIDDENrUPGRADE_REQUIREDheadersr r BaseException __cause__ BAD_REQUEST ExceptionerrorINTERNAL_SERVER_ERRORr emailutils formatdater) r<request accept_headerextensions_headerprotocol_headerexcresponse exc_chainexc_strrSs r=acceptzServerProtocol.acceptos,9  $$W-  !n)++000=(  ) *7&'  (2CG. /  &0?G, -2G<<} !$G !$D zz !!"4t!D;;))9#cB  !$G !$D zz !!"5!E{{00=cUCEFH+6H  Y 'O !$G !$D zz !!"7$!G]C0I" G%%1%// R {++%%1;;++9'#F  "%G !$D  KK  84  H;;55=  s]A.. J 7A$C!J ! J -A5E("J ( J 4A6H+-HJ  J *AJ>J J c^|j}t|jdDcgc] }t|c}g}t d|Ds#t d|rdj |dt|jdDcgc] }t|c}g}t|dk(r|djdk(s#t d|rdj |d |d } tj|jd }t|d k7r t%d |t'|} |d} | dk7r t%d| |j)||_|j-|\} |_|j1|x} |_| | | fScc}wcc}w#t$r td dt$rtd d dwxYw#t j"$r}t%d ||d}~wwxYw#t$r tddt$rtdd dwxYw)a Check a handshake request and negotiate extensions and subprotocol. This function doesn't verify that the request is an HTTP/1.1 or higher GET request and doesn't check the ``Host`` header. These controls are usually performed earlier in the HTTP request handling code. They're the responsibility of the caller. Args: request: WebSocket handshake request received from the client. Returns: ``Sec-WebSocket-Accept``, ``Sec-WebSocket-Extensions``, and ``Sec-WebSocket-Protocol`` headers for the handshake response. Raises: InvalidHandshake: If the handshake request is invalid; then the server must return 400 Bad Request error. rFc3BK|]}|jdk(yw)upgradeN)lower).0values r= z1ServerProtocol.process_request..sF%5;;=I-Fs, NrBr rrAzSec-WebSocket-Keymultiple valuesT)validatezSec-WebSocket-Version13)rSsumget_allranyrjoinrlenriKeyErrorr r base64 b64decodeencodebinasciiErrorrr)process_originoriginprocess_extensionsr-process_subprotocol subprotocol) r<r]rSrk connectionrhkeyraw_keyrar^versionr_r`s r=rJzServerProtocol.process_requestsR0//-029//,2O P e $ PRT. F:FF zdii 3 GK *-/6y/I Je]5 ! JB*  G !gaj&6&6&8K&G 'DIIg,>T TtT T R-.C  H&&szz|dCG w<2 $%8#> >"3  V56G d?$%" R 35FGT Q R~~ H$%8#>C G H C 78d B" V 79JKQU U Vs;F! F&.F+4%G?H++GG>, G99G>+H,c@ |jd}|tt|}|j S|j D]9}||k(s0t |tjs#|&|j|8|St||S#t$rtdddwxYw)aG Handle the Origin HTTP request header. Args: headers: WebSocket handshake request headers. Returns: origin, if it is acceptable. Raises: InvalidHandshake: If the Origin header is invalid. InvalidOrigin: If the origin isn't acceptable. r%rnN) getr r rr%r, isinstancerePattern fullmatchr)r<rSr~origin_or_regexs r=r}zServerProtocol.process_origins" G[[*F  &&)F << ##'<< ,"f, ;*'11&9E  ,$F++ # G*;<$ F Gs BBcd}g}g}|jd}|r|jrt|Dcgc] }t|c}g}|D]a\}} |jD]M} | j|k7r | j | |\} } |j|| f|j| ac|r t|}||fScc}w#t $rYswxYw)a Handle the Sec-WebSocket-Extensions HTTP request header. Accept or reject each extension proposed in the client request. Negotiate parameters for accepted extensions. Per :rfc:`6455`, negotiation rules are defined by the specification of each extension. To provide this level of flexibility, for each extension proposed by the client, we check for a match with each extension available in the server configuration. If no match is found, the extension is ignored. If several variants of the same extension are proposed by the client, it may be accepted several times, which won't make sense in general. Extensions must implement their own requirements. For this purpose, the list of previously accepted extensions is provided. This process doesn't allow the server to reorder extensions. It can only select a subset of the extensions proposed by the client. Other requirements, for example related to mandatory extensions or the order of extensions, may be implemented by overriding this method. Args: headers: WebSocket handshake request headers. Returns: ``Sec-WebSocket-Extensions`` HTTP response header and list of accepted extensions. Raises: InvalidHandshake: If the Sec-WebSocket-Extensions header is invalid. NrG) rsr7rrrnameprocess_request_paramsrappendr) r<rSresponse_header_valueextension_headersaccepted_extensions header_values header_valueparsed_header_valuesrrequest_params ext_factoryresponse_params extensions r=rz!ServerProtocol.process_extensions6s N-135/1(BC T66:=CPQ<.QSU; )= $n#'#<#<K"''4/ !5@5W5W*,?62&,,dO-DE'..y9% 2 $34E$F !$&999?R,! !sC1C CCct|jdDcgc] }t|c}g}|j|Scc}w)a Handle the Sec-WebSocket-Protocol HTTP request header. Args: headers: WebSocket handshake request headers. Returns: Subprotocol, if one was selected; this is also the value of the ``Sec-WebSocket-Protocol`` response header. Raises: InvalidHandshake: If the Sec-WebSocket-Subprotocol header is invalid. rH)rrrsrr/)r<rSrr.s r=rz"ServerProtocol.process_subprotocolsR/2%,OO4L$M  ",/   / &&|44  sAc|jsy|s tdt|}|jD] }||vs|cStddj|jz)aq Pick a subprotocol among those offered by the client. If several subprotocols are supported by both the client and the server, pick the first one in the list declared the server. If the server doesn't support any subprotocols, continue without a subprotocol, regardless of what the client offers. If the server supports at least one subprotocol and the client doesn't offer any, abort the handshake with an HTTP 400 error. You provide a ``select_subprotocol`` argument to :class:`ServerProtocol` to override this logic. For example, you could accept the connection even if client doesn't offer a subprotocol, rather than reject it. Here's how to negotiate the ``chat`` subprotocol if the client supports it and continue without a subprotocol otherwise:: def select_subprotocol(protocol, subprotocols): if "chat" in subprotocols: return "chat" Args: subprotocols: List of subprotocols offered by the client. Returns: Selected subprotocol, if a common subprotocol was found. :obj:`None` to continue without a subprotocol. Raises: NegotiationError: Custom implementations may raise this exception to abort the handshake with an HTTP 400 error. Nzmissing subprotocolz%invalid subprotocol; expected one of rm)r8rsetru)r<r.proposed_subprotocolsrs r=r/z!ServerProtocol.select_subprotocols|R**"#89 9!$L 166 #K33"" #  3ii334 5  r>c tj|}|j}tdtj j dfddtt|fdg}t|j|j||S)a' Create a handshake response to reject the connection. A short plain text response is the best fallback when failing to establish a WebSocket connection. You must send the handshake response with :meth:`send_response`. You may modify the response before sending 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. rETrC)rFclosezContent-Length)z Content-Typeztext/plain; charset=utf-8) rOrPrzr rZr[r\strrvrrkphrase)r<statustextbodyrSs r=rNzServerProtocol.rejectsw*({{}//t/<='!3s4y>2=    fmmWdCCr>c6|jr|j|j}}|jjd|||jj D]"\}}|jjd||$|j r/|jjdt|j |jj|j|jdk(r;|jtusJt|_ |jjdy|jjd|j|j|j|j!|_t%|j"y)z Send a handshake response to the client. Args: response: WebSocket handshake response event to send. z> HTTP/1.1 %d %sz> %s: %sz> [body] (%d bytes)rIzconnection openzconnection rejected (%d %s)N)rM status_code reason_phraser2rS raw_itemsrrvwritesr serializer0rrinfosend_eofdiscardparsernext)r<rbcoderrrks r= send_responsezServerProtocol.send_responses6 ::#//1G1G&D KK  0$ ?&..88: : U !!*c59 :}} !!"7X]]9KL 8--/0   3 &::+ ++DJ KK  . / KK  -$$&&  MMO,,.DK  r>c#K|jtur tj|jj Ed{}|jre|jjdj |j"j%D]"\}}|jjd||$|j&j)t*| Ed{y7#t $rj}td|_||j_ |j|j|_ t|jdYd}~d}~wwxYw7}w)Nz$did not receive a valid HTTP requestz< GET %s HTTP/1.1z< %s: %s)r0rrparsereader read_linerWrrLrUrrrrrMr2pathrSreventsrr5)r<r]rarrkr;s r=rzServerProtocol.parses :: # %,]]KK))&zz !!"5w||D")//";";"=>JCKK%%j#u=> KK  w '7=?"") %3:&"03"", "lln T[[! " #sNE%,C-C+C-BE%%E#&E%+C-- E 6AEE%E  E%)r,z0Sequence[Origin | re.Pattern[str] | None] | Noner-z'Sequence[ServerExtensionFactory] | Noner.zSequence[Subprotocol] | Noner/zLCallable[[ServerProtocol, Sequence[Subprotocol]], Subprotocol | None] | Noner0r!r1z int | Noner2zLoggerLike | NonereturnNone)r]rrr)r]rrz"tuple[str, str | None, str | None])rSr rz Origin | None)rSr rz"tuple[str | None, list[Extension]])rSr rSubprotocol | None)r.zSequence[Subprotocol]rr)rr&rrrr)rbrrr)rzGenerator[None])__name__ __module__ __qualname____doc__rr6rerJr}rrr/rNrr __classcell__r;s@r=r*r*0s<EI>B59 !$$(!B!< ! 3 ! !!!"! !!FZ=xFCFC ,FCP!FO:O: ,O:b50: +:  : xDB D##r>c eZdZdfd ZxZS)ServerConnectioncXtjdtt||i|y)Nz.ServerConnection was renamed to ServerProtocol)warningswarnDeprecationWarningr5r6)r<argskwargsr;s r=r6zServerConnection.__init__9s) <   $)&)r>)rrrrrr)rrrr6rrs@r=rr8s **r>rz.legacy.server)WebSocketServerWebSocketServerProtocol broadcastserve unix_serve)deprecated_aliases)< __future__rrxr{ email.utilsrZrOrrcollections.abcrrtypingrrrdatastructuresr r exceptionsr r rrrrrr-rrrSrrrrrhttp11rrimportsrprotocolrrrr r!r"r#r$r%r&r'r(r[r)__all__r*rglobalsr>r=rs"  /&&8:& ??  E#XE#P*~*  I,#3%!&  r>