Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
server.cpython-313.pyc321 linesDownload Raw Back to __pycache__
1�

2p�jo��`�SSKJr SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSK	r3SSKrSSKrSSK
r
SSKJrJr SSKJr SSKJrJrJrJr SSKJr SSKJr SS	KJr SS4KJr SSK J!r!J"r"J#r# SSK$J%r%J&r&J'r' SS
K(J)r)J*r*J+r+ SSK,J-r- SSKJ.r.J/r/J0r0J1r1 SSK2J3r3 SSK4J5r5 /SQr6"SS\35r7"SS5r8S#Sjr9S$SSSSSSSSS\%SSSSSSSSS.S%Sjjjr:S&S'S jjr;S(S!jr<S)S*S"jjr=g)+�)�annotationsN)�Iterable�Sequence)�
TracebackType)�Any�Callable�Mapping�cast�)�
InvalidHeader)�ServerExtensionFactory)� enable_server_permessage_deflate)�	CloseCode)�build_www_authenticate_basic�parse_authorization_basic�validate_subprotocols)�SERVER�Request�Response)�5CONNECTING�OPEN�Event)�ServerProtocol)�6LoggerLike�Origin�7StatusLike�Subprotocol�)�8Connection)�Deadline)�serve�9unix_serve�ServerConnection�Server�10basic_authc�^�\rSrSrSrSSSSS.SU4SjjjrSSjrS	S	\S	4SS11jjrSU4Sjjr	SU4Sjjr12S
rU=r$)r#�&a�13:mod:`threading` implementation of a WebSocket server connection.14 15:class:`ServerConnection` provides :meth:`recv` and :meth:`send` methods for16receiving and sending messages.17 18It supports iteration to receive messages::19 20    for message in websocket:21        process(message)22 23The iterator exits normally when the connection is closed with code241000 (OK) or 1001 (going away) or without a close code. It raises a25:exc:`~websockets.exceptions.ConnectionClosedError` when the connection is26closed with any other code.27 28The ``ping_interval``, ``ping_timeout``, ``close_timeout``, and29``max_queue`` arguments have the same meaning as in :func:`serve`.30 31Args:32    socket: Socket connected to a WebSocket client.33    protocol: Sans-I/O connection.34 35��36���
ping_interval�ping_timeout�
close_timeout�	max_queuec	�n>�U [R"5Ul[TU]UUUUUUS9 U U U g)Nr+)�	threadingr�request_rcvd�super�__init__)�self�socket�protocolr,r-r.r/�	__class__s       ��\D:\code\apps\devtools\python\user_packages\Python313\site-packages\websockets/sync/server.pyr4�ServerConnection.__init__@sF���	
�%�O�O�-���
�����'�%�'��
	�	37�	
���c�8�URRX5$)a�38Create a plain text HTTP response.39 40``process_request`` and ``process_response`` may call this method to41return an HTTP response instead of performing the WebSocket opening42handshake.43 44You can modify the response before returning it, for example by changing45HTTP headers.46 47Args:48    status: HTTP status code.49    text: HTTP response body; it will be encoded to UTF-8.50 51Returns:52    HTTP response to send to the client.53 54)r7�reject)r5�status�texts   r9�respond�ServerConnection.respondXs��&�}�}�#�#�F�1�1r;Nc��URRU5(d[S5eURb�UR	[55S9 SnUbU"XR5nUc+URRUR5UlOXPlU(aX0RRS'SnUb'U"XRUR5nUbXPlURR!UR5 SSS5 URRbURReg![aOnX`RlURR[RRS5nSnAGN.SnAff=f![aOnX`RlURR[RRS5nSnAGNSnAff=f!,(df   N�=f)z!56Perform the opening handshake.57 58z-timed out while waiting for handshake requestN)�expected_statezLFailed to open a WebSocket connection.59See server log for more information.60r$)r2�wait�TimeoutError�request�send_contextr�	Exceptionr7�
handshake_excr=�http�61HTTPStatus�INTERNAL_SERVER_ERROR�accept�response�headers�
send_response)r5�process_request�process_response�
server_header�timeoutrN�excs       r9�	handshake�ServerConnection.handshakems���.� � �%�%�g�.�.��N�O�O��<�<�#��"�"�*�"�=���"�.�62�#2�4���#F���#�$(�M�M�$8�$8����$F�D�M�$,�M� �6C�M�M�)�)�(�3���#�/�63�#3�D�,�,��
�
�#V�� �+�(0�
��
�
�+�+�D�M�M�:�U>�h�=�=�&�&�2��-�-�-�-�-�3��]%��69�
�
�3�#'�=�=�#7�#7� �O�O�A�A�!I�$�����.%��69�
�
�3�#'�=�=�#7�#7� �O�O�A�A�!I�$�����;>�=�sc�G7�D?�%AG7�>F�.G7�?64F�	AF�
G7�F�G7�65G4�%AG/�)G7�/G4�4G7�766Hc�>�URc8[U[5(deXlURR	5 g[67TU]U5 g)z68Process one incoming event.69 70N)rF�71isinstancerr2�setr3�
process_event)r5�eventr8s  �r9r[�ServerConnection.process_event�sH����<�<���e�W�-�-�-�-� �L����!�!�#�
�G�!�%�(r;c�>�[TU]5 URR5 g!URR5 f=f)z972Read incoming data from the socket and process events.73 74N)r3�recv_eventsr2rZ)r5r8s �r9r_�ServerConnection.recv_events�s:���75	$��G��!�
���!�!�#��D���!�!�#�s	�,�A)rFr2rN)r6�
socket.socketr7rr,�float | Noner-rbr.rbr/�*int | None | tuple[int | None, int | None]�return�None)r>rr?�strrdr)76rQ�=Callable[[ServerConnection, Request], Response | None] | NonerR�GCallable[[ServerConnection, Request, Response], Response | None] | NonerS�77str | NonerTrbrdre)r\rrdre�rdre)
�__name__�78__module__�__qualname__�__firstlineno__�__doc__r4r@rrVr[r_�__static_attributes__�
__classcell__)r8s@r9r#r#&s�����<')�%'�&(�@B�/��/�!�/�79$�/�#�
/�$�/�>�/�80�/�/�02�:
�
�$*� $�#P.�
�P.�
�P.� "�!P.�"�#P.�$81�%P.�d)�	$�	$r;r#c�x�\rSrSrSrSSSjjrS
SjrS
SjrSSjrSSjr	SS	jr82S83rg)r$��aw84WebSocket server returned by :func:`serve`.85 86This class mirrors the API of :class:`~socketserver.BaseServer`, notably the87:meth:`~socketserver.BaseServer.serve_forever` and88:meth:`~socketserver.BaseServer.shutdown` methods, as well as the context89manager protocol.90 91Args:92    socket: Server socket listening for new connections.93    handler: Handler for one connection. Receives the socket and address94        returned by :meth:`~socket.socket.accept`.95    logger: Logger for this server.96        It defaults to ``logging.getLogger("websockets.server")``.97        See the :doc:`logging guide <../../topics/logging>` for details.98 99Nc���XlX lUc[R"S5nX0l[100RS:wa#[R"5uUl	Ul101gg)Nzwebsockets.server�win32)r6�handler�logging�	getLogger�logger�sys�platform�os�pipe�shutdown_watcher�shutdown_notifier)r5r6rvrys    r9r4�Server.__init__�sP�������>��&�&�':�;�F����<�<�7�"�<>�G�G�I�9�D�!�4�#9�#r;c���[R"5nURUR[R5 [RS:wa*URUR[R5 UR5 URR5up#[R"URX#4S9nUR5 M_![102a gf=f![a gf=f)z�103See :meth:`socketserver.BaseServer.serve_forever`.104 105This method doesn't return. Calling :meth:`shutdown` from another thread106stops the server.107 108Typical use::109 110    with serve(...) as server:111        server.serve_forever()112 113Nru)�target�args)�	selectors�DefaultSelector�registerr6�114EVENT_READ�115ValueErrorrzr{r~�selectrM�OSErrorr1�Threadrv�start)r5�poller�sock�addr�threads     r9�
serve_forever�Server.serve_forever�s����*�*�,��	��O�O�D�K�K��)=�)=�>��<�<�7�"��O�O�D�1�1�9�3G�3G�H���M�M�O�
�"�[�[�/�/�1�116���%�%�T�\�\���M�F��L�L�N����	�
�		���
��
�s#�*C�C/�117C,�+C,�/118C<�;C<c��URR5 [RS:wa"[R119"URS5 gg)z0120See :meth:`socketserver.BaseServer.shutdown`.121 122ru�xN)r6�closerzr{r|�writer�r5s r9�shutdown�Server.shutdown s9��123	
�������<�<�7�"��H�H�T�+�+�T�2�#r;c�6�URR5$)z.124See :meth:`socketserver.BaseServer.fileno`.125 126)r6�filenor�s r9r��
Server.fileno)s��127�{�{�!�!�#�#r;c��U$�N�r�s r9�	__enter__�Server.__enter__0s���r;c�$�UR5 gr�)r�)r5�exc_type�	exc_value�	tracebacks    r9�__exit__�Server.__exit__3s
��	
�
�
�r;)rvryrr~r6r�)r6rarvz$Callable[[socket.socket, Any], None]ry�LoggerLike | Nonerdrerj)rd�int)rdr$)r�ztype[BaseException] | Noner�zBaseException | Noner�zTracebackType | Nonerdre)rkrlrmrnror4r�r�r�r�r�rpr�r;r9r$r$�s|���,%)�	F��F�6�F�"�	F�128129�F�$�L3�$���,��(��(�	�130131�r;r$c�~�US:Xa![R"S[5 [$[	S[132<SU<35e)N�WebSocketServerz%WebSocketServer was renamed to Serverzmodule z has no attribute )�warnings�warn�DeprecationWarningr$�AttributeErrorrk)�names r9�__getattr__r�<s=��� � ��
�
�3��	133��
�134�7�8�,�.@���I�135J�Jr;�deflater)r(ir*)r��ssl�origins�136extensions�subprotocols�select_subprotocol�compressionrQrRrS�open_timeoutr,r-r.�max_sizer/ry�create_connectionc�^^^^^^^137^^^
^^^^^^^^�Tc2SU;a,URS5m[R"S[5 Tb[	T5 U	S:Xa[T5mOU	b[
SU	35eTc[mURSS5mURSS5nUcfT(aFUc[
S	5eURS138[R5 [R"U40UD6nO'[R"X440UD6nOUb[
S5eTbTRUSSS
9nSUUUUUUUU
UUUU139UUUUUU4Sjjn[UUT5$)a>140Create a WebSocket server listening on ``host`` and ``port``.141 142Whenever a client connects, the server creates a :class:`ServerConnection`,143performs the opening handshake, and delegates to the ``handler``.144 145The handler receives the :class:`ServerConnection` instance, which you can146use to send and receive messages.147 148Once the handler completes, either normally or with an exception, the server149performs the closing handshake and closes the connection.150 151This function returns a :class:`Server` whose API mirrors152:class:`~socketserver.BaseServer`. Treat it as a context manager to ensure153that it will be closed and call :meth:`~Server.serve_forever` to serve154requests::155 156    from websockets.sync.server import serve157 158    def handler(websocket):159        ...160 161    with serve(handler, ...) as server:162        server.serve_forever()163 164Args:165    handler: Connection handler. It receives the WebSocket connection,166        which is a :class:`ServerConnection`, in argument.167    host: Network interfaces the server binds to.168        See :func:`~socket.create_server` for details.169    port: TCP port the server listens on.170        See :func:`~socket.create_server` for details.171    sock: Preexisting TCP socket. ``sock`` replaces ``host`` and ``port``.172        You may call :func:`socket.create_server` to create a suitable TCP173        socket.174    ssl: Configuration for enabling TLS on the connection.175    origins: Acceptable values of the ``Origin`` header, for defending176        against Cross-Site WebSocket Hijacking attacks. Values can be177        :class:`str` to test for an exact match or regular expressions178        compiled by :func:`re.compile` to test against a pattern. Include179        :obj:`None` in the list if the lack of an origin is acceptable.180    extensions: List of supported extensions, in order in which they181        should be negotiated and run.182    subprotocols: List of supported subprotocols, in order of decreasing183        preference.184    select_subprotocol: Callback for selecting a subprotocol among185        those supported by the client and the server. It receives a186        :class:`ServerConnection` (not a187        :class:`~websockets.server.ServerProtocol`!) instance and a list of188        subprotocols offered by the client. Other than the first argument,189        it has the same behavior as the190        :meth:`ServerProtocol.select_subprotocol191        <websockets.server.ServerProtocol.select_subprotocol>` method.192    compression: The "permessage-deflate" extension is enabled by default.193        Set ``compression`` to :obj:`None` to disable it. See the194        :doc:`compression guide <../../topics/compression>` for details.195    process_request: Intercept the request during the opening handshake.196        Return an HTTP response to force the response. Return :obj:`None` to197        continue normally. When you force an HTTP 101 Continue response, the198        handshake is successful. Else, the connection is aborted.199    process_response: Intercept the response during the opening handshake.200        Modify the response or return a new HTTP response to force the201        response. Return :obj:`None` to continue normally. When you force an202        HTTP 101 Continue response, the handshake is successful. Else, the203        connection is aborted.204    server_header: Value of  the ``Server`` response header.205        It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to206        :obj:`None` removes the header.207    open_timeout: Timeout for opening connections in seconds.208        :obj:`None` disables the timeout.209    ping_interval: Interval between keepalive pings in seconds.210        :obj:`None` disables keepalive.211    ping_timeout: Timeout for keepalive pings in seconds.212        :obj:`None` disables timeouts.213    close_timeout: Timeout for closing connections in seconds.214        :obj:`None` disables the timeout.215    max_size: Maximum size of incoming messages in bytes.216        :obj:`None` disables the limit. You may pass a ``(max_message_size,217        max_fragment_size)`` tuple to set different limits for messages and218        fragments when you expect long messages sent in short fragments.219    max_queue: High-water mark of the buffer where frames are received.220        It defaults to 16 frames. The low-water mark defaults to ``max_queue221        // 4``. You may pass a ``(high, low)`` tuple to set the high-water222        and low-water marks. If you want to disable flow control entirely,223        you may set it to ``None``, although that's a bad idea.224    logger: Logger for this server.225        It defaults to ``logging.getLogger("websockets.server")``. See the226        :doc:`logging guide <../../topics/logging>` for details.227    create_connection: Factory for the :class:`ServerConnection` managing228        the connection. Set it to a wrapper or a subclass to customize229        connection handling.230 231Any other keyword arguments are passed to :func:`~socket.create_server`.232 233N�ssl_contextzssl_context was renamed to sslr�zunsupported compression: �unixF�pathzmissing path argument�familyz(path and sock arguments are incompatibleT)�server_side�do_handshake_on_connectc	�>^�[T
5nT(d/UR[R[RS5 TbaURUR
55 [U[R5(deUR5 URS5 SnTbSUU4Sjjn[TTTUTT234S9nTceT"UUTTTTS9mTRTTTUR
55 TR*R,[.LdeTR15 T	"T5 TR5 g![a UR5 gf=f![a- TR!5 TR"R%5 g[aG TR&R)SSS9 TR!5 TR"R%5 gf=f![a< TR&R)SSS9 TR45 gf=f![a UR5 gf=f)	NTc�B>�TceUTRLdeT"TU5$r�)r7)r7r��235connectionr�s  ��r9�protocol_select_subprotocol�@serve.<locals>.conn_handler.<locals>.protocol_select_subprotocol*s2���236.�9�9�9�#�z�':�':�:�:�:�-�j�,�G�Gr;)r�r�r�r�r�ryr+zopening handshake failed)�exc_infozconnection handler failed)r7rr�zSequence[Subprotocol]rdzSubprotocol | None)r �237setsockoptr6�IPPROTO_TCP�TCP_NODELAY�238settimeoutrTrY�239ssl_module�	SSLSocket�do_handshakerrHr�rVrE�close_socket�recv_events_thread�joinry�errorr7�stater�start_keepaliver�INTERNAL_ERROR)r�r��deadliner�r7r�r.r�r�rvryr/r�r�r�r,r-rQrRr�rSr�r�r�s     @������������������r9�conn_handler�serve.<locals>.conn_handlers]����L�)��;	������ 2� 2�F�4F�4F��M������� 0� 0� 2�3�!�$�240�(<�(<�=�=�=�=��!�!�#�����%��

(�"�-�H�,�H�"7�H�(�H�H�&��%�)�#>�!��
�H�%�0�0�0�*���+�)�+�#�
�J�	�
��$�$�#�$�!��$�$�&�	� �&�&�,�,��4�4�4�
#��*�*�,��241�#�242� � �"��=�	��J�J�L��	�� �
��'�'�)��-�-�2�2�4���
��!�!�'�'�(B�T�'�R��'�'�)��-�-�2�2�4��	
���
;��!�!�'�'�(C�d�'�S�� � ��!9�!9�:�
;���	��J�J�L�	�st�CE�"E(�?H:�G1�7H:�E%�$E%�(4G.�H:�A
G.�+H:�-G.�.H:�1AH7�4H:�6H7�7H:�:I�I)r�rar�rrdre)�popr�r�r�rrr�r#�243setdefaultr6�AF_UNIX�
create_server�wrap_socketr$)rv�host�portr�r�r�r�r�r�r�rQrRrSr�r,r-r.r�r/ryr��kwargsr�r�r�s`   ````` ```````````   @r9r!r!FsU�����j�{�}��.��j�j��'���
�
�,��	244�245���l�+��i��5�j�A�246�	�	 ��4�[�M�B�C�C�� �,��247���F�E�*�D��z�z�&�$�/�D��|���|� �!8�9�9����h����7��'�'��7��7�D��'�'���?��?�D����G�H�H��������$)�	�248��a�a�a�a�J�$��f�-�-r;c� �[U4SUS.UD6$)a�249Create a WebSocket server listening on a Unix socket.250 251This function accepts the same keyword arguments as :func:`serve`.252 253It's only available on Unix.254 255It's useful for deploying a server behind a reverse proxy such as nginx.256 257Args:258    handler: Connection handler. It receives the WebSocket connection,259        which is a :class:`ServerConnection`, in argument.260    path: File system path to the Unix socket.261 262T)r�r�)r!)rvr�r�s   r9r"r"ss��(��9�t�$�9�&�9�9r;c��Uup[U[5=(a [U[5$![[4a gf=f�NF)rYrf�	TypeErrorr�)�credentials�username�passwords   r9�is_credentialsr��sD��G�(����(�C�(�F�Z��#�-F�F��
�z�"����s�-�A�Ac��^^^�USLTSL:Xa[S5eUb�[U5(a[[[[4U5/nOv[U[5(aS[[[[[[4U55n[SU55(d[SU35eO[SU35e[U5mSU4SjjmTceSUU4SjjnU$)	a�263Factory for ``process_request`` to enforce HTTP Basic Authentication.264 265:func:`basic_auth` is designed to integrate with :func:`serve` as follows::266 267    from websockets.sync.server import basic_auth, serve268 269    with serve(270        ...,271        process_request=basic_auth(272            realm="my dev server",273            credentials=("hello", "iloveyou"),274        ),275    ):276 277If authentication succeeds, the connection's ``username`` attribute is set.278If it fails, the server responds with an HTTP 401 Unauthorized status.279 280One of ``credentials`` or ``check_credentials`` must be provided; not both.281 282Args:283    realm: Scope of protection. It should contain only ASCII characters284        because the encoding of non-ASCII characters is undefined. Refer to285        section 2.2 of :rfc:`7235` for details.286    credentials: Hard coded authorized credentials. It can be a287        ``(username, password)`` pair or a list of such pairs.288    check_credentials: Function that verifies credentials.289        It receives ``username`` and ``password`` arguments and returns290        whether they're valid.291Raises:292    TypeError: If ``credentials`` or ``check_credentials`` is wrong.293    ValueError: If ``credentials`` and ``check_credentials`` are both294        provided or both not provided.295 296Nz/provide either credentials or check_credentialsc3�8# �UHn[U5v� M g7fr�)r�)�.0�items  r9�	<genexpr>�basic_auth.<locals>.<genexpr>�s���I�8H��~�d�+�+�8H�s�zinvalid credentials argument: c�\>�TUn[R"X!5$![a gf=fr�)�KeyError�hmac�compare_digest)r�r��expected_password�credentials_dicts   �r9�check_credentials�%basic_auth.<locals>.check_credentials�s;���
�$4�X�$>�!��&�&�'8�C�C���
��
�s��297+�+c�@>�URSn[U5upET"XE5(dDUR[RR298S5n[
T5URS'U$X@l	g![aG UR[RR299S5n[
T5URS'Us$f=f![aG UR[RR300S5n[
T5URS'Us$f=f)z�301Perform HTTP Basic Authentication.302 303If it succeeds, set the connection's ``username`` attribute and return304:obj:`None`. If it fails, return an HTTP 401 Unauthorized responss.305 306�
AuthorizationzMissing credentials307zWWW-AuthenticatezUnsupported credentials308zInvalid credentials309N)310rOr�r@rJrK�UNAUTHORIZEDrrrr�)r�rF�
authorizationrNr�r�r��realms      ��r9rQ�#basic_auth.<locals>.process_request�s���	�#�O�O�O�<�M�	�!:�=�!I��H�!��4�4�!�)�)����,�,�'��H�4P�PU�3V�H���/�0��O�&����7�	�!�)�)����,�,�'��H�4P�PU�3V�H���/�0��O�
	���	�!�)�)����,�,�+��H�4P�PU�3V�H���/�0��O�
	�s$�A8�
C�8AC	�C	�AD�D)r�rfr�rfrd�bool)r�r#rFrrdzResponse | None)r�r�r311�tuplerfrYr�list�allr��dict)r�r�r��credentials_listrQr�s` `  @r9r%r%�s���P	�t��!2�d�!:�;��J�K�K����+�&�&� $�U�3��8�_�k� B�C��
��X�
.�
.�#�D��%��S��/�)B�K�$P�Q���I�8H�I�I�I��"@��
� N�O�O�J��<�[�M�J�K�K�� 0�1��	D��(�(�(�(�$�(��(�312�(�(�T�r;)r�rfrdr)NN).rv�"Callable[[ServerConnection], None]r�rir�z313int | Noner�zsocket.socket | Noner�zssl_module.SSLContext | Noner�z0Sequence[Origin | re.Pattern[str] | None] | Noner�z'Sequence[ServerExtensionFactory] | Noner�zSequence[Subprotocol] | Noner�zNCallable[[ServerConnection, Sequence[Subprotocol]], Subprotocol | None] | Noner�rirQrgrRrhrSrir�rbr,rbr-rbr.rbr�rcr/rcryr�r�ztype[ServerConnection] | Noner�rrdr$r�)rvrr�rir�rrdr$)r�rrdr�)�NN)r�rfr�z2tuple[str, str] | Iterable[tuple[str, str]] | Noner�z!Callable[[str, str], bool] | Nonerdz6Callable[[ServerConnection, Request], Response | None])>�314__future__rr�rJrwr|�rer�r6r�r�rzr1r��collections.abcrr�typesr�typingrrr	r315�316exceptionsr�extensions.baser
�extensions.permessage_deflater�framesrrOrrr�http11rrrr7rrr�serverrrrrrr�r�utilsr �__all__r#r$r�r!r"r�r%r�r;r9�<module>rsb��"����	�	��
��317���.��/�/�&�4�L����318/�.�.�.�#�@�@�"��N��p$�z�p$�f`�`�FK���j.�"&�(,�@D�:>�15�	
�'�	
�	
� &�!#�"$�!#�"$�;@�<>� $�7;�_j.�
/�j.�319�j.��j.��
j.�320&�j.�>�j.�8�j.�/�j.�	�j.�&�'j.�,	�-j.�:	�;j.�F�Gj.�J�Kj.�L �Mj.�N�Oj.�P �Qj.�T9�Uj.�V:�Wj.�Z
�[j.�^5�_j.�`�aj.�b�cj.�^	�:�
/�:�321�:��:��	:�.G��FJ�;?�j��j�C�j�9�j�<�	jr;
codekingpro/portable-devtools · Team Ai