%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /lib/python3/dist-packages/twisted/protocols/__pycache__/
Upload File :
Create Path :
Current File : //lib/python3/dist-packages/twisted/protocols/__pycache__/amp.cpython-312.pyc

�

Ϫ�f�z����dZddlmZddlZddlZddlZddlmZddlm	Z	ddl
mZddlm
Z
ddlmZdd	lmZmZmZmZmZmZmZmZmZmZdd
lmZmZddlmZm Z m!Z!ddl"m#Z#m$Z$m%Z%dd
l&m'Z'ddl(m)Z)ddl*m+Z+ddl,m-Z-m.Z.ddl/m0Z0m1Z1ddl2m3Z4m5Z6ddl7m8Z8ddl9m:Z:ddl;m<Z<	ddl=m>Z?e?j�r
ddlAmBZBmCZCmDZDmEZEndZ>e?Z>gd�ZGededeHf��ZIdZJdZKdZLdZMd ZNd!ZOd"ZPd#ZQd$ZRd%ZSGd&�d'e�ZTGd(�d)e�ZUGd*�d+e�ZVGd,�d-e�ZWGd.�d/eX�ZYGd0�d1eX�ZZGd2�d3eY�Z[Gd4�d5eY�Z\Gd6�d7eY�Z]Gd8�d9eY�Z^Gd:�d;eY�Z_Gd<�d=eY�Z`Gd>�d?e`�ZaGd@�dAeY�ZbGdB�dCeY�ZcGdD�dEeY�ZdeQeciZeGdF�dGeefeff�ZgegZhGdH�dIeg�ZiGdJ�dKeg�ZjeeV�GdL�dM��ZkGdN�dOel�ZmeeW�GdP�dQem�R��ZneeW�GdS�dT��ZogdU�ZpdV�ZqeeT�GdW�dX��ZrGdY�dZer�ZsGd[�d\er�ZtGd]�d^er�ZuGd_�d`er�ZvGda�dbet�ZwGdc�ddew�ZxGde�dfer�ZyGdg�dher�ZzGdi�djes�Z{edk�Z|Gdl�dmel�Z}Gdn�doe}�R�Z~Gdp�dq�ZGdr�dseg�Z�Gdt�duet�Z�Gdv�dwe~�Z�Gdx�dye~�Z�ee'�Gdz�d{��Z�eeU�Gd|�d}e.e-e���Z�Gd~�de�ekeneo�Z�Gd��d��Z�e��jZ�e��jZ�d��Z�d��Z�Gd��d�er�Z�Gd��d�er�Z�y#eF$rdZ>Y���wxYw)�a�
This module implements AMP, the Asynchronous Messaging Protocol.

AMP is a protocol for sending multiple asynchronous request/response pairs over
the same connection.  Requests and responses are both collections of key/value
pairs.

AMP is a very simple protocol which is not an application.  This module is a
"protocol construction kit" of sorts; it attempts to be the simplest wire-level
implementation of Deferreds.  AMP provides the following base-level features:

    - Asynchronous request/response handling (hence the name)

    - Requests and responses are both key/value pairs

    - Binary transfer of all data: all data is length-prefixed.  Your
      application will never need to worry about quoting.

    - Command dispatching (like HTTP Verbs): the protocol is extensible, and
      multiple AMP sub-protocols can be grouped together easily.

The protocol implementation also provides a few additional features which are
not part of the core wire protocol, but are nevertheless very useful:

    - Tight TLS integration, with an included StartTLS command.

    - Handshaking to other protocols: because AMP has well-defined message
      boundaries and maintains all incoming and outgoing requests for you, you
      can start a connection over AMP and then switch to another protocol.
      This makes it ideal for firewall-traversal applications where you may
      have only one forwarded port but multiple applications that want to use
      it.

Using AMP with Twisted is simple.  Each message is a command, with a response.
You begin by defining a command type.  Commands specify their input and output
in terms of the types that they expect to see in the request and response
key-value pairs.  Here's an example of a command that adds two integers, 'a'
and 'b'::

    class Sum(amp.Command):
        arguments = [('a', amp.Integer()),
                     ('b', amp.Integer())]
        response = [('total', amp.Integer())]

Once you have specified a command, you need to make it part of a protocol, and
define a responder for it.  Here's a 'JustSum' protocol that includes a
responder for our 'Sum' command::

    class JustSum(amp.AMP):
        def sum(self, a, b):
            total = a + b
            print 'Did a sum: %d + %d = %d' % (a, b, total)
            return {'total': total}
        Sum.responder(sum)

Later, when you want to actually do a sum, the following expression will return
a L{Deferred} which will fire with the result::

    ClientCreator(reactor, amp.AMP).connectTCP(...).addCallback(
        lambda p: p.callRemote(Sum, a=13, b=81)).addCallback(
            lambda result: result['total'])

Command responders may also return Deferreds, causing the response to be
sent only once the Deferred fires::

    class DelayedSum(amp.AMP):
        def slowSum(self, a, b):
            total = a + b
            result = defer.Deferred()
            reactor.callLater(3, result.callback, {'total': total})
            return result
        Sum.responder(slowSum)

This is transparent to the caller.

You can also define the propagation of specific errors in AMP.  For example,
for the slightly more complicated case of division, we might have to deal with
division by zero::

    class Divide(amp.Command):
        arguments = [('numerator', amp.Integer()),
                     ('denominator', amp.Integer())]
        response = [('result', amp.Float())]
        errors = {ZeroDivisionError: 'ZERO_DIVISION'}

The 'errors' mapping here tells AMP that if a responder to Divide emits a
L{ZeroDivisionError}, then the other side should be informed that an error of
the type 'ZERO_DIVISION' has occurred.  Writing a responder which takes
advantage of this is very simple - just raise your exception normally::

    class JustDivide(amp.AMP):
        def divide(self, numerator, denominator):
            result = numerator / denominator
            print 'Divided: %d / %d = %d' % (numerator, denominator, total)
            return {'result': result}
        Divide.responder(divide)

On the client side, the errors mapping will be used to determine what the
'ZERO_DIVISION' error means, and translated into an asynchronous exception,
which can be handled normally as any L{Deferred} would be::

    def trapZero(result):
        result.trap(ZeroDivisionError)
        print "Divided by zero: returning INF"
        return 1e1000
    ClientCreator(reactor, amp.AMP).connectTCP(...).addCallback(
        lambda p: p.callRemote(Divide, numerator=1234,
                               denominator=0)
        ).addErrback(trapZero)

For a complete, runnable example of both of these commands, see the files in
the Twisted repository::

    doc/core/examples/ampserver.py
    doc/core/examples/ampclient.py

On the wire, AMP is a protocol which uses 2-byte lengths to prefix keys and
values, and empty keys to separate messages::

    <2-byte length><key><2-byte length><value>
    <2-byte length><key><2-byte length><value>
    ...
    <2-byte length><key><2-byte length><value>
    <NUL><NUL>                  # Empty Key == End of Message

And so on.  Because it's tedious to refer to lengths and NULs constantly, the
documentation will refer to packets as if they were newline delimited, like
so::

    C: _command: sum
    C: _ask: ef639e5c892ccb54
    C: a: 13
    C: b: 81

    S: _answer: ef639e5c892ccb54
    S: total: 94

Notes:

In general, the order of keys is arbitrary.  Specific uses of AMP may impose an
ordering requirement, but unless this is specified explicitly, any ordering may
be generated and any ordering must be accepted.  This applies to the
command-related keys I{_command} and I{_ask} as well as any other keys.

Values are limited to the maximum encodable size in a 16-bit length, 65535
bytes.

Keys are limited to the maximum encodable size in a 8-bit length, 255 bytes.
Note that we still use 2-byte lengths to encode keys.  This small redundancy
has several features:

    - If an implementation becomes confused and starts emitting corrupt data,
      or gets keys confused with values, many common errors will be signalled
      immediately instead of delivering obviously corrupt packets.

    - A single NUL will separate every key, and a double NUL separates
      messages.  This provides some redundancy when debugging traffic dumps.

    - NULs will be present at regular intervals along the protocol, providing
      some padding for otherwise braindead C implementations of the protocol,
      so that <stdio.h> string functions will see the NUL and stop.

    - This makes it possible to run an AMP server on a port also used by a
      plain-text protocol, and easily distinguish between non-AMP clients (like
      web browsers) which issue non-NUL as the first byte, and AMP clients,
      which always issue NUL as the first byte.

@var MAX_VALUE_LENGTH: The maximum length of a message.
@type MAX_VALUE_LENGTH: L{int}

@var ASK: Marker for an Ask packet.
@type ASK: L{bytes}

@var ANSWER: Marker for an Answer packet.
@type ANSWER: L{bytes}

@var COMMAND: Marker for a Command packet.
@type COMMAND: L{bytes}

@var ERROR: Marker for an AMP box of error type.
@type ERROR: L{bytes}

@var ERROR_CODE: Marker for an AMP box containing the code of an error.
@type ERROR_CODE: L{bytes}

@var ERROR_DESCRIPTION: Marker for an AMP box containing the description of the
    error.
@type ERROR_DESCRIPTION: L{bytes}
�)�annotationsN)�partial)�BytesIO)�count)�pack)�
MethodType)
�Any�Callable�ClassVar�Dict�List�Optional�Tuple�Type�TypeVar�Union)�	Interface�implementer)�Deferred�fail�
maybeDeferred)�ConnectionClosed�ConnectionLost�PeerVerifyError)�IFileDescriptorReceiver)�CONNECTION_LOST)�Protocol)�Int16StringReceiver�StatefulStringProtocol)�filepath�log)�UTC�FixedOffsetTimeZone)�nativeString)�Failure)�accumulateClassDict)�ssl)�DN�Certificate�CertificateOptions�KeyPair)5�AMP�ANSWER�ASK�AmpBox�AmpError�AmpList�Argument�BadLocalReturn�BinaryBoxProtocol�Boolean�Box�
BoxDispatcher�COMMAND�Command�CommandLocator�Decimal�
Descriptor�ERROR�
ERROR_CODE�ERROR_DESCRIPTION�Float�
IArgumentType�IBoxReceiver�
IBoxSender�IResponderLocator�IncompatibleVersions�Integer�InvalidSignature�ListOf�MAX_KEY_LENGTH�MAX_VALUE_LENGTH�MalformedAmpBox�NoEmptyBoxes�
OnlyOneTLS�PROTOCOL_ERRORS�PYTHON_KEYWORDS�Path�ProtocolSwitchCommand�ProtocolSwitched�QuitBox�RemoteAmpError�SimpleStringLocator�StartTLS�String�TooLong�UNHANDLED_ERROR_CODE�UNKNOWN_ERROR_CODE�UnhandledCommand�utc�Unicode�UnknownRemoteError�parse�parseString�_T_Callable.)�bounds_asks_answers_commands_errors_error_codes_error_descriptionsUNKNOWNs	UNHANDLED��c��eZdZdZd�Zd�Zy)rAz�
    An L{IArgumentType} can serialize a Python object into an AMP box and
    deserialize information from an AMP box back into a Python object.

    @since: 9.0
    c��y)a
        Given an argument name and an AMP box containing serialized values,
        extract one or more Python objects and add them to the C{objects}
        dictionary.

        @param name: The name associated with this argument. Most commonly
            this is the key which can be used to find a serialized value in
            C{strings}.
        @type name: C{bytes}

        @param strings: The AMP box from which to extract one or more
            values.
        @type strings: C{dict}

        @param objects: The output dictionary to populate with the value for
            this argument. The key used will be derived from C{name}. It may
            differ; in Python 3, for example, the key will be a Unicode/native
            string. See L{_wireNameToPythonIdentifier}.
        @type objects: C{dict}

        @param proto: The protocol instance which received the AMP box being
            interpreted.  Most likely this is an instance of L{AMP}, but
            this is not guaranteed.

        @return: L{None}
        N���name�strings�objects�protos    �7/usr/lib/python3/dist-packages/twisted/protocols/amp.py�fromBoxzIArgumentType.fromBoxI���c��y)a=
        Given an argument name and a dictionary containing structured Python
        objects, serialize values into one or more strings and add them to
        the C{strings} dictionary.

        @param name: The name associated with this argument. Most commonly
            this is the key in C{strings} to associate with a C{bytes} giving
            the serialized form of that object.
        @type name: C{bytes}

        @param strings: The AMP box into which to insert one or more strings.
        @type strings: C{dict}

        @param objects: The input dictionary from which to extract Python
            objects to serialize. The key used will be derived from C{name}.
            It may differ; in Python 3, for example, the key will be a
            Unicode/native string. See L{_wireNameToPythonIdentifier}.
        @type objects: C{dict}

        @param proto: The protocol instance which will send the AMP box once
            it is fully populated.  Most likely this is an instance of
            L{AMP}, but this is not guaranteed.

        @return: L{None}
        Nrgrhs    rm�toBoxzIArgumentType.toBoxerorpN)�__name__�
