K i4ddlmZddlZddlZddlZddlmZmZddlm Z ddl m Z m Z ddl mZmZmZmZmZmZmZddlmZmZdd lmZmZmZmZmZmZmZm Z dd l!m"Z"m#Z#dd l$m%Z%dd l&m'Z'm(Z(m)Z)m*Z*m+Z+dd lm,Z,m-Z-m.Z.m/Z/m0Z0m1Z1ddl2m3Z3ddl4m5Z5m6Z6dgZ7Gdde*Z8Gdde8Z9e:ejvjyddZ=e:ejvjyddZ>e:ejvjyddZ?e:ejvjyddZ@e=e>e?e@f d dZAe%eBddddy)!) annotationsN) GeneratorSequence)Any)HeadersMultipleValuesError)InvalidHandshake InvalidHeaderInvalidHeaderValueInvalidMessage InvalidStatusInvalidUpgradeNegotiationError)ClientExtensionFactory Extension)build_authorization_basicbuild_extension build_hostbuild_subprotocolparse_connectionparse_extensionparse_subprotocol parse_upgrade)RequestResponse) lazy_import)CLIENT CONNECTINGOPENProtocolState)ConnectionOptionExtensionHeader LoggerLikeOrigin SubprotocolUpgradeProtocol) WebSocketURI) accept_key generate_keyClientProtocolceZdZdZdddeddd d fdZd dZddZddZdd Z dd Z dfd Z xZ S)r,a Sans-I/O implementation of a WebSocket client connection. Args: uri: URI of the WebSocket server, parsed with :func:`~websockets.uri.parse_uri`. origin: Value of the ``Origin`` header. This is useful when connecting to a server that validates the ``Origin`` header to defend 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. 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.client")``; see the :doc:`logging guide <../../topics/logging>` for details. Ni)origin extensions subprotocolsstatemax_sizeloggerct|t|||||_||_||_||_t|_y)N)sider1r2r3) super__init__rurir.available_extensionsavailable_subprotocolsr+key) selfr8r.r/r0r1r2r3 __class__s W/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/websockets/client.pyr7zClientProtocol.__init__GsL    $.!&2#>ct}t|jj|jj|jj |d<|jj rt|jj |d<|j|j|d<d|d<d|d<|j|d<d|d <|j@t|jDcgc]}|j|jf c}|d <|jt|j|d <t!|jj"|Scc}w) a1 Create a handshake request to open a connection. You must send the handshake request with :meth:`send_request`. You can modify it before sending it, for example to add HTTP headers. Returns: WebSocket handshake request event to send to the server. Host Authorizationr& websocketUpgrade ConnectionzSec-WebSocket-Key13zSec-WebSocket-VersionSec-WebSocket-ExtensionsSec-WebSocket-Protocol)rrr8hostportsecure user_inforr.r;r9rnameget_request_paramsr:rr resource_name)r<headersextension_factorys r>connectzClientProtocol.connect^s5)$TXX]]DHHMM488??S 88  '@$((BTBT'UGO $ ;; " $ GH (  ) '+xx#$+/'(  $ $ 02A.2-F-F)'++->-Q-Q-ST3G. /  & & 20A++1G, -txx--w77s$#Ec,|jdk7r t||j}t|j dDcgc] }t |c}g}t d|Ds#td|rdj|dt|j dDcgc] }t|c}g}t|dk(r|djd k(s#td|rdj|d |d }|t|j k7r t#d ||j%||_|j)||_ycc}wcc}w#t$r td dt$rtd d dwxYw) z Check a handshake response. Args: request: WebSocket handshake response received from the server. Raises: InvalidHandshake: If the handshake response is invalid. erEc3BK|]}|jdk(yw)upgradeN)lower).0values r> z2ClientProtocol.process_response..sF%5;;=I-Fs, NrDrrrCzSec-WebSocket-Acceptzmultiple values) status_coderrPsumget_allranyrjoinrlenrWKeyErrorr r r*r;r process_extensionsr/process_subprotocol subprotocol)r<responserPrY connectionrV s_w_accepts r>process_responsezClientProtocol.process_responses   3 &) )""-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 U !78J DHH- -$%;ZH H11':33G<3 Q K B 67T A" U 68IJPT T UsE&E#E((+Fcg}|jd}|r|j tdt|Dcgc] }t |c}g}|D][\}}|jD]7}|j |k7r |j ||} |j| Ktd|d||Scc}w#t$rY^wxYw)aj Handle the Sec-WebSocket-Extensions HTTP response header. Check that each extension is supported, as well as its parameters. :rfc:`6455` leaves the rules up to the specification of each extension. To provide this level of flexibility, for each extension accepted by the server, we check for a match with each extension available in the client configuration. If no match is found, an exception is raised. If several variants of the same extension are accepted by the server, it may be configured 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. Other requirements, for example related to mandatory extensions or the order of extensions, may be implemented by overriding this method. Args: headers: WebSocket handshake response headers. Returns: List of accepted extensions. Raises: InvalidHandshake: To abort the handshake. rGzno extensions supportedzUnsupported extension: name = z , params = )r^r9rr]rrMprocess_response_paramsappend) r<rPaccepted_extensionsr/ header_valueparsed_extensionsrMresponse_paramsrQ extensions r>rcz!ClientProtocol.process_extensionss >02__%?@ ((0&'@AA7:CMN<.NPR8 *; %o)-)B)B%(--5 !$5$M$M+-@% (..y9#,+""&{?2CE/ 8#"?O,! !sB28B77 CCcHd}|jd}|r|j tdt|Dcgc] }t |c}g}t |dkDrt dddj||d}||jvrtd||Scc}w) a# Handle the Sec-WebSocket-Protocol HTTP response header. If provided, check that it contains exactly one supported subprotocol. Args: headers: WebSocket handshake response headers. Returns: Subprotocol, if one was selected. NrHzno subprotocols supportedrzmultiple values: r[rzunsupported subprotocol: )r^r:rr]rrar r`)r<rPrer0rnparsed_subprotocolss r>rdz"ClientProtocol.process_subprotocols+/ '?@ **2&'BCC9 GET %s HTTP/1.1z> %s: %sN)debugr3pathrP raw_itemswritesrl serialize)r<requestr;rYs r> send_requestzClientProtocol.send_requestsw :: KK  17<< @%oo779 : U !!*c59 : 7,,./r?c#K|jturc tj|jj |jj |jjEd{}|j rj"|j$}}|j&j!d|||j(j+D]"\}}|j&j!d||$|j,r/|j&j!dt/|j, |j1|jtusJt:|_|j6j9|t<| Ed{y7##t$rj}td|_ ||j_ |j|j|_t|jdYd}~d}~wwxYw#t2$rr}|_|j6j9|||_ |j|j|_t|jdYd}~@d}~wwxYw7w)Nz%did not receive a valid HTTP responsez< HTTP/1.1 %d %sz< %s: %sz< [body] (%d bytes))r1rrparsereader read_line read_exact read_to_eof Exceptionr handshake_exc __cause__send_eofdiscardparsernextrur\ reason_phraser3rPrwbodyrarir _exceptioneventsrlr r6)r<rfexccodephraser;rYr=s r>r}zClientProtocol.parse*s :: # &.nnKK))KK**KK++'zz'33X5K5Kf !!"4dFC"*"2"2"<"<">>JCKK%%j#u=>==KK%%&;S=OP %%h/::+ ++DJ KK  x (7=?""M  %3;&"03"", "lln T[[! ($ &)# ""8,%(" "lln T[[!  #s{J AF.F/F3B;J /H A J  J J F HAH<J HJ  JA'J:J JJ )r8r)r.z Origin | Noner/z'Sequence[ClientExtensionFactory] | Noner0zSequence[Subprotocol] | Noner1r"r2z int | Noner3zLoggerLike | NonereturnNone)rr)rfrrr)rPrrzlist[Extension])rPrrzSubprotocol | None)rzrrr)rzGenerator[None]) __name__ __module__ __qualname____doc__rr7rRrircrdr{r} __classcell__r=s@r>r,r,0s4!%>B59!$$(" " " < " 3 """"" ".!8F+=ZG#R"H 0)#)#r?c eZdZdfd ZxZS)ClientConnectioncXtjdtt||i|y)Nz.ClientConnection was renamed to ClientProtocol)warningswarnDeprecationWarningr6r7)r<argskwargsr=s r>r7zClientConnection.__init__Ws) <   $)&)r?)rrrrrr)rrrr7rrs@r>rrVs **r?r WEBSOCKETS_BACKOFF_INITIAL_DELAY5WEBSOCKETS_BACKOFF_MIN_DELAYz3.1WEBSOCKETS_BACKOFF_MAX_DELAYz90.0WEBSOCKETS_BACKOFF_FACTORz1.618c#tKtj|z|}||kr|||z}||kr |w)z Generate a series of backoff delays between reconnection attempts. Yields: How many seconds to wait before retrying to connect. )random) initial_delay min_delay max_delayfactordelays r>backoffresM --/M )) E )    )   s/88z.legacy.client)WebSocketClientProtocolrR unix_connect)deprecated_aliases) rfloatrrrrrrrzGenerator[float])C __future__rosrrcollections.abcrrtypingrdatastructuresrr exceptionsr r r r rrrr/rrrPrrrrrrrrhttp11rrimportsrprotocolrrr r!r"r#r$r%r&r'r(r8r)utilsr*r+__all__r,rrenvirongetBACKOFF_INITIAL_DELAYBACKOFF_MIN_DELAYBACKOFF_MAX_DELAYBACKOFF_FACTORrglobalsr?r>rsP" /8:   & ??+  c#Xc#L *~*bjjnn-OQTUV"**..)GOP"**..)GPQrzz~~&A7KL1(("     0  I$4#( r?