__module__�__qualname__�__doc__rnrrrgrprmrArAAs����8rprAc��eZdZdZd�Zd�Zy)rCz7
    A transport which can send L{AmpBox} objects.
    c��y)z�
        Send an L{AmpBox}.

        @raise ProtocolSwitched: if the underlying protocol has been
        switched.

        @raise ConnectionLost: if the underlying connection has already been
        lost.
        Nrg��boxs rm�sendBoxzIBoxSender.sendBox�rorpc��y)z�
        An unhandled error occurred in response to a box.  Log it
        appropriately.

        @param failure: a L{Failure} describing the error that occurred.
        Nrg)�failures rm�unhandledErrorzIBoxSender.unhandledError�rorpN)rsrtrurvr{r~rgrprmrCrC�s���	�rprCc�"�eZdZdZd�Zd�Zd�Zy)rBzh
    An application object which can receive L{AmpBox} objects and dispatch them
    appropriately.
    c��y)z�
        The L{IBoxReceiver.ampBoxReceived} method will start being called;
        boxes may be responded to by responding to the given L{IBoxSender}.

        @param boxSender: an L{IBoxSender} provider.
        Nrg��	boxSenders rm�startReceivingBoxesz IBoxReceiver.startReceivingBoxes�rorpc��y)zS
        A box was received from the transport; dispatch it appropriately.
        Nrgrys rm�ampBoxReceivedzIBoxReceiver.ampBoxReceived�rorpc��y)zi
        No further boxes will be received on this connection.

        @type reason: L{Failure}
        Nrg)�reasons rm�stopReceivingBoxeszIBoxReceiver.stopReceivingBoxes�rorpN)rsrtrurvr�r�r�rgrprmrBrB�s���
��
rprBc��eZdZdZd�Zy)rDze
    An application object which can look up appropriate responder methods for
    AMP commands.
    c��y)a�
        Locate a responder method appropriate for the named command.

        @param name: the wire-level name (commandName) of the AMP command to be
        responded to.
        @type name: C{bytes}

        @return: a 1-argument callable that takes an L{AmpBox} with argument
        values for the given command, and returns an L{AmpBox} containing
        argument values for the named command, or a L{Deferred} that fires the
        same.
        Nrg)ris rm�locateResponderz!IResponderLocator.locateResponder�rorpN)rsrtrurvr�rgrprmrDrD�s���
rprDc��eZdZdZy)r0z3
    Base class of all Amp-related exceptions.
    N�rsrtrurvrgrprmr0r0����rpr0c��eZdZdZy)rRz�
    Connections which have been switched to other protocols can no longer
    accept traffic at the AMP level.  This is raised when you try to send it.
    Nr�rgrprmrRrR����rprRc��eZdZdZy)rMz`
    This is an implementation limitation; TLS may only be started once per
    connection.
    Nr�rgrprmrMrM�r�rprMc��eZdZdZy)rLzt
    You can't have empty boxes on the connection.  This is raised when you
    receive or attempt to send one.
    Nr�rgrprmrLrL�r�rprLc��eZdZdZy)rGz5
    You didn't pass all the required arguments.
    Nr�rgrprmrGrG�r�rprGc� �eZdZdZdd�Zdd�Zy)rXa
    One of the protocol's length limitations was violated.

    @ivar isKey: true if the string being encoded in a key position, false if
    it was in a value position.

    @ivar isLocal: Was the string encoded locally, or received too long from
    the network?  (It's only physically possible to encode "too long" values on
    the network for keys.)

    @ivar value: The string that was too long.

    @ivar keyName: If the string being encoded was in a value position, what
    key was it being encoded for?
    Nc�f�tj|�||_||_||_||_y�N)r0�__init__�isKey�isLocal�value�keyName)�selfr�r�r�r�s     rmr�zTooLong.__init__�s,�����$����
������
���rpc���|jxrdxsd}|js|dt|j�zz
}|jxrdxsd}d||t	|j
�fzS)N�keyr�� �local�remotez%s %s too long: %d)r��reprr�r��lenr�)r��hdr�lcls   rm�__repr__zTooLong.__repr__sa���j�j�"�U�-�g���z�z��3��d�l�l�+�+�+�C��l�l�&�w�2�(��#�s�C��T�Z�Z��&A�A�Arpr���return�str)rsrtrurvr�r�rgrprmrXrX�s��� �BrprXc�$�eZdZdZdd�Zdd�ZeZy)r3zU
    A bad value was returned from a local command; we were unable to coerce it.
    c�J�tj|�||_||_yr�)r0r��message�enclosed)r�r�r�s   rmr�zBadLocalReturn.__init__s�����$����� ��
rpc�V�|jdz|jj�zS)Nr�)r�r��getBriefTraceback�r�s rmr�zBadLocalReturn.__repr__s#���|�|�c�!�D�M�M�$C�$C�$E�E�ErpN)r�r�r�r%r��Noner�)rsrtrurvr�r��__str__rgrprmr3r3s���!�
F��Grpr3c�$��eZdZdZd�fd�	Z�xZS)rTz�
    This error indicates that something went wrong on the remote end of the
    connection, and the error was serialized and transmitted to you.
    c���|rd}|j�}nd}d}djd�|D��}|rdj||||�}ndj|||�}t�	|�|�||_||_||_||_y)a�Create a remote error with an error code and description.

        @param errorCode: the AMP error code of this error.
        @type errorCode: C{bytes}

        @param description: some text to show to the user.
        @type description: C{str}

        @param fatal: a boolean, true if this error should terminate the
        connection.

        @param local: a local Failure, if one exists.
        z (local)�c3�HK�|]}|dk\rd|d��n
t|����y�w)�z\x�2xN)�chr)�.0�cs  rm�	<genexpr>z*RemoteAmpError.__init__.<locals>.<genexpr>8s,����&
�67�A��I�c�!�B��L�3�q�6�1�&
�s� "zCode<{}>{}: {}
{}zCode<{}>{}: {}N)	r��join�format�superr�r��	errorCode�description�fatal)
r�r�r�r�r��	localwhat�othertb�errorCodeForMessager��	__class__s
         �rmr�zRemoteAmpError.__init__!s�����"�I��-�-�/�G��I��G�!�g�g�&
�;D�&
�
���*�1�1�#����	�G�'�-�-�#�Y���G�	����!���
�"���&�����
rp)FN)rsrtrurvr��
__classcell__�r�s@rmrTrTs����
+�+rprTc��eZdZdZd�Zy)r^zc
    This means that an error whose type we can't identify was raised from the
    other side.
    c�>�t}tj|||�yr�)rZrTr�)r�r�r�s   rmr�zUnknownRemoteError.__init__Us��&�	�����i��=rpN)rsrtrurvr�rgrprmr^r^Os���
>rpr^c��eZdZdZy)rKzJ
    This error indicates that the wire-level protocol was malformed.
    Nr�rgrprmrKrKZr�rprKc��eZdZdZy)r[z=
    A command received via amp could not be dispatched.
    Nr�rgrprmr[r[`r�rpr[c��eZdZdZy)rEzw
    It was impossible to negotiate a compatible version of the protocol with
    the other end of the connection.
    Nr�rgrprmrErEfr�rprEc�L��eZdZUdZgZded<�fd�Zd�Zd�Zd�Z	d	d�Z
�xZS)
r/z\
    I am a packet in the AMP protocol, much like a
    regular bytes:bytes dictionary.
    �	List[str]�	__slots__c����t�|�|i|��|D�cgc]}t|t�r�|��}}|D]'}|j	d�}|j|�||<�)ycc}w)a

        Initialize a new L{AmpBox}.

        In Python 3, keyword arguments MUST be Unicode/native strings whereas
        in Python 2 they could be either byte strings or Unicode strings.

        However, all keys of an L{AmpBox} MUST be byte strings, or possible to
        transparently coerce into byte strings (i.e. Python 2).

        In Python 3, therefore, native string keys are coerced to byte strings
        by encoding as ASCII. This can result in C{UnicodeEncodeError} being
        raised.

        @param args: See C{dict}, but all keys and values should be C{bytes}.
            On Python 3, native strings may be used as keys provided they
            contain only ASCII characters.

        @param kw: See C{dict}, but all keys and values should be C{bytes}.
            On Python 3, native strings may be used as keys provided they
            contain only ASCII characters.

        @raise UnicodeEncodeError: When a native string key cannot be coerced
            to an ASCII byte string (Python 3 only).
        �asciiN)r�r��
isinstance�bytes�encode�pop)r��args�kw�n�nonByteNames�nonByteName�byteNamer�s       �rmr�zAmpBox.__init__zsj���2	���$�%�"�%�#'�D�a�z�!�U�/C��D��D�'�	3�K�"�)�)�'�2�H�!�X�X�k�2�D��N�	3��Es
�A�Ac�H�|j�}|j|�|S)z5
        Return another AmpBox just like me.
        )r��update)r��newBoxs  rm�copyzAmpBox.copy�s!�����!���
�
�d���
rpc
��t|j��}g}|j}|D]�\}}t|�tk(rtd|z��t|�tk(rtd|�d|����t
|�tkDrtdd|d��t
|�tkDrtdd||��||fD]%}|tdt
|���||��'��|tdd��d	j|�S)
z�
        Convert me into a wire-encoded string.

        @return: a C{bytes} encoded according to the rules described in the
            module docstring.
        zUnicode key not allowed: %rzUnicode value for key z not allowed: TNF�!Hrrp)�sorted�items�append�typer��	TypeErrorr�rIrXrJrr�)r��i�L�w�k�v�kvs       rm�	serializezAmpBox.serialize�s���
�4�:�:�<� ����
�H�H���	�D�A�q��A�w�#�~�� =�� A�B�B��A�w�#�~��"8���^�A�5� Q�R�R��1�v��&��d�D�!�T�2�2��1�v�(�(��e�T�1�a�0�0���d�
���$�t�S��W�%�&��"��
�	�	
�$�t�Q�-���x�x��{�rpc�&�|j|�y)aW
        Serialize and send this box to an Amp instance.  By the time it is being
        sent, several keys are required.  I must have exactly ONE of::

            _ask
            _answer
            _error

        If the '_ask' key is set, then the '_command' key must also be
        set.

        @param proto: an AMP instance.
        N)r{)r�rls  rm�_sendTozAmpBox._sendTo�s��	�
�
�d�rpc�4�dtj|��d�S)NzAmpBox(�))�dictr�r�s rmr�zAmpBox.__repr__�s������t�,�-�Q�/�/rpr�)rsrtrurvr��__annotations__r�r�r�r�r�r�r�s@rmr/r/ps-�����I�y��3�>��2� 0rpr/c�>��eZdZUdZgZded<d�fd�Z�fd�Z�xZS)rSzJ
    I am an AmpBox that, upon being sent, terminates the connection.
    r�r�c�(��dt�|���d�S)Nz
QuitBox(**r�)r�r�)r�r�s �rmr�zQuitBox.__repr__�s����E�G�,�.�/�q�1�1rpc�X��t�|�|�|jj�y)z@
        Immediately call loseConnection after sending.
        N)r�r��	transport�loseConnection�r�rlr�s  �rmr�zQuitBox._sendTo�s!���	�����
���&�&�(rpr�)	rsrtrurvr�r�r�r�r�r�s@rmrSrS�s#�����I�y��2�)�)rprSc�4��eZdZdZ�fd�Zdd�Z�fd�Z�xZS)�
_SwitchBoxz|
    Implementation detail of ProtocolSwitchCommand: I am an AmpBox which sets
    up state for the protocol to switch.
    c�2��t�|�di|��||_y)z�
        Create a _SwitchBox with the protocol to switch to after being sent.

        @param innerProto: the protocol instance to switch to.
        @type innerProto: an IProtocol provider.
        Nrg)r�r��
innerProto)r�r�r�r�s   �rmr�z_SwitchBox.__init__�s���	����2��$��rpc�`�dj|jtj|��S)Nz_SwitchBox({!r}, **{}))r�r�r�r�r�s rmr�z_SwitchBox.__repr__�s(��'�.�.��O�O��M�M�$��
�	
rpc�z��t�|�|�|j�|j|j�y)z{
        Send me; I am the last box on the connection.  All further traffic will be
        over the new protocol.
        N)r�r��_lockForSwitch�	_switchTor�r�s  �rmr�z_SwitchBox._sendTo�s-���
	�����
����
������(rpr�)rsrtrurvr�r�r�r�r�s@rmr�r��s����%�
�)�)rpr�c�~�eZdZdZdZdZdZdZd�Zd�Z	d�Z
d�Zd�Zdd	�Z
dd
�Zd�Zd�Zd
�Zd�Zd�Zd�Zd�Zd�Zy)r7a
    A L{BoxDispatcher} dispatches '_ask', '_answer', and '_error' L{AmpBox}es,
    both incoming and outgoing, to their appropriate destinations.

    Outgoing commands are converted into L{Deferred}s and outgoing boxes, and
    associated tracking state to fire those L{Deferred} when '_answer' boxes
    come back.  Incoming '_answer' and '_error' boxes are converted into
    callbacks and errbacks on those L{Deferred}s, respectively.

    Incoming '_ask' boxes are converted into method calls on a supplied method
    locator.

    @ivar _outstandingRequests: a dictionary mapping request IDs to
    L{Deferred}s which were returned for those requests.

    @ivar locator: an object with a L{CommandLocator.locateResponder} method
        that locates a responder function that takes a Box and returns a result
        (either a Box or a Deferred which fires one).

    @ivar boxSender: an object which can send boxes, via the L{_sendBoxCommand}
    method, such as an L{AMP} instance.
    @type boxSender: L{IBoxSender}
    Nrc� �i|_||_yr�)�_outstandingRequests�locator)r�rs  rmr�zBoxDispatcher.__init__&s��$&��!���rpc��||_y)z�
        The given boxSender is going to start calling boxReceived on this
        L{BoxDispatcher}.

        @param boxSender: The L{IBoxSender} to send command responses to.
        Nr�)r�r�s  rmr�z!BoxDispatcher.startReceivingBoxes*s��#��rpc�&�|j|�y)z�
        No further boxes will be received here.  Terminate all currently
        outstanding command deferreds with the given reason.
        N)�failAllOutgoing�r�r�s  rmr�z BoxDispatcher.stopReceivingBoxes3s��
	
���V�$rpc��||_|jj�}d|_|D]\}}|j|��y)z�
        Call the errback on all outstanding requests awaiting responses.

        @param reason: the Failure instance to pass to those errbacks.
        N)�_failAllReasonrr��errback)r�r��ORr�r�s     rmr	zBoxDispatcher.failAllOutgoing:sG��%���
�
&�
&�
,�
,�
.��$(��!��	"�J�C���M�M�&�!�	"rpc�L�|xjdz
c_d|jfzS)z�
        Generate protocol-local serial numbers for _ask keys.

        @return: a string that has not yet been used on this connection.
        �s%x)�_counterr�s rm�_nextTagzBoxDispatcher._nextTagFs$��	
�
�
���
���
�
�'�'�'rpc�
�|j�|rt|j�Sy||t<|j�}|r	||t<|j|j�|rt�x}|j|<|Sd}|S)a�
        Send a command across the wire with the given C{amp.Box}.

        Mutate the given box to give it any additional keys (_command, _ask)
        required for the command and request/response machinery, then send it.

        If requiresAnswer is True, returns a C{Deferred} which fires when a
        response is received. The C{Deferred} is fired with an C{amp.Box} on
        success, or with an C{amp.RemoteAmpError} if an error is received.

        If the Deferred fails and the error is not handled by the caller of
        this method, the failure will be logged and the connection dropped.

        @param command: a C{bytes}, the name of the command to issue.

        @param box: an AmpBox with the arguments for the command.

        @param requiresAnswer: a boolean.  Defaults to True.  If True, return a
        Deferred which will fire when the other side responds to this command.
        If False, return None and do not ask the other side for acknowledgement.

        @return: a Deferred which fires the AmpBox that holds the response to
        this command, or None, as specified by requiresAnswer.

        @raise ProtocolSwitched: if the protocol has been switched.
        N)	rrr8rr.r�r�rr)r��commandrz�requiresAnswer�tag�results      rm�_sendBoxCommandzBoxDispatcher._sendBoxCommandOs���6���*���D�/�/�0�0����G���m�m�o����C��H����D�N�N�#��6>�j�@�F�T�.�.�s�3��
��F��
rpc�>�t|�}|j|||�S)at
        This is a low-level API, designed only for optimizing simple messages
        for which the overhead of parsing is too great.

        @param command: a C{bytes} naming the command.

        @param kw: arguments to the amp box.

        @param requiresAnswer: a boolean.  Defaults to True.  If True, return a
        Deferred which will fire when the other side responds to this command.
        If False, return None and do not ask the other side for acknowledgement.

        @return: a Deferred which fires the AmpBox that holds the response to
        this command, or None, as specified by requiresAnswer.
        )r6r)r�rrr�rzs     rm�callRemoteStringzBoxDispatcher.callRemoteStringzs"�� �"�g���#�#�G�S�.�A�Arpc�h�	||i|��}|j|�S#t$r
t�cYSwxYw)ah
        This is the primary high-level API for sending messages via AMP.  Invoke it
        with a command and appropriate arguments to send a message to this
        connection's peer.

        @param commandType: a subclass of Command.
        @type commandType: L{type}

        @param a: Positional (special) parameters taken by the command.
        Positional parameters will typically not be sent over the wire.  The
        only command included with AMP which uses positional parameters is
        L{ProtocolSwitchCommand}, which takes the protocol that will be
        switched to as its first argument.

        @param kw: Keyword arguments taken by the command.  These are the
        arguments declared in the command's 'arguments' attribute.  They will
        be encoded and sent to the peer as arguments for the L{commandType}.

        @return: If L{commandType} has a C{requiresAnswer} attribute set to
        L{False}, then return L{None}.  Otherwise, return a L{Deferred} which
        fires with a dictionary of objects representing the result of this
        call.  Additionally, this L{Deferred} may fail with an exception
        representing a connection failure, with L{UnknownRemoteError} if the
        other end of the connection fails for an unknown reason, or with any
        error specified as a key in L{commandType}'s C{errors} dictionary.
        )�
BaseExceptionr�
_doCommand)r��commandType�ar��cos     rm�
callRemotezBoxDispatcher.callRemote�s@��J	��a�&�2�&�B��}�}�T�"�"���	��6�M�	�s��1�1c�8�|jj|�S)zy
        This is a terminal callback called after application code has had a
        chance to quash any errors.
        )r�r~�r�r}s  rmr~zBoxDispatcher.unhandledError�s��
�~�~�,�,�W�5�5rpc��|jj|t�}|j|j�|j|�y)z�
        An AMP box was received that answered a command previously sent with
        L{callRemote}.

        @param box: an AmpBox with a value for its L{ANSWER} key.
        N)rr�r-�
addErrbackr~�callback)r�rz�questions   rm�_answerReceivedzBoxDispatcher._answerReceived�s@���,�,�0�0��V��=�����D�/�/�0����#�rpc�b�|jj|t�}|j|j�|t
}|t}t|t�r|jdd�}|tvrt|||�}nt||�}|jt|��y)z�
        An AMP box was received that answered a command previously sent with
        L{callRemote}, with an error.

        @param box: an L{AmpBox} with a value for its L{ERROR}, L{ERROR_CODE},
        and L{ERROR_DESCRIPTION} keys.
        �utf-8�replaceN)rr�r=r%r~r>r?r�r��decoderNrTr
r%)r�rzr'r�r��excs      rm�_errorReceivedzBoxDispatcher._errorReceived�s����,�,�0�0��U��<�����D�/�/�0��
�O�	��+�,���k�5�)�%�,�,�W�i�@�K���'�!�)�,�Y��D�C� ��K�8�C�������&rpc�����fd�}�fd�}|j��}t�vr-|j||�|j|j�|j|j�y)zc
        @param box: an L{AmpBox} with a value for its L{COMMAND} and L{ASK}
        keys.
        c�(���t|t<|Sr�)r.r-)�	answerBoxrzs �rm�formatAnswerz4BoxDispatcher._commandReceived.<locals>.formatAnswer�s��� #�C��I�f���rpc���|jt�rz|jj}|jj}t|t�r|jdd�}|jjrt�}n2t�}n't�}tj|�t}d}�t|t<||t <||t"<|S)Nr*r+s
Unknown Error)�checkrTr�r�r�r�r�r�r�rSr/r!�errrZr.r=r?r>)�error�code�desc�errorBoxrzs    �rm�formatErrorz3BoxDispatcher._commandReceived.<locals>.formatError�s�����{�{�>�*��{�{�,�,���{�{�.�.���d�C�(��;�;�w�	�:�D��;�;�$�$�&�y�H�%�x�H�"�9�������)��'��!�#�h�H�U�O�*.�H�&�'�#'�H�Z� ��OrpN)�dispatchCommandr.�addCallbacks�addCallback�	_safeEmitr%r~)r�rzr2r:�deferreds `   rm�_commandReceivedzBoxDispatcher._commandReceived�s\���	�	�*�'�'��,���#�:��!�!�,��<�� � ����0����D�/�/�0rpc��t|vr|j|�yt|vr|j|�yt|vr|j|�yt
|��)a�
        An AmpBox was received, representing a command, or an answer to a
        previously issued command (either successful or erroneous).  Respond to
        it according to its contents.

        @param box: an AmpBox

        @raise NoEmptyBoxes: when a box is received that does not contain an
        '_answer', '_command' / '_ask', or '_error' key; i.e. one which does not
        fit into the command / response protocol defined by AMP.
        N)r-r(r=r.r8r@rL�r�rzs  rmr�zBoxDispatcher.ampBoxReceivedsN���S�=�� � ��%�
�c�\�����$�
��^��!�!�#�&��s�#�#rpc�f�	|j|j�y#ttf$rYywxYw)z�
        Emit a box, ignoring L{ProtocolSwitched} and L{ConnectionLost} errors
        which cannot be usefully handled.
        N)r�r�rRr)r��aBoxs  rmr>zBoxDispatcher._safeEmits.��
	��L�L����(�� �.�1�	��	�s��0�0c���|t}|jj|�}|�2d|��}tt	t
|dt
t�����St||�S)z�
        A box with a _command key was received.

        Dispatch it to a local handler call it.

        @param box: an AmpBox to be dispatched.
        zUnhandled Command: F�r�)	r8rr�rrTrYr%r[r)r�rz�cmd�	responderr�s     rmr;zBoxDispatcher.dispatchCommand"sl���'�l���L�L�0�0��5�	���/��w�7�K���(���!�"2�"4�5�	��
��Y��,�,rp)T)rsrtrurvrrrr�r�r�r�r	rrrr!r~r(r.r@r�r>r;rgrprmr7r7sm���0�N����H��I��#�%�
"�(�)�VB�&)#�V6�	�'�(#1�J$�*�-rpr7c�&�eZdZUdZgZded<d�Zy)�_CommandLocatorMetaa�
    This metaclass keeps track of all of the Command.responder-decorated
    methods defined since the last CommandLocator subclass was defined.  It
    assumes (usually correctly, but unfortunately not necessarily so) that
    those commands responders were all declared as methods of the class
    being defined.  Note that this list can be incorrect if users use the
    Command.responder decorator outside the context of a CommandLocator
    class declaration.

    Command responders defined on subclasses are given precedence over
    those inherited from a base class.

    The Command.responder decorator explicitly cooperates with this
    metaclass.
    z0'list[tuple[type[Command], Callable[..., Any]]]'�_currentClassCommandsc��|jdd}g|jddix}|d<tj||||�}t|jdd�}|j�|D]}|j
t|di��� |D]\}	}
|	|
f||	j<�|r'|jtjk7r
d�}||_|S)N�_commandDispatchrc�\�tjdtd��|j|�S)Nz-Override locateResponder, not lookupFunction.���category�
stacklevel)�warnings�warn�PendingDeprecationWarning�lookupFunction�r�ris  rmr�z4_CommandLocatorMeta.__new__.<locals>.locateResponderYs*���
�
�C�6� ��
�*�*�4�0�0rp)rKr��__new__�list�__mro__�reverser��getattr�commandNamerVr:r�)�clsri�bases�attrs�commands�cd�subcls�	ancestors�ancestor�commandClass�
responderFuncr�s            rmrXz_CommandLocatorMeta.__new__Ls����,�,�Q�/��')��!�!�!�$�)+�+��U�%�
&����c�4���6��������+�,�	�����!�	A�H��I�I�g�h�(:�B�?�@�	A�+3�	I�'�L�-�,8�-�+H�B�|�'�'�(�	I��f�+�+�~�/L�/L�L�
1�&5�F�"��
rpN)rsrtrurvrKr�rXrgrprmrJrJ9s��� OQ��K�P�rprJc�"�eZdZdZd�Zd�Zd�Zy)r:z�
    A L{CommandLocator} is a collection of responders to AMP L{Command}s, with
    the help of the L{Command.responder} decorator.
    c��������fd�}|S)a<
        Wrap aCallable with its command's argument de-serialization
        and result serialization logic.

        @param aCallable: a callable with a 'command' attribute, designed to be
        called with keyword arguments.

        @param command: the command class whose serialization to use.

        @return: a 1-arg callable which, when invoked with an AmpBox, will
        deserialize the argument list and invoke appropriate user code for the
        callable's command, returning a Deferred which fires with the result or
        fails with an error.
        c����j|��}�fd�}���fd�}t�fi|��j|�j|�S)Nc����|j�j�}�j|}t|j�}t	t|||�jv|���S)NrF)�trap�	allErrorsr�r�r%rT�fatalErrors)r6r�r7r8rs    �rm�checkKnownErrorszMCommandLocator._wrapWithSerialization.<locals>.doit.<locals>.checkKnownErrorss^��� �e�j�j�'�"3�"3�4���(�(��-���5�;�;�'���"�4��s�g�6I�6I�/I�QV�W��rpc	���	�j|��S#t$r t�}t��d|�d��d�|��wxYw)Nz
 returned � and z could not serialize it)�makeResponserr%r3)rk�originalFailure�	aCallablerr�s  ���rm�makeResponseForzLCommandLocator._wrapWithSerialization.<locals>.doit.<locals>.makeResponseFor�sM���	�"�/�/���>�>��$��&-�i�O�(�$�g�w�8�'����s��)>)�parseArgumentsrr=r%)rzr�rorurtrr�s    ���rm�doitz3CommandLocator._wrapWithSerialization.<locals>.doit|sH����'�'��T�2�B�
�

��i�.�2�.���_�-���,�-�
rprg)r�rtrrws``` rm�_wrapWithSerializationz%CommandLocator._wrapWithSerializationls��� 	�:�rpc���|jjtjk7rtj||�St	j
dtd��|j|�S)zJ
        Deprecated synonym for L{CommandLocator.locateResponder}
        z)Call locateResponder, not lookupFunction.rOrP)r�rVr:r�rSrTrUrWs  rmrVzCommandLocator.lookupFunction�sW���>�>�(�(�N�,I�,I�I�!�1�1�$��=�=��M�M�;�2��
�
�#�#�D�)�)rpc�p�|j}||vr&||\}}t||�}|j||�Sy)a�
        Locate a callable to invoke when executing the named command.

        @param name: the normalized name (from the wire) of the command.
        @type name: C{bytes}

        @return: a 1-argument function that takes a Box and returns a box or a
        Deferred which fires a Box, for handling the command identified by the
        given name, or None, if no appropriate responder can be found.
        N)rMrrx)r�rirbrfrg�responderMethods      rmr�zCommandLocator.locateResponder�sH���
"�
"���2�:�*,�T�(�'�L�-�(���=�O��.�.���M�M�rpN)rsrtrurvrxrVr�rgrprmr:r:es���
-�^*�Nrpr:)�	metaclassc��eZdZdZdZd�Zy)rUz^
    Implement the L{AMP.locateResponder} method to do simple, string-based
    dispatch.
    samp_c�h�t|j|j�z�}t||d�S)a�
        Locate a callable to invoke when executing the named command.

        @return: a function with the name C{"amp_" + name} on the same
            instance, or None if no such function exists.
            This function will then be called with the L{AmpBox} itself as an
            argument.

        @param name: the normalized name (from the wire) of the command.
        @type name: C{bytes}
        N)r$�baseDispatchPrefix�upperr\)r�ri�fNames   rmr�z#SimpleStringLocator.locateResponder�s.���T�4�4�t�z�z�|�C�D���t�U�D�)�)rpN)rsrtrurvrr�rgrprmrUrU�s���
!��
*rprU)�and�del�for�is�raise�assert�elif�from�lambdar��break�else�global�not�try�class�except�if�or�while�continue�exec�import�pass�yield�def�finally�in�printc�l�t|jdd��}|tvr|j�S|S)a|
    (Private) Normalize an argument name from the wire for use with Python
    code.  If the return value is going to be a python keyword it will be
    capitalized.  If it contains any dashes they will be replaced with
    underscores.

    The rationale behind this method is that AMP should be an inherently
    multi-language protocol, so message keys may contain all manner of bizarre
    bytes.  This is not a complete solution; there are still forms of arguments
    that this implementation will be unable to parse.  However, Python
    identifiers share a huge raft of properties with identifiers from many
    other languages, so this is a 'good enough' effort for now.  We deal
    explicitly with dashes because that is the most likely departure: Lisps
    commonly use dashes to separate method names, so protocols initially
    implemented in a lisp amp dialect may use dashes in argument or command
    names.

    @param key: a C{bytes}, looking something like 'foo-bar-baz' or 'from'
    @type key: C{bytes}

    @return: a native string which is a valid python identifier, looking
    something like 'foo_bar_baz' or 'From'.
    �-�_)r$r+rO�title)r��lkeys  rm�_wireNameToPythonIdentifierr��s2��0����D�$�/�0�D�����z�z�|���Krpc�F�eZdZdZdZdd�Zd�Zd�Zd�Zd�Z	d�Z
d	�Zd
�Zy)
r2a�
    Base-class of all objects that take values from Amp packets and convert
    them into objects for Python functions.

    This implementation of L{IArgumentType} provides several higher-level
    hooks for subclasses to override.  See L{toString} and L{fromString}
    which will be used to define the behavior of L{IArgumentType.toBox} and
    L{IArgumentType.fromBox}, respectively.
    Fc��||_y)z�
        Create an Argument.

        @param optional: a boolean indicating whether this argument can be
        omitted in the protocol.
        N��optional)r�r�s  rmr�zArgument.__init__#s��!��
rpc�p�|jr|j|�}|�||=|S|j|�}|S)a/
        Retrieve the given key from the given dictionary, removing it if found.

        @param d: a dictionary.

        @param name: a key in I{d}.

        @param proto: an instance of an AMP.

        @raise KeyError: if I am not optional and no value was found.

        @return: d[name].
        )r��getr�)r��drirlr�s     rm�retrievezArgument.retrieve,s@���=�=��E�E�$�K�E�� ��d�G����E�E�$�K�E��rpc��|j|||�}t|�}|jr|�d||<y|j||�||<y)aG
        Populate an 'out' dictionary with mapping names to Python values
        decoded from an 'in' AmpBox mapping strings to string values.

        @param name: the argument name to retrieve
        @type name: C{bytes}

        @param strings: The AmpBox to read string(s) from, a mapping of
        argument names to string values.
        @type strings: AmpBox

        @param objects: The dictionary to write object(s) to, a mapping of
        names to Python objects. Keys will be native strings.
        @type objects: dict

        @param proto: an AMP instance.
        N)r�r�r��fromStringProto)r�rirjrkrl�st�nks       rmrnzArgument.fromBoxBsJ��$�]�]�7�D�%�
0��
(��
.���=�=�R�Z��G�B�K��.�.�r�5�9�G�B�Krpc��|j|t|�|�}|jr|�y|j||�||<y)a]
        Populate an 'out' AmpBox with strings encoded from an 'in' dictionary
        mapping names to Python values.

        @param name: the argument name to retrieve
        @type name: C{bytes}

        @param strings: The AmpBox to write string(s) to, a mapping of
        argument names to string values.
        @type strings: AmpBox

        @param objects: The dictionary to read object(s) from, a mapping of
        names to Python objects. Keys should be native strings.

        @type objects: dict

        @param proto: the protocol we are converting for.
        @type proto: AMP
        N)r�r�r��
toStringProto)r�rirjrkrl�objs      rmrrzArgument.toBox[s@��(�m�m�G�%@��%F��N���=�=�S�[�� �.�.�s�E�:�G�D�Mrpc�$�|j|�S)z�
        Convert a string to a Python value.

        @param inString: the string to convert.
        @type inString: C{bytes}

        @param proto: the protocol we are converting for.
        @type proto: AMP

        @return: a Python object.
        )�
fromString�r��inStringrls   rmr�zArgument.fromStringProtovs�����x�(�(rpc�$�|j|�S)z�
        Convert a Python object to a string.

        @param inObject: the object to convert.

        @param proto: the protocol we are converting for.
        @type proto: AMP
        )�toString)r��inObjectrls   rmr�zArgument.toStringProto�s���}�}�X�&�&rpc��y)z�
        Convert a string to a Python object.  Subclasses must implement this.

        @param inString: the string to convert.
        @type inString: C{bytes}

        @return: the decoded value from C{inString}
        Nrg�r�r�s  rmr�zArgument.fromString�rorpc��y)a
        Convert a Python object into a string for passing over the network.

        @param inObject: an object of the type that this Argument is intended
        to deal with.

        @return: the wire encoding of inObject
        @rtype: C{bytes}
        Nrg�r�r�s  rmr�zArgument.toString�rorpN�F)
rsrtrurvr�r�r�rnrrr�r�r�r�rgrprmr2r2s6����H�!��,:�2;�6)�	'��	rpr2c��eZdZdZeZd�Zy)rFz�
    Encode any integer values of any size on the wire as the string
    representation.

    Example: C{123} becomes C{"123"}
    c��d|fzS)Ns%drgr�s  rmr�zInteger.toString�s����{�"�"rpN)rsrtrurv�intr�r�rgrprmrFrF�s����J�#rprFc��eZdZdZd�Zd�Zy)rWzB
    Don't do any conversion at all; just pass through 'str'.
    c��|Sr�rgr�s  rmr�zString.toString�����rpc��|Sr�rgr�s  rmr�zString.fromString�r�rpN�rsrtrurvr�r�rgrprmrWrW�s����rprWc��eZdZdZeZd�Zy)r@zA
    Encode floating-point values on the wire as their repr.
    c�r�t|t�std|����t|�j	d�S)NzBad float value r�)r��float�
ValueErrorr�r�r�s  rmr�zFloat.toString�s4���(�E�*��/��|�<�=�=��8�}�#�#�G�,�,rpN)rsrtrurvr�r�r�rgrprmr@r@�s����J�-rpr@c��eZdZdZd�Zd�Zy)r5z@
    Encode True or False as "True" or "False" on the wire.
    c�6�|dk(ry|dk(rytd|����)N�TrueT�FalseFzBad boolean value: )r�r�s  rmr�zBoolean.fromString�s+���w���
��
!���1�(��>�?�?rpc�
�|ryy)Nr�r�rgr�s  rmr�zBoolean.toString�s����rpN�rsrtrurvr�r�rgrprmr5r5�s���@�rpr5c��eZdZdZd�Zd�Zy)r]z7
    Encode a unicode string on the wire as UTF-8.
    c�L�tj||jd��S�Nr*)rWr�r�r�s  rmr�zUnicode.toString�s�����t�X�_�_�W�%=�>�>rpc�L�tj||�jd�Sr�)rWr�r,r�s  rmr�zUnicode.fromString�s ��� � ��x�0�7�7��@�@rpNr�rgrprmr]r]�s���?�Arpr]c��eZdZdZd�Zd�Zy)rPaY
    Encode and decode L{filepath.FilePath} instances as paths on the wire.

    This is really intended for use with subprocess communication tools:
    exchanging pathnames on different machines over a network is not generally
    meaningful, but neither is it disallowed; you can use this to communicate
    about NFS paths, for example.
    c�T�tjtj||��Sr�)r �FilePathr]r�r�s  rmr�zPath.fromString�s ��� � ��!3�!3�D�(�!C�D�Drpc�^�tj||j�j�Sr�)r]r��
asTextMode�pathr�s  rmr�z
Path.toString�s$������h�&9�&9�&;�&@�&@�A�ArpNr�rgrprmrPrP�s���E�BrprPc�$�eZdZdZdd�Zd�Zd�Zy)rHa�
    Encode and decode lists of instances of a single other argument type.

    For example, if you want to pass::

        [3, 7, 9, 15]

    You can create an argument like this::

        ListOf(Integer())

    The serialized form of the entire list is subject to the limit imposed by
    L{MAX_VALUE_LENGTH}.  List elements are represented as 16-bit length
    prefixed strings.  The argument type passed to the L{ListOf} initializer is
    responsible for producing the serialized form of each element.

    @ivar elementType: The L{Argument} instance used to encode and decode list
        elements (note, not an arbitrary L{IArgumentType} implementation:
        arguments must be implemented using only the C{fromString} and
        C{toString} methods, not the C{fromBox} and C{toBox} methods).

    @param optional: a boolean indicating whether this argument can be
        omitted in the protocol.

    @since: 10.0
    c�>�||_tj||�yr�)�elementTyper2r�)r�r�r�s   rmr�zListOf.__init__s��&������$��)rpc��g}t�}|j|_|j|�|jj
}|D�cgc]
}||���c}Scc}w)zn
        Convert the serialized form of a list of instances of some type back
        into that list.
        )rr��stringReceived�dataReceivedr�r�)r�r�rj�parser�elementFromString�strings      rmr�zListOf.fromStringsW��
��$�&�� '��������H�%� �,�,�7�7��8?�@�f�!�&�)�@�@��@s�	Ac	���g}|D]R}|jj|�}|jtdt	|���|j|��Tdj|�S)zI
        Serialize the given list of objects to a single string.
        r�rp)r�r�r�rr�r�)r�r�rjr��
serializeds     rmr�zListOf.toString)sb�����	'�C��)�)�2�2�3�7�J��N�N�4��c�*�o�6�7��N�N�:�&�	'��x�x�� � rpNr�)rsrtrurvr�r�r�rgrprmrHrH�s���6*�
A�	!rprHc�$�eZdZdZdd�Zd�Zd�Zy)r1aI
    Convert a list of dictionaries into a list of AMP boxes on the wire.

    For example, if you want to pass::

        [{'a': 7, 'b': u'hello'}, {'a': 9, 'b': u'goodbye'}]

    You might use an AmpList like this in your arguments or response list::

        AmpList([('a', Integer()),
                 ('b', Unicode())])
    c�v�td�|D��s
Jd|����||_tj||�y)ag
        Create an AmpList.

        @param subargs: a list of 2-tuples of ('name', argument) describing the
        schema of the dictionaries in the sequence of amp boxes.
        @type subargs: A C{list} of (C{bytes}, L{Argument}) tuples.

        @param optional: a boolean indicating whether this argument can be
        omitted in the protocol.
        c3�BK�|]\}}t|t����y�wr�)r�r�)r�ri�_s   rmr�z#AmpList.__init__.<locals>.<genexpr>Ns����B�w�t�Q�:�d�E�*�B�s�zeAmpList should be defined with a list of (name, argument) tuples where `name' is a byte string, got: N)�all�subargsr2r�)r�r�r�s   rmr�zAmpList.__init__CsA���B�'�B�B�	
�?F�
I�	
�B�������$��)rpc�n�t|�}|D�cgc]}t||j|���}}|Scc}wr�)r`�_stringsToObjectsr�)r�r�rl�boxesrz�valuess      rmr�zAmpList.fromStringProtoUs8���H�%��IN�O�#�#�C����u�=�O��O��
��Ps�2c��dj|D�cgc]0}t||jt�|�j	���2c}�Scc}w)Nrp)r��_objectsToStringsr�r6r�)r�r�rlrks    rmr�zAmpList.toStringProtoZsJ���x�x� (�
��"�'�4�<�<����F�P�P�R�
�
�	
��
s�5ANr�)rsrtrurvr�r�r�rgrprmr1r15s���*�$�

rpr1c��eZdZdZd�Zd�Zy)r<aO
    Encode and decode file descriptors for exchange over a UNIX domain socket.

    This argument type requires an AMP connection set up over an
    L{IUNIXTransport<twisted.internet.interfaces.IUNIXTransport>} provider (for
    example, the kind of connection created by
    L{IReactorUNIX.connectUNIX<twisted.internet.interfaces.IReactorUNIX.connectUNIX>}
    and L{UNIXClientEndpoint<twisted.internet.endpoints.UNIXClientEndpoint>}).

    There is no correspondence between the integer value of the file descriptor
    on the sending and receiving sides, therefore an alternate approach is taken
    to matching up received descriptors with particular L{Descriptor}
    parameters.  The argument is encoded to an ordinal (unique per connection)
    for inclusion in the AMP command or response box.  The descriptor itself is
    sent using
    L{IUNIXTransport.sendFileDescriptor<twisted.internet.interfaces.IUNIXTransport.sendFileDescriptor>}.
    The receiver uses the order in which file descriptors are received and the
    ordinal value to come up with the received copy of the descriptor.
    c�6�|jt|��S)a�
        Take a unique identifier associated with a file descriptor which must
        have been received by now and use it to look up that descriptor in a
        dictionary where they are kept.

        @param inString: The base representation (as a byte string) of an
            ordinal indicating which file descriptor corresponds to this usage
            of this argument.
        @type inString: C{str}

        @param proto: The protocol used to receive this descriptor.  This
            protocol must be connected via a transport providing
            L{IUNIXTransport<twisted.internet.interfaces.IUNIXTransport>}.
        @type proto: L{BinaryBoxProtocol}

        @return: The file descriptor represented by C{inString}.
        @rtype: C{int}
        )�_getDescriptorr�r�s   rmr�zDescriptor.fromStringProtoxs��&�#�#�C��M�2�2rpc�V�|j|�}tj|||�}|S)a�
        Send C{inObject}, an integer file descriptor, over C{proto}'s connection
        and return a unique identifier which will allow the receiver to
        associate the file descriptor with this argument.

        @param inObject: A file descriptor to duplicate over an AMP connection
            as the value for this argument.
        @type inObject: C{int}

        @param proto: The protocol which will be used to send this descriptor.
            This protocol must be connected via a transport providing
            L{IUNIXTransport<twisted.internet.interfaces.IUNIXTransport>}.

        @return: A byte string which can be used by the receiver to reconstruct
            the file descriptor.
        @rtype: C{bytes}
        )�_sendFileDescriptorrFr�)r�r�rl�
identifier�	outStrings     rmr�zDescriptor.toStringProto�s.��$�.�.�x�8�
��)�)�$�
�E�B�	��rpN)rsrtrurvr�r�rgrprmr<r<cs���(3�*rpr<�_Selfc�,�eZdZdZ										dd�Zy)�_CommandMetazh
    Metaclass hack to establish reverse-mappings for 'errors' and
    'fatalErrors' as class vars.
    c�Z�ix}|d<ix}|d<d|vr|jd�|d<tj||||�}t|jt
�s$t
dj|j���|jD]#\}}t|t
�r�t
d|����|jD]#\}}t|t
�r�t
d|����i}	i}
t|d|	�t|d	|
�t|jt�st|j�|_t|jt�st|j�|_
|	j�D]\}}|||<|||<�|
j�D]\}}|||<|||<�|jj�D]#\}}t|t
�r�t
d
|����|jj�D]#\}}t|t
�r�t
d|����|S)N�
reverseErrorsrmr]r�z-Command names must be byte strings, got: {!r}z*Argument names must be byte strings, got: z*Response names must be byte strings, got: �errorsrnz'Error names must be byte strings, got: z-Fatal error names must be byte strings, got: )r�r�rXr�r]r�r�r��	arguments�responser&r�r�rnr�)
r^rir_r`r��er�newtype�bnamer�r�rnr�r�s
             rmrXz_CommandMeta.__new__�sH��24�3�
��o�.�"$�$��U�;�
���%�#'�;�;�w�#7�E�-� �!%���c�4���!F���'�-�-�u�5��?�F�F��'�'���
�
 �)�)�	X�H�E�1��e�U�+��"L�U�I� V�W�W�	X� �(�(�	X�H�E�1��e�U�+��"L�U�I� V�W�W�	X�02��46���G�X�v�6��G�]�K�@��'�.�.�$�/�!�'�.�.�1�G�N��'�-�-�t�4�"&�w�':�':�";�G���L�L�N�	�D�A�q� �M�!���B�q�E�	� �%�%�'�	�D�A�q� �M�!���B�q�E�	� ���,�,�.�	U�H�A�u��e�U�+��"I�%�� S�T�T�	U� �+�+�1�1�3�	�H�A�u��e�U�+��C�E�9�M���	��rpN)
r^ztype[_Self]rir�r_ztuple[type]r`zdict[str, object]r�z
Type[Command])rsrtrurvrXrgrprmr�r��s4���
0�
�0� #�0�,7�0�@Q�0�	�0rpr�c���eZdZUdZded<gZded<gZded<gZded<iZd	ed
<iZ	d	ed<e
Zded
<e
Zded<dZ
d�Zed��Zed��Zed��Zed��Zedd��Zd�Zy)r9a�
    Subclass me to specify an AMP Command.

    @cvar arguments: A list of 2-tuples of (name, Argument-subclass-instance),
    specifying the names and values of the parameters which are required for
    this command.

    @cvar response: A list like L{arguments}, but instead used for the return
    value.

    @cvar errors: A mapping of subclasses of L{Exception} to wire-protocol tags
        for errors represented as L{str}s.  Responders which raise keys from
        this dictionary will have the error translated to the corresponding tag
        on the wire.
        Invokers which receive Deferreds from invoking this command with
        L{BoxDispatcher.callRemote} will potentially receive Failures with keys
        from this mapping as their value.
        This mapping is inherited; if you declare a command which handles
        C{FooError} as 'FOO_ERROR', then subclass it and specify C{BarError} as
        'BAR_ERROR', responders to the subclass may raise either C{FooError} or
        C{BarError}, and invokers must be able to deal with either of those
        exceptions.

    @cvar fatalErrors: like 'errors', but errors in this list will always
    terminate the connection, despite being of a recognizable error type.

    @cvar commandType: The type of Box used to issue commands; useful only for
    protocol-modifying behavior like startTLS or protocol switching.  Defaults
    to a plain vanilla L{Box}.

    @cvar responseType: The type of Box used to respond to this command; only
    useful for protocol-modifying behavior like startTLS or protocol switching.
    Defaults to a plain vanilla L{Box}.

    @ivar requiresAnswer: a boolean; defaults to True.  Set it to False on your
    subclass if you want callRemote to return None.  Note: this is a hint only
    to the client side of the protocol.  The return-type of a command responder
    method must always be a dictionary adhering to the contract specified by
    L{response}, because clients are always free to request a response if they
    want one.
    zClassVar[bytes]r]z&ClassVar[List[Tuple[bytes, Argument]]]r�rzClassVar[List[Any]]�extraz&ClassVar[Dict[Type[Exception], bytes]]r�rnz+'ClassVar[Union[Type[Command], Type[Box]]]'rzClassVar[Type[AmpBox]]�responseTypeTc��||_g}|jD]=\}}t|�}||jvs� |jr�-|j	|��?|r4tdj
dj|�|j���g}y)a5
        Create an instance of this command with specified values for its
        parameters.

        In Python 3, keyword arguments MUST be Unicode/native strings whereas
        in Python 2 they could be either byte strings or Unicode strings.

        A L{Command}'s arguments are defined in its schema using C{bytes}
        names. The values for those arguments are plucked from the keyword
        arguments using the name returned from L{_wireNameToPythonIdentifier}.
        In other words, keyword arguments should be named using the
        Python-side equivalent of the on-wire (C{bytes}) name.

        @param kw: a dict containing an appropriate value for each name
        specified in the L{arguments} attribute of my class.

        @raise InvalidSignature: if you forgot any required arguments.
        zforgot {} for {}z, N)	�
structuredr�r�r�r�rGr�r�r])r�r��	forgottenri�arg�
pythonNames      rmr�zCommand.__init__s���&����	����	-�I�D�#�4�T�:�J�����0����� � ��,�	-��"�"�)�)�$�)�)�I�*>��@P�@P�Q��
��	rpc��	|j�}t||j||�S#t$r
t�cYSwxYw)a`
        Serialize a mapping of arguments using this L{Command}'s
        response schema.

        @param objects: a dict with keys matching the names specified in
        self.response, having values of the types that the Argument objects in
        self.response can format.

        @param proto: an L{AMP}.

        @return: an L{AmpBox}.
        )rrrr�r)r^rkrlrs    rmrrzCommand.makeResponse6sD��	��+�+�-�L�!��#�,�,��e�L�L���	��6�M�	�s�*�A�Ac���t�}|jD]\}}|jt|���!|D]}||vs�t	|�d���t||j|j
�|�S)a�
        Serialize a mapping of arguments using this L{Command}'s
        argument schema.

        @param objects: a dict with keys similar to the names specified in
        self.arguments, having values of the types that the Argument objects in
        self.arguments can parse.

        @param proto: an L{AMP}.

        @return: An instance of this L{Command}'s C{commandType}.
        z is not a valid argument)�setr��addr�rGr�r)r^rkrl�allowedNames�argName�ignored�intendedArgs       rm�
makeArgumentszCommand.makeArgumentsJs����u�� #�
�
�	C��G�W����8��A�B�	C�#�	Q�K��,�.�&�+��6N�'O�P�P�	Q�!��#�-�-����9J�E�R�Rrpc�0�t||j|�S)aZ
        Parse a mapping of serialized arguments using this
        L{Command}'s response schema.

        @param box: A mapping of response-argument names to the
        serialized forms of those arguments.
        @param protocol: The L{AMP} protocol.

        @return: A mapping of response-argument names to the parsed
        forms.
        )r�r�r^rz�protocols   rm�
parseResponsezCommand.parseResponseas��!��c�l�l�H�=�=rpc�0�t||j|�S)a?
        Parse a mapping of serialized arguments using this
        L{Command}'s argument schema.

        @param box: A mapping of argument names to the seralized forms
        of those arguments.
        @param protocol: The L{AMP} protocol.

        @return: A mapping of argument names to the parsed forms.
        )r�r�rs   rmrvzCommand.parseArgumentsps��!��c�m�m�X�>�>rpc�H�tjj||f�|S)a
        Declare a method to be a responder for a particular command.

        This is a decorator.

        Use like so::

            class MyCommand(Command):
                arguments = [('a', ...), ('b', ...)]

            class MyProto(AMP):
                def myFunMethod(self, a, b):
                    ...
                MyCommand.responder(myFunMethod)

        Notes: Although decorator syntax is not used within Twisted, this
        function returns its argument and is therefore safe to use with
        decorator syntax.

        This is not thread safe.  Don't declare AMP subclasses in other
        threads.  Don't declare responders outside the scope of AMP subclasses;
        the behavior is undefined.

        @param methodfunc: A function which will later become a method, which
        has a keyword signature compatible with this command's L{arguments} list
        and returns a dictionary with a set of keys compatible with this
        command's L{response} list.

        @return: the methodfunc parameter.
        )r:rKr�)r^�
methodfuncs  rmrHzCommand.responder~s$��@	�,�,�3�3�S�*�4E�F��rpc����fd�}|j�j�j�j|��j�}�jr-|j�j|�|j|�|S)aL
        Encode and send this Command to the given protocol.

        @param proto: an AMP, representing the connection to send to.

        @return: a Deferred which will fire or error appropriately when the
        other side responds to the command (or error if the connection is lost
        before it is responded to).
        c����|jt�|j}�jj	|j
t�}t||j��Sr�)	rlrTr�r�r�r�r^r%r�)r6�rje�	errorTyper�s   �rm�
_massageErrorz)Command._doCommand.<locals>._massageError�sI����J�J�~�&��+�+�C��*�*�.�.�s�}�}�>P�Q�I��9�S�_�_�5�6�6rp)rr]rrrr=rr%)r�rlr r�s`   rmrzCommand._doCommand�sp���	7�
�!�!�������t����6����
�����
�M�M�$�,�,�e�4�
�L�L��'��rpN)rrar�ra)rsrtrurvr�r�rrr�rnr6rrrr��classmethodrrrrrvrHrrgrprmr9r9�s���(�T!� �8:�I�5�:�79�H�4�9�!#�E��#�57�F�2�7�:<�K�7�<�?B�K�<�B�+.�L�(�.��N��>�M��M�&�S��S�,�>��>��?��?�� �� �Frpr9c��eZdZdZd�Zd�Zy)�_NoCertificatea
    This is for peers which don't want to use a local certificate.  Used by
    AMP because AMP's internal language is all about certificates and this
    duck-types in the appropriate place; this API isn't really stable though,
    so it's not exposed anywhere public.

    For clients, it will use ephemeral DH keys, or whatever the default is for
    certificate-less clients in OpenSSL.  For servers, it will generate a
    temporary self-signed certificate with garbage values in the DN and use
    that.
    c��||_y)aT
        Create a _NoCertificate which either is or isn't for the client side of
        the connection.

        @param client: True if we are a client and should truly have no
        certificate and be anonymous, False if we are a server and actually
        have to generate a temporary certificate.

        @type client: bool
        N)�client)r�r%s  rmr�z_NoCertificate.__init__�s����rpc
��|jsftd��}tj�}|j	|�}|j||d�d�}|j
|�}|j|�St�}|r5|jtdd|D�cgc]}|j��c}���tdi|��}	|	Scc}w)zT
        Behaves like L{twisted.internet.ssl.PrivateCertificate.options}().
        zTEMPORARY CERTIFICATE)�CNc��y�NTrg)�dns rm�<lambda>z(_NoCertificate.options.<locals>.<lambda>�rorprT)�verify�requireCertificate�caCertsrg)r%r(r+�generate�certificateRequest�signCertificateRequest�newCertificate�optionsr�r��originalr*)
r��authorities�sharedDNr��cr�sscrd�certr3�auth�occos
          rmr3z_NoCertificate.options�s����{�{��4�5�H��"�"�$�C��'�'��1�B��.�.�x��_�a�P�E��%�%�e�,�D��4�<�<��-�-��&����N�N���'+�7B�C�t�T�]�]�C��
�"�,�G�,�����	Ds�CN)rsrtrurvr�r3rgrprmr#r#�s��
��rpr#c�L�eZdZUdZgZded<d�Zed��Zed��Z	d�Z
y)	�_TLSBoxzK
    I am an AmpBox that, upon being sent, initiates a TLS connection.
    r�r�c�R�t�tdd��tj|�y)Ns	TLS_ERRORzTLS not available)r'rTr/r�r�s rmr�z_TLSBox.__init__�s!���;� ��/B�C�C�����rpc�8�|jdtd��S)N�tls_localCertificateF)r�r#r�s rm�certificatez_TLSBox.certificates���x�x�/���1F�G�Grpc�&�|jdd�S)N�tls_verifyAuthorities)r�r�s rmr,z_TLSBox.verifys���x�x�0�$�7�7rpc��t|�}dD]}|j|d��|j|�|j|j|j
�y)zK
        Send my encoded value to the protocol, then initiate TLS.
        )r@rCN)r/r�r��	_startTLSrAr,)r�rl�abr�s    rmr�z_TLSBox._sendTosM���D�\��D�	�A��F�F�1�d�O�	�
�
�
�5��
����(�(�$�+�+�6rpN)rsrtrurvr�r�r��propertyrAr,r�rgrprmr=r=�sG����I�y���
�H��H��8��8�7rpr=c��eZdZdZd�Zy)�_LocalArgumentz�
    Local arguments are never actually relayed across the wire.  This is just a
    shim so that StartTLS can pretend to have some arguments: if arguments
    acquire documentation properties, replace this with something nicer later.
    c��yr�rg)r�rirjrkrls     rmrnz_LocalArgument.fromBoxs��rpN)rsrtrurvrnrgrprmrIrIs���
rprIc��eZdZdZded��fded��fgZded��fded��fgZeZddd�d�Z	d	�Z
y)
rVaz
    Use, or subclass, me to implement a command that starts TLS.

    Callers of StartTLS may pass several special arguments, which affect the
    TLS negotiation:

        - tls_localCertificate: This is a
        twisted.internet.ssl.PrivateCertificate which will be used to secure
        the side of the connection it is returned on.

        - tls_verifyAuthorities: This is a list of
        twisted.internet.ssl.Certificate objects that will be used as the
        certificate authorities to verify our peer's certificate.

    Each of those special parameters may also be present as a key in the
    response dictionary.
    r@Tr�rCN)�tls_localCertificate�tls_verifyAuthoritiesc��t�td��|�td�n||_||_tj|fi|��y)a�
        Create a StartTLS command.  (This is private.  Use AMP.callRemote.)

        @param tls_localCertificate: the PrivateCertificate object to use to
        secure the connection.  If it's L{None}, or unspecified, an ephemeral DH
        key is used instead.

        @param tls_verifyAuthorities: a list of Certificate objects which
        represent root certificates to verify our peer with.
        NzTLS not available.T)r'�RuntimeErrorr#rAr5r9r�)r�rLrMr�s    rmr�zStartTLS.__init__AsO���;��3�4�4�$�+�
�4� �%�	
��
1�������$��$rpc����tj���}�j�j�j���fd�}|j|�|S)z�
        When a StartTLS command is sent, prepare to start TLS, but don't actually
        do it; wait for the acknowledgement, then initiate the TLS handshake.
        c�T���j�j�j�|Sr�)rErAr5)rrlr�s ��rm�
actuallystartz*StartTLS._doCommand.<locals>.actuallystart_s"����O�O�D�,�,�d�.>�.>�?��Orp)r9r�_prepareTLSrAr5r=)r�rlr�rRs``  rmrzStartTLS._doCommandVsK���

���t�U�+��
���$�*�*�D�,<�,<�=�	�	
�
�
�m�$��rp)rsrtrurvrIr�rr=rr�rrgrprmrVrV"sc���&
!�.�$�"?�@�	!�>�4�#@�A��I�
!�.�$�"?�@�	!�>�4�#@�A��H�
�L�/3�4�%�*rprVc�<��eZdZdZ�fd�Zed��Z�fd�Z�xZS)rQa�
    Use this command to switch from something Amp-derived to a different
    protocol mid-connection.  This can be useful to use amp as the
    connection-startup negotiation phase.  Since TLS is a different layer
    entirely, you can use Amp to negotiate the security parameters of your
    connection, then switch to a different protocol, and the connection will
    remain secured.
    c�2��||_t�|�di|��y)a
        Create a ProtocolSwitchCommand.

        @param _protoToSwitchToFactory: a ProtocolFactory which will generate
        the Protocol to switch to.

        @param kw: Keyword arguments, encoded and handled normally as
        L{Command} would.
        Nrg)�protoToSwitchToFactoryr�r�)r��_protoToSwitchToFactoryr�r�s   �rmr�zProtocolSwitchCommand.__init__qs���'>��#�
����2�rpc��t|�Sr�)r�)r^r�rls   rmrrz"ProtocolSwitchCommand.makeResponses
���*�%�%rpc�����t�����}�j���fd�}��fd�}|j||�S)z�
        When we emit a ProtocolSwitchCommand, lock the protocol, but don't actually
        switch to the new protocol unless an acknowledgement is received.  If
        an error is received, switch back.
        c����jj�jj��}�j	|�j�|Sr�)rV�
buildProtocolr��getPeerr)�ignr�rlr�s  ��rm�	switchNowz3ProtocolSwitchCommand._doCommand.<locals>.switchNow�sD����4�4�B�B����'�'�)��J�
�O�O�J��(C�(C�D��Jrpc�z���j��jjdtt��|Sr�)�_unlockFromSwitchrV�clientConnectionFailedr%r)r]rlr�s ��rm�handlez0ProtocolSwitchCommand._doCommand.<locals>.handle�s4����#�#�%��'�'�>�>��g�o�.�
��Jrp)r�rrr<)r�rlr�r^rbr�s``   �rmrz ProtocolSwitchCommand._doCommand�s=���
�G��u�%��
����	�	��~�~�i��0�0rp)	rsrtrurvr�r!rrrr�r�s@rmrQrQgs+������&��&�1�1rprQc�"�eZdZdZd�Zd�Zd�Zy)�_DescriptorExchangera
    L{_DescriptorExchanger} is a mixin for L{BinaryBoxProtocol} which adds
    support for receiving file descriptors, a feature offered by
    L{IUNIXTransport<twisted.internet.interfaces.IUNIXTransport>}.

    @ivar _descriptors: Temporary storage for all file descriptors received.
        Values in this dictionary are the file descriptors (as integers).  Keys
        in this dictionary are ordinals giving the order in which each
        descriptor was received.  The ordering information is used to allow
        L{Descriptor} to determine which is the correct descriptor for any
        particular usage of that argument type.
    @type _descriptors: C{dict}

    @ivar _sendingDescriptorCounter: A no-argument callable which returns the
        ordinals, starting from 0.  This is used to construct values for
        C{_sendFileDescriptor}.

    @ivar _receivingDescriptorCounter: A no-argument callable which returns the
        ordinals, starting from 0.  This is used to construct values for
        C{fileDescriptorReceived}.
    c��i|_|jj|_ttt��|_ttt��|_yr�)�_descriptorsr�r�r�nextr�_sendingDescriptorCounter�_receivingDescriptorCounterr�s rmr�z_DescriptorExchanger.__init__�s@�����"�/�/�3�3���)0��u�w�)?��&�+2�4���+A��(rpc�X�|jj|�|j�S)z�
        Assign and return the next ordinal to the given descriptor after sending
        the descriptor over this protocol's transport.
        )r��sendFileDescriptorrh�r��
descriptors  rmr�z(_DescriptorExchanger._sendFileDescriptor�s%��
	
���)�)�*�5��-�-�/�/rpc�>�||j|j�<y)z�
        Collect received file descriptors to be claimed later by L{Descriptor}.

        @param descriptor: The received file descriptor.
        @type descriptor: C{int}
        N)rfrirls  rm�fileDescriptorReceivedz+_DescriptorExchanger.fileDescriptorReceived�s��AK����$�:�:�<�=rpN)rsrtrurvr�r�rorgrprmrdrd�s���,B�0�Krprdc���eZdZUdZdZdZdZdZdZdZ	dZ
dZdZde
d<dZd�Zdd�Zd�Zd	�Zd
�Zd�ZdZd
ZeZd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Ze d��Z!d�Z"d�Z#e$jKe#�y)r4a�
    A protocol for receiving L{AmpBox}es - key/value pairs - via length-prefixed
    strings.  A box is composed of:

        - any number of key-value pairs, described by:
            - a 2-byte network-endian packed key length (of which the first
              byte must be null, and the second must be non-null: i.e. the
              value of the length must be 1-255)
            - a key, comprised of that many bytes
            - a 2-byte network-endian unsigned value length (up to the maximum
              of 65535)
            - a value, comprised of that many bytes
        - 2 null bytes

    In other words, an even number of strings prefixed with packed unsigned
    16-bit integers, and then a 0-length string to indicate the end of the box.

    This protocol also implements 2 extra private bits of functionality related
    to the byte boundaries between messages; it can start TLS between two given
    boxes or switch to an entirely different protocol.  However, due to some
    tricky elements of the implementation, the public interface to this
    functionality is L{ProtocolSwitchCommand} and L{StartTLS}.

    @ivar _keyLengthLimitExceeded: A flag which is only true when the
        connection is being closed because a key length prefix which was longer
        than allowed by the protocol was received.

    @ivar boxReceiver: an L{IBoxReceiver} provider, whose
        L{IBoxReceiver.ampBoxReceived} method will be invoked for each
        L{AmpBox} that is received.
    FNzOptional[Protocol]�
innerProtocolc�<�tj|�||_yr�)rdr��boxReceiver)r�rss  rmr�zBinaryBoxProtocol.__init__�s���%�%�d�+�&��rpc��|j}d|_||_||_|j|j�|r|j|�yy)a�
        Switch this BinaryBoxProtocol's transport to a new protocol.  You need
        to do this 'simultaneously' on both ends of a connection; the easiest
        way to do this is to use a subclass of ProtocolSwitchCommand.

        @param newProto: the new protocol instance to switch to.

        @param clientFactory: the ClientFactory to send the
            L{twisted.internet.protocol.ClientFactory.clientConnectionLost}
            notification to.
        r�N)�recvdrq�innerProtocolClientFactory�makeConnectionr�r�)r��newProto�
clientFactory�newProtoDatas    rmrzBinaryBoxProtocol._switchTo	sP���z�z��
��
�&���*7��'�������/���!�!�,�/�rpc��|jrtd��|j�
t��|j�|jj|�y|jj
|j��y)a/
        Send a amp.Box to my peer.

        Note: transport.write is never called outside of this method.

        @param box: an AmpBox.

        @raise ProtocolSwitched: if the protocol has previously been switched.

        @raise ConnectionLost: if the connection has previously been lost.
        z5This connection has switched: no AMP traffic allowed.N)�_lockedrRr�r�_startingTLSBufferr��writer�rBs  rmr{zBinaryBoxProtocol.sendBox	sh���<�<�"�G��
��>�>�!� �"�"��"�"�.��#�#�*�*�3�/��N�N� � �����1rpc�h�||_|jj|�|j�y)z�
        Notify L{boxReceiver} that it is about to receive boxes from this
        protocol by invoking L{IBoxReceiver.startReceivingBoxes}.
        N)r�rsr��connectionMade�r�r�s  rmrwz BinaryBoxProtocol.makeConnection6	s+��
#������,�,�T�2����rpc��|jrd|_|j�|jj|�ytj||�S)zg
        Either parse incoming data as L{AmpBox}es or relay it to our nested
        protocol.
        FN)�_justStartedTLSrqr�r)r��datas  rmr�zBinaryBoxProtocol.dataReceived?	sM��
���#(�D� ����)����+�+�D�1��"�/�/��d�;�;rpc�~�|j�C|jj|�|j�|jjd|�|jrtt
dddd��}n/|jt�r|jrtd�}n|}|jj|�y)zF
        The connection was lost; notify any nested protocol.
        NTFz4Peer rejected our certificate for an unknown reason.)
rq�connectionLostrv�clientConnectionLost�_keyLengthLimitExceededr%rXr4rr�rrsr�)r�r��
failReasons   rmr�z BinaryBoxProtocol.connectionLostM	s������)����-�-�f�5��.�.�:��/�/�D�D�T�6�R��'�'� ���u�d�D�!A�B�J�
�\�\�*�
+��0D�0D�
)�F��J� �J����+�+�J�7rprcrdc�B�t�|_|j|�S)z6
        String received in the 'init' state.
        )r/�_currentBox�	proto_key�r�r�s  rm�
proto_initzBinaryBoxProtocol.proto_initm	s��"�8����~�~�f�%�%rpc��|r||_|j|_y|jj	|j
�d|_y)zu
        String received in the 'key' state.  If the key is empty, a complete
        box has been received.
        r�N�init)�_currentKey�_MAX_VALUE_LENGTH�
MAX_LENGTHrsr�r�r�s  rmr�zBinaryBoxProtocol.proto_keyt	sD��
�%�D��"�4�4�D�O�����+�+�D�,<�,<�=�#�D��rpc�f�||j|j<d|_|j|_y)z7
        String received in the 'value' state.
        Nr�)r�r��_MAX_KEY_LENGTHr�r�s  rm�proto_valuezBinaryBoxProtocol.proto_value�	s2��.4�����)�)�*�����.�.���rpc�F�d|_|jj�y)z�
        The key length limit was exceeded.  Disconnect the transport and make
        sure a meaningful exception is reported.
        TN)r�r�r�)r��lengths  rm�lengthLimitExceededz%BinaryBoxProtocol.lengthLimitExceeded�	s��
(,��$����%�%�'rpc��d|_y)a
        Lock this binary protocol so that no further boxes may be sent.  This
        is used when sending a request to switch underlying protocols.  You
        probably want to subclass ProtocolSwitchCommand rather than calling
        this directly.
        TN)r|r�s rmrz BinaryBoxProtocol._lockForSwitch�	s����rpc�@�|j�td��d|_y)z�
        Unlock this locked binary protocol so that further boxes may be sent
        again.  This is used after an attempt to switch protocols has failed
        for some reason.
        Nz*Protocol already switched.  Cannot unlock.F)rqrRr|r�s rmr`z#BinaryBoxProtocol._unlockFromSwitch�	s#�����)�"�#O�P�P���rpc	�~�g|_|j�*td|j�d|j�d||f����y)z�
        Used by StartTLSCommand to put us into the state where we don't
        actually send things that get sent, instead we buffer them.  see
        L{_sendBoxCommand}.
        Nz,Previously authenticated connection between rqz is trying to re-establish as )r}�hostCertificaterM�peerCertificate)r�rA�verifyAuthoritiess   rmrSzBinaryBoxProtocol._prepareTLS�	sL��#%������+���(�(��(�(� �"3�4���
�,rpc���||_d|_|�d}|jj|j|��|j
}|� d|_|D]}|j
|��yy)a<
        Used by TLSBox to initiate the SSL handshake.

        @param certificate: a L{twisted.internet.ssl.PrivateCertificate} for
        use locally.

        @param verifyAuthorities: L{twisted.internet.ssl.Certificate} instances
        representing certificate authorities which will verify our peer.
        TNrg)r�r�r��startTLSr3r}r{)r�rAr��stlsbrzs     rmrEzBinaryBoxProtocol._startTLS�	sz�� +���#����$� "������� 3�� 3� 3�5F� G�H��'�'����&*�D�#��
"�����S�!�
"�rpc�Z�|jrytj|j�Sr�)�noPeerCertificater)�peerFromTransportr�r�s rmr�z!BinaryBoxProtocol.peerCertificate�	s#���!�!���,�,�T�^�^�<�<rpc�~�tj|d�|j�|jj�yy)zv
        The buck stops here.  This error was completely unhandled, time to
        terminate the connection.
        z�Amp server or network failure unhandled by client application.  Dropping connection!  To avoid, add errbacks to ALL remote commands!N)r!r5r�r�r#s  rmr~z BinaryBoxProtocol.unhandledError�	s9��
	����
�	
��>�>�%��N�N�)�)�+�&rpc��iS)aX
        The default TLS responder doesn't specify any certificate or anything.

        From a security perspective, it's little better than a plain-text
        connection - but it is still a *bit* better, so it's included for
        convenience.

        You probably want to override this by providing your own StartTLS.responder.
        rgr�s rm�_defaultStartTLSResponderz+BinaryBoxProtocol._defaultStartTLSResponder�	s	���	rpr�)&rsrtrurvr�r}r|r�r�r�r�r�rqr�rvr�rr{rwr�r�r�r�r�r�r�r�r�rr`rSrErGr�r~r�rVrHrgrprmr4r4�s����@�O����G��K��K�#���O���(,�M�%�,�!%��'�0�:2�.�<�8�.�O���!�J�&���(����$"�*�=��=�
,�
�
���0�1rpr4c�6�eZdZdZdZd	d�Zd�Zd
d�Zd�Zd�Z	y)r,za
    This protocol is an AMP connection.  See the module docstring for protocol
    details.
    FNc�z�d|_|�|}|�|}tj||�tj||�yr))�_ampInitializedr7r�r4)r�rsrs   rmr�zAMP.__init__�	sA�� $������K��?��G����t�W�-��"�"�4��5rpc�f�tj||�}|�|Stj||�}|S)z�
        Unify the implementations of L{CommandLocator} and
        L{SimpleStringLocator} to perform both kinds of dispatch, preferring
        L{CommandLocator}.

        @type name: C{bytes}
        )r:r�rU)r�ri�firstResponder�secondResponders    rmr�zAMP.locateResponder
s:��(�7�7��d�C���%�!�!�-�=�=�d�D�I���rpc��|j�d|j��}nd}d|jj�|�dt|�d�d�S)zo
        A verbose string representation which gives us information about this
        AMP connection.
        z inner r��<z at 0x�x�>)rqr�rs�id)r��	innerReprs  rmr�zAMP.__repr__
sR��
���)�!�$�"4�"4�!7�8�I��I��4�>�>�*�*�+�I�;�f�R��X�a�L��J�Jrpc�R�|jstj|�|j�|_|j�|_tj|jj�d|j�d|j�d��tj||�y)zI
        Emit a helpful log message when the connection is made.
        z connection established (HOST:� PEER:r�N)
r�r,r�r\�_transportPeer�getHost�_transportHostr!�msgr�rsr4rwr�s  rmrwzAMP.makeConnection 
s~���#�#�
�L�L���'�/�/�1���'�/�/�1�������~�~�&�&��(;�(;�T�=P�=P�
R�	
�	�(�(��y�9rpc���tj|jj�d|j�d|j
�d��tj||�d|_y)zI
        Emit a helpful log message when the connection is lost.
        z connection lost (HOST:r�r�N)	r!r�r�rsr�r�r4r�r�r
s  rmr�zAMP.connectionLost1
sL��	����~�~�&�&��(;�(;�T�=P�=P�
R�	
�	�(�(��v�6���rp)NNr�)
rsrtrurvr�r�r�r�rwr�rgrprmr,r,�	s(���
�O�
6��	K�:�"	rpr,c�R�eZdZdZd�Zd�Zd�ZdZd�Zd�Z	e
d��Ze
d	��Zy
)�
_ParserHelperz:
    A box receiver which records all boxes received.
    c��g|_yr�)r�r�s rmr�z_ParserHelper.__init__B
s	����
rpc��y�Nr�rgr�s rmr\z_ParserHelper.getPeerE
���rpc��yr�rgr�s rmr�z_ParserHelper.getHostH
r�rpFc��y)z0
        No initialization is required.
        Nrg)r��senders  rmr�z!_ParserHelper.startReceivingBoxesM
rorpc�:�|jj|�yr�)r�r�rBs  rmr�z_ParserHelper.ampBoxReceivedR
s���
�
���#�rpc��|�}t|��}|j|�|j|j��|jS)z�
        Parse some amp data stored in a file.

        @param fileObj: a file-like object.

        @return: a list of AmpBoxes encoded in the given file.
        )rs)r4rwr��readr�)r^�fileObj�parserHelper�bbps    rmr_z_ParserHelper.parseV
sC���u���L�9�����<�(��������(��!�!�!rpc�6�|jt|��S)z�
        Parse some amp data stored in a string.

        @param data: a str holding some amp-encoded data.

        @return: a list of AmpBoxes encoded in the given string.
        )r_r)r^r�s  rmr`z_ParserHelper.parseStringe
s���y�y����'�'rpN)
rsrtrurvr�r\r��
disconnectingr�r�r!r_r`rgrprmr�r�=
sO�������M��
��"��"��(��(rpr�c�f�i}|j�}|D]\}}|j||||��|S)a~
    Convert an AmpBox to a dictionary of python objects, converting through a
    given arglist.

    @param strings: an AmpBox (or dict of strings)

    @param arglist: a list of 2-tuples of strings and Argument objects, as
    described in L{Command.arguments}.

    @param proto: an L{AMP} instance.

    @return: the converted dictionary mapping names to argument objects.
    )r�rn)rj�arglistrlrk�	myStrings�argname�	argparsers       rmr�r�u
sA���G�����I�%�>�������'�9�g�u�=�>��Nrpc�b�|j�}|D]\}}|j||||��|S)a-
    Convert a dictionary of python objects to an AmpBox, converting through a
    given arglist.

    @param objects: a dict mapping names to python objects

    @param arglist: a list of 2-tuples of strings and Argument objects, as
    described in L{Command.arguments}.

    @param strings: [OUT PARAMETER] An object providing the L{dict}
    interface which will be populated with serialized data.

    @param proto: an L{AMP} instance.

    @return: The converted dictionary mapping names to encoded argument
    strings (identical to C{strings}).
    )r�rr)rkr�rjrl�	myObjectsr�r�s       rmr�r��
s:��$����I�%�<���������)�U�;�<��Nrpc��eZdZdZd�Zd�Zy)r;a�
    Encodes C{decimal.Decimal} instances.

    There are several ways in which a decimal value might be encoded.

    Special values are encoded as special strings::

      - Positive infinity is encoded as C{"Infinity"}
      - Negative infinity is encoded as C{"-Infinity"}
      - Quiet not-a-number is encoded as either C{"NaN"} or C{"-NaN"}
      - Signalling not-a-number is encoded as either C{"sNaN"} or C{"-sNaN"}

    Normal values are encoded using the base ten string representation, using
    engineering notation to indicate magnitude without precision, and "normal"
    digits to indicate precision.  For example::

      - C{"1"} represents the value I{1} with precision to one place.
      - C{"-1"} represents the value I{-1} with precision to one place.
      - C{"1.0"} represents the value I{1} with precision to two places.
      - C{"10"} represents the value I{10} with precision to two places.
      - C{"1E+2"} represents the value I{10} with precision to one place.
      - C{"1E-1"} represents the value I{0.1} with precision to one place.
      - C{"1.5E+2"} represents the value I{15} with precision to two places.

    U{http://speleotrove.com/decimal/} should be considered the authoritative
    specification for the format.
    c�B�t|�}tj|�Sr�)r$�decimalr;r�s  rmr�zDecimal.fromString�
s����)�����x�(�(rpc��t|tj�rt|�j	d�Std��)zW
        Serialize a C{decimal.Decimal} instance to the specified wire format.
        r�z8amp.Decimal can only encode instances of decimal.Decimal)r�r�r;r�r�r�r�s  rmr�zDecimal.toString�
s3���h����0��x�=�'�'��0�0��S�T�TrpNr�rgrprmr;r;�
s���8)�Urpr;c��eZdZdZedd�edd�edd�edd	�ed
d�edd
�edd�edd�edd�g	Zd�Zd�Zy)�DateTimeaO
    Encodes C{datetime.datetime} instances.

    Wire format: '%04i-%02i-%02iT%02i:%02i:%02i.%06i%s%02i:%02i'. Fields in
    order are: year, month, day, hour, minute, second, microsecond, timezone
    direction (+ or -), timezone hour, timezone minute. Encoded string is
    always exactly 32 characters long. This format is compatible with ISO 8601,
    but that does not mean all ISO 8601 dates can be accepted.

    Also, note that the datetime module's notion of a "timezone" can be
    complex, but the wire format includes only a fixed offset, so the
    conversion is not lossless. A lossless transmission of a C{datetime} instance
    is not feasible since the receiving end would require a Python interpreter.

    @ivar _positions: A sequence of slices giving the positions of various
        interesting parts of the wire format.
    r�����
��
���������� c��t|�}t|�dk7rtd|����|jD�cgc]}t	||���}}|d}tj|g|dd���}|g|ddtj|�Scc}w)z|
        Parse a string containing a date and time in the wire format into a
        C{datetime.datetime} instance.
        r�zinvalid date format r�r�N)r$r�r��
_positionsr��_FixedOffsetTZInfo�fromSignHoursMinutes�datetime)r��s�pr��sign�timezones      rmr�zDateTime.fromString�
s���

��O���q�6�R�<��3�A�5�9�:�:�%)�_�_�5��#�a��d�)�5��5���u��%�:�:�4�M�&���*�M���Z��q�r�
�� � �&�)�)��	6s�Bc
��|j�}|�td��|jdz|jzdz}|dkDrd}nd}d|j|j
|j|j|j|j|j|t|�dzt|�dzf
z}|jd�S)	zm
        Serialize a C{datetime.datetime} instance to a string in the specified
        wire format.
        zUamp.DateTime cannot serialize naive datetime instances.  You may find amp.utc useful.i�Q�<r�+�-z-%04i-%02i-%02iT%02i:%02i:%02i.%06i%s%02i:%02ir�)
�	utcoffsetr��days�seconds�year�month�day�hour�minute�second�microsecond�absr�)r�r��offset�
minutesOffsetr��packeds      rmr�zDateTime.toString�
s���
������>��/��
�
 ���u�,�v�~�~�=�"�D�
��1���D��D�A�
�F�F�
�G�G�
�E�E�
�F�F�
�H�H�
�H�H�
�M�M���
��"�$��
���#�D
�
���}�}�W�%�%rpN)rsrtrurv�slicer�r�r�rgrprmr�r��
sk���&	�a���
�a���
�a���
�b�"�
�
�b�"�
�
�b�"�
�
�b�"�
�
�b�"�
�
�b�"�
��J�*� %&rpr�)�rv�
__future__rr�r�rS�	functoolsr�ior�	itertoolsr�structr�typesr�typingr	r
rrr
rrrrr�zope.interfacerr�twisted.internet.deferrrr�twisted.internet.errorrrr�twisted.internet.interfacesr�twisted.internet.mainr�twisted.internet.protocolr�twisted.protocols.basicrr�twisted.pythonr r!�twisted.python._tzhelperr"r\r#r��twisted.python.compatr$�twisted.python.failurer%�twisted.python.reflectr&�twisted.internetr'�_ssl�	supported�twisted.internet.sslr(r)r*r+�ImportError�__all__�objectrar.r-r8r=r>r?rZrYrIrJrArCrBrD�	Exceptionr0rRrMrLrGrXr3rTr^rKr[rErNr�r/r6rSr�r7r�rJr:rUrOr�r2rFrWr@r5r]rPrHr1r<r�r�r9r#r=rIrVrQrdr4r,r�r_r`r�r�r;r�rgrprm�<module>r"s1��|�z#������������2�@�@�T�T�?�1�.�O�(��/�*�6�
�,��~�~�U�U����C�6��r�m�8�C��K�+@�A����	��
����
�
�)����#������=�I�=�@���2�9��6�	��*�y���y������8���x��B�h�B�@
�X�
� 1�X�1�h>��>��h���x���8��(�)9�:��[0�T�%��,�
�[0�@
��)�f�)�$)��)�D
�\��n-�n-��n-�b	)�$�)�X
�
��TN�2�TN� �TN�n
�
��*�*� �*�0��B�<
�]��L�L��L�^#�h�#�	�X�	�
-�H�
-��h��(	A�f�	A�B�7�B�"5!�X�5!�p+
�h�+
�\>��>�B	����6�4�6�r]��]�@5�5�p7�f�7�>
�V�
�B�w�B�J31�G�31�l
�
$�%�,K�,K�&�,K�^
�Z��_2��/�1E�_2��_2�D	J�
�]�N�<O�J�Z1(�1(�h	�����'�'���*�0(U�h�(U�VU&�x�U&��wN��
�C��s�$!M&�&M1�0M1

Zerion Mini Shell 1.0