Ë
    ojhC  ã                   ó0  — d Z ddlZddlZddlmZ ddlmZmZmZm	Z	m
Z
mZmZmZ ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZmZmZmZ ddlm Z  dZ!d„ Z"dZ#d„ Z$d„ Z%d„ Z& G d„ d«      Z'd„ Z( ee«       G d„ d«      «       Z) G d„ d«      Z*y)zD
Tools for automated testing of L{twisted.pair}-based applications.
é    N)Údeque)ÚEAGAINÚEBADFÚEINTRÚEINVALÚENOBUFSÚENOSYSÚEPERMÚEWOULDBLOCK©Úwraps)Úimplementer)ÚDatagramProtocol)ÚEthernetProtocol)Ú
IPProtocol)ÚRawUDPProtocol)Ú	_IFNAMSIZÚ
_TUNSETIFFÚTunnelFlagsÚ_IInputOutputSystem)ÚnativeStringé   c                 ó.   — t        j                  d| «      S )zê
    Pack an integer into a network-order two-byte string.

    @param n: The integer to pack.  Only values that fit into 16 bits are
        supported.

    @return: The packed representation of the integer.
    @rtype: L{bytes}
    z>H)ÚstructÚpack)Úns    ú6/usr/lib/python3/dist-packages/twisted/pair/testing.pyÚ_Hr      s   € ô �;‰;�t˜QÓÐó    é   c                 ó*   — || z   t        |«      z   |z   S )aØ  
    Construct an ethernet frame.

    @param src: The source ethernet address, encoded.
    @type src: L{bytes}

    @param dst: The destination ethernet address, encoded.
    @type dst: L{bytes}

    @param protocol: The protocol number of the payload of this datagram.
    @type protocol: L{int}

    @param payload: The content of the ethernet frame (such as an IP datagram).
    @type payload: L{bytes}

    @return: The full ethernet frame.
    @rtype: L{bytes}
    )r   ©ÚsrcÚdstÚprotocolÚpayloads       r   Ú	_ethernetr'   .   s   € ð& �‰9”r˜(“|Ñ# gÑ-Ð-r   c                 ó¼  — dt        dt        |«      z   «      z   dz   t        d«      z   t        j                  t        j                  t        | «      «      z   t        j                  t        j                  t        |«      «      z   }t        t        j                  d|«      «      }|dz	  }|dz  |z   }|dz  }|dd	 t        j                  d
|«      z   |dd z   }||z   S )aÌ  
    Construct an IP datagram with the given source, destination, and
    application payload.

    @param src: The source IPv4 address as a dotted-quad string.
    @type src: L{bytes}

    @param dst: The destination IPv4 address as a dotted-quad string.
    @type dst: L{bytes}

    @param payload: The content of the IP datagram (such as a UDP datagram).
    @type payload: L{bytes}

    @return: An IP datagram header and payload.
    @rtype: L{bytes}
    s   E é   s      @r   z!10Hé   iÿÿ  Né
   z!Hé   )
r   ÚlenÚsocketÚ	inet_ptonÚAF_INETr   Úsumr   Úunpackr   )r#   r$   r&   ÚipHeaderÚchecksumStep1ÚcarryÚchecksumStep2ÚchecksumStep3s           r   Ú_ipr8   D   sé   € ð&	ô ˆR”#�g“,ÑÓ
ñ		 ð
 &ñ	&ô ˆQ‹%ñ	ô ×
Ñ
œ6Ÿ>™>¬<¸Ó+<Ó
=ñ		>ô ×
Ñ
œ6Ÿ>™>¬<¸Ó+<Ó
=ñ	>ð ô" œŸ™ f¨hÓ7Ó8€Mà˜RÑ€Eà" VÑ+¨uÑ4€Mà! FÑ*€Mð
 ˜˜ˆ}œvŸ{™{¨4°Ó?Ñ?À(È2È3À-ÑO€Hà�gÑÐr   c                 ó‚   — t        | «      t        |«      z   t        t        |«      dz   «      z   t        d«      z   }||z   S )a~  
    Construct a UDP datagram with the given source, destination, and
    application payload.

    @param src: The source port number.
    @type src: L{int}

    @param dst: The destination port number.
    @type dst: L{int}

    @param payload: The content of the UDP datagram.
    @type payload: L{bytes}

    @return: A UDP datagram header and payload.
    @rtype: L{bytes}
    é   r   )r   r-   )r#   r$   r&   Ú	udpHeaders       r   Ú_udpr<   v   sO   € ô& 	ˆ3‹ä
ˆS‹'ñ	ô ŒS�‹\˜AÑÓ
ñ		ô ˆQ‹%ñ	ð ð �wÑÐr   c                   óŠ   — e Zd ZdZdZ eed«      Z ee	d«      Z
 eed«      ZeZdZd„ Zed„ «       Zed	„ «       Zd
„ Zd„ Zd„ Zy)ÚTunnelzè
    An in-memory implementation of a tun or tap device.

    @cvar _DEVICE_NAME: A string representing the conventional filesystem entry
        for the tunnel factory character special device.
    @type _DEVICE_NAME: C{bytes}
    s   /dev/net/tunz Resource temporarily unavailablezOperation would blockzInterrupted function calli   c                 ó¤   — || _         || _        d| _        d| _        d| _        t        «       | _        t        «       | _        t        «       | _        y)a  
        @param system: An L{_IInputOutputSystem} provider to use to perform I/O.

        @param openFlags: Any flags to apply when opening the tunnel device.
            See C{os.O_*}.

        @type openFlags: L{int}

        @param fileMode: ignored
        N)	ÚsystemÚ	openFlagsÚ
tunnelModeÚrequestedNameÚnamer   Ú
readBufferÚwriteBufferÚpendingSignals)Úselfr@   rA   ÚfileModes       r   Ú__init__zTunnel.__init__¬   sG   € ð ˆŒð #ˆŒØˆŒØ!ˆÔØˆŒ	Ü›'ˆŒÜ ›7ˆÔÜ#›gˆÕr   c                 óJ   — | j                   | j                  j                  z   S )zx
        If the file descriptor for this tunnel is open in blocking mode,
        C{True}.  C{False} otherwise.
        )rA   r@   Ú
O_NONBLOCK©rH   s    r   ÚblockingzTunnel.blockingÃ   s    € ð —N‘N T§[¡[×%;Ñ%;Ñ;Ð<Ð<r   c                 óZ   — t        | j                  | j                  j                  z  «      S )zz
        If the file descriptor for this tunnel is marked as close-on-exec,
        C{True}.  C{False} otherwise.
        )ÚboolrA   r@   Ú	O_CLOEXECrM   s    r   ÚcloseOnExeczTunnel.closeOnExecË   s"   € ô �D—N‘N T§[¡[×%:Ñ%:Ñ:Ó;Ð;r   c                 ó®   — | j                   t        j                  j                  z  rt	        ddt
        |¬«      }| j                  j                  |«       y)aI  
        Deliver a datagram to this tunnel's read buffer.  This makes it
        available to be read later using the C{read} method.

        @param datagram: The IPv4 datagram to deliver.  If the mode of this
            tunnel is TAP then ethernet framing will be added automatically.
        @type datagram: L{bytes}
        s         s   ÿÿÿÿÿÿr"   N)rB   r   ÚIFF_TAPÚvaluer'   Ú_IPv4rE   Úappend©rH   Údatagrams     r   ÚaddToReadBufferzTunnel.addToReadBufferÓ   sC   € ð �?‰?œ[×0Ñ0×6Ñ6Ò6Ü Ø [¼5È(ôˆHð 	�‰×Ñ˜xÕ(r   c                 ó  — | j                   rX| j                  t        j                  j                  z  rd}ndt
        z  }|dz  }|| j                   j                  «       d| z   S | j                  r
t        «       ‚| j                  ‚)a  
        Read a datagram out of this tunnel.

        @param limit: The maximum number of bytes from the datagram to return.
            If the next datagram is larger than this, extra bytes are dropped
            and lost forever.
        @type limit: L{int}

        @raise OSError: Any of the usual I/O problems can result in this
            exception being raised with some particular error number set.

        @raise IOError: Any of the usual I/O problems can result in this
            exception being raised with some particular error number set.

        @return: The datagram which was read from the tunnel.  If the tunnel
            mode does not include L{TunnelFlags.IFF_NO_PI} then the datagram is
            prefixed with a 4 byte PI header.
        @rtype: L{bytes}
        r   ó    r   N)
rE   rB   r   Ú	IFF_NO_PIrU   Ú_PI_SIZEÚpopleftrN   ÚNotImplementedErrorÚnonBlockingExceptionStyle)rH   ÚlimitÚheaders      r   ÚreadzTunnel.readä   sx   € ð( �?Š?Ø�‰¤×!6Ñ!6×!<Ñ!<Ò<Ø‘ð
 !¤8Ñ+�Ø˜‘
�Ø˜DŸO™O×3Ñ3Ó5°f°uÐ=Ñ=Ð=Ø�]Š]Ü%Ó'Ð'à×0Ñ0Ð0r   c                 ó
  — | j                   r*| j                   j                  «        t        t        d«      ‚t	        |«      | j
                  kD  rt        t        d«      ‚| j                  j                  |«       t	        |«      S )a{  
        Write a datagram into this tunnel.

        @param datagram: The datagram to write.
        @type datagram: L{bytes}

        @raise IOError: Any of the usual I/O problems can result in this
            exception being raised with some particular error number set.

        @return: The number of bytes of the datagram which were written.
        @rtype: L{int}
        zInterrupted system callzNo buffer space available)	rG   r_   ÚOSErrorr   r-   ÚSEND_BUFFER_SIZEr   rF   rW   rX   s     r   ÚwritezTunnel.write  sk   € ð ×ÒØ×Ñ×'Ñ'Ô)Üœ%Ð!:Ó;Ð;äˆx‹=˜4×0Ñ0Ò0Üœ'Ð#>Ó?Ð?à×Ñ×Ñ Ô)Ü�8‹}Ðr   N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú_DEVICE_NAMEÚIOErrorr   ÚEAGAIN_STYLErf   r   ÚEWOULDBLOCK_STYLEr   ÚEINTR_STYLEra   rg   rJ   ÚpropertyrN   rR   rZ   rd   rh   © r   r   r>   r>   ”   sƒ   „ ñð #€Lñ ˜6Ð#EÓF€LÙ Ð-DÓEÐñ ˜%Ð!<Ó=€Kà ,ÐàÐò&ð. ñ=ó ð=ð ñ<ó ð<ò)ò"!1óFr   r>   c                 ó.   ‡ — t        ‰ «      ˆ fd„«       }|S )a|  
    Wrap a L{MemoryIOSystem} method with permission-checking logic.  The
    returned function will check C{self.permissions} and raise L{IOError} with
    L{errno.EPERM} if the function name is not listed as an available
    permission.

    @param original: The L{MemoryIOSystem} instance to wrap.

    @return: A wrapper around C{original} that applies permission checks.
    c                 ól   •— ‰j                   | j                  vrt        t        d«      ‚ ‰| g|¢­i |¤ŽS )NzOperation not permitted)ri   Úpermissionsrf   r
   )rH   ÚargsÚkwargsÚoriginals      €r   ÚpermissionCheckerz&_privileged.<locals>.permissionChecker+  s:   ø€ à×Ñ D×$4Ñ$4Ñ4Üœ%Ð!:Ó;Ð;Ù˜Ð.˜tÒ. vÑ.Ð.r   r   )ry   rz   s   ` r   Ú_privilegedr{     s#   ø€ ô ˆ8ƒ_ó/ó ð/ð
 Ðr   c                   ór   — e Zd ZdZdZdZdZdZd„ Zd„ Z	d„ Z
edd
„«       Zd„ Zd„ Zd„ Zed„ «       Zd„ Zd„ Zy	)ÚMemoryIOSystemz÷
    An in-memory implementation of basic I/O primitives, useful in the context
    of unit testing as a drop-in replacement for parts of the C{os} module.

    @ivar _devices:
    @ivar _openFiles:
    @ivar permissions:

    @ivar _counter:
    i    é   é   r   c                 ó2   — i | _         i | _        ddh| _        y )NÚopenÚioctl)Ú_devicesÚ
_openFilesrv   rM   s    r   rJ   zMemoryIOSystem.__init__G  s   € ØˆŒØˆŒØ" GÐ,ˆÕr   c                 ó<   — | j                   |j                  «          S )aX  
        Get the L{Tunnel} object associated with the given L{TuntapPort}.

        @param port: A L{TuntapPort} previously initialized using this
            L{MemoryIOSystem}.

        @return: The tunnel object created by a prior use of C{open} on this
            object on the tunnel special device file.
        @rtype: L{Tunnel}
        )r„   Úfileno)rH   Úports     r   Ú	getTunnelzMemoryIOSystem.getTunnelL  s   € ð �‰˜tŸ{™{›}Ñ-Ð-r   c                 ó"   — || j                   |<   y)a1  
        Specify a class which will be used to handle I/O to a device of a
        particular name.

        @param name: The filesystem path name of the device.
        @type name: L{bytes}

        @param cls: A class (like L{Tunnel}) to instantiated whenever this
            device is opened.
        N)rƒ   )rH   rD   Úclss      r   ÚregisterSpecialDevicez$MemoryIOSystem.registerSpecialDeviceY  s   € ð "ˆ�‰�dÒr   Nc                 óÌ   — || j                   v rG| j                  }| xj                  dz  c_         | j                   |   | ||«      | j                  |<   |S t        t        d«      ‚)aþ  
        A replacement for C{os.open}.  This initializes state in this
        L{MemoryIOSystem} which will be reflected in the behavior of the other
        file descriptor-related methods (eg L{MemoryIOSystem.read},
        L{MemoryIOSystem.write}, etc).

        @param name: A string giving the name of the file to open.
        @type name: C{bytes}

        @param flags: The flags with which to open the file.
        @type flags: C{int}

        @param mode: The mode with which to open the file.
        @type mode: C{int}

        @raise OSError: With C{ENOSYS} if the file is not a recognized special
            device file.

        @return: A file descriptor associated with the newly opened file
            description.
        @rtype: L{int}
        r~   zFunction not implemented)rƒ   Ú_counterr„   rf   r	   )rH   rD   ÚflagsÚmodeÚfds        r   r�   zMemoryIOSystem.openf  s\   € ð0 �4—=‘=Ñ Ø—‘ˆBØ�MŠM˜QÑ�MØ"5 $§-¡-°Ñ"5°d¸EÀ4Ó"HˆD�O‰O˜BÑØˆIÜ”fÐ8Ó9Ð9r   c                 óz   — 	 | j                   |   j                  |«      S # t        $ r t        t        d«      ‚w xY w)z¤
        Try to read some bytes out of one of the in-memory buffers which may
        previously have been populated by C{write}.

        @see: L{os.read}
        úBad file descriptor)r„   rd   ÚKeyErrorrf   r   )rH   r�   rb   s      r   rd   zMemoryIOSystem.read…  s>   € ð	8Ø—?‘? 2Ñ&×+Ñ+¨EÓ2Ð2øÜò 	8Üœ%Ð!6Ó7Ð7ð	8úó   ‚   :c                 óz   — 	 | j                   |   j                  |«      S # t        $ r t        t        d«      ‚w xY w)z’
        Try to add some bytes to one of the in-memory buffers to be accessed by
        a later C{read} call.

        @see: L{os.write}
        r’   )r„   rh   r“   rf   r   )rH   r�   Údatas      r   rh   zMemoryIOSystem.write‘  s>   € ð	8Ø—?‘? 2Ñ&×,Ñ,¨TÓ2Ð2øÜò 	8Üœ%Ð!6Ó7Ð7ð	8úr”   c                 óZ   — 	 | j                   |= y# t        $ r t        t        d«      ‚w xY w)zŠ
        Discard the in-memory buffer and other in-memory state for the given
        file descriptor.

        @see: L{os.close}
        r’   N)r„   r“   rf   r   )rH   r�   s     r   ÚclosezMemoryIOSystem.close�  s0   € ð	8Ø—‘ Ñ#øÜò 	8Üœ%Ð!6Ó7Ð7ð	8ús   ‚ �*c                 óf  — 	 | j                   |   }|t        k7  rt        t
        d«      ‚t        j                  dt        fz  |«      \  }}||_	        ||_
        |dt        dz
   dz   |_        t        j                  dt        fz  |j                  |«      S # t        $ r t        t        d«      ‚w xY w)z�
        Perform some configuration change to the in-memory state for the given
        file descriptor.

        @see: L{fcntl.ioctl}
        r’   zRequest or args is not valid.z%dsHNé   s   123)r„   r“   rf   r   r   r   r   r2   r   rB   rC   rD   r   )rH   r�   Úrequestrw   ÚtunnelrD   r�   s          r   r‚   zMemoryIOSystem.ioctl©  s¬   € ð	8Ø—_‘_ RÑ(ˆFð ”jÒ Üœ&Ð"AÓBÐBä—]‘] 6¬Y¨LÑ#8¸$Ó?‰
ˆˆdØ ˆÔØ#ˆÔØ˜?œY¨™]Ð+¨fÑ4ˆŒä�{‰{˜6¤Y LÑ0°&·+±+¸tÓDÐDøô ò 	8Üœ%Ð!6Ó7Ð7ð	8ús   ‚B ÂB0c           	      óÀ   — d}d}t        ||d   t        ||d   |¬«      ¬«      }t        | j                  j	                  «       «      }|d   j                  |«       ||fS )ah  
        Write an ethernet frame containing an ip datagram containing a udp
        datagram containing the given payload, addressed to the given address,
        to a tunnel device previously opened on this I/O system.

        @param datagram: A UDP datagram payload to send.
        @type datagram: L{bytes}

        @param address: The destination to which to send the datagram.
        @type address: L{tuple} of (L{bytes}, L{int})

        @return: A two-tuple giving the address from which gives the address
            from which the datagram was sent.
        @rtype: L{tuple} of (L{bytes}, L{int})
        z10.1.2.3iaS  r   r~   )r#   r$   r&   )r8   r<   Úlistr„   ÚvaluesrZ   )rH   rY   ÚaddressÚsrcIPÚsrcPortÚ
serializedÚ	openFiless          r   ÚsendUDPzMemoryIOSystem.sendUDPÀ  sh   € ð" ˆØˆäØØ˜‘
Ü˜W¨'°!©*¸hÔGô
ˆ
ô ˜Ÿ™×/Ñ/Ó1Ó2ˆ	Ø�!‰×$Ñ$ ZÔ0à�wÐÐr   c                 ó   — t        | |«      S )aa  
        Get a socket-like object which can be used to receive a datagram sent
        from the given address.

        @param fileno: A file descriptor representing a tunnel device which the
            datagram will be received via.
        @type fileno: L{int}

        @param host: The IPv4 address to which the datagram was sent.
        @type host: L{bytes}

        @param port: The UDP port number to which the datagram was sent.
            received.
        @type port: L{int}

        @return: A L{socket.socket}-like object which can be used to receive
            the specified datagram.
        )Ú	_FakePort)rH   r†   Úhostr‡   s       r   Ú
receiveUDPzMemoryIOSystem.receiveUDPß  s   € ô& ˜˜vÓ&Ð&r   ©N)ri   rj   rk   rl   r�   ÚO_RDWRrL   rQ   rJ   rˆ   r‹   r{   r�   rd   rh   r˜   r‚   r¥   r©   rs   r   r   r}   r}   4  so   „ ñ	ð €Hà€FØ€JØ€Iò-ò
.ò"ð ò:ó ð:ò<
8ò
8ò
8ð ñEó ðEò, ó>'r   r}   c                   ó   — e Zd ZdZd„ Zd„ Zy)r§   zŒ
    A socket-like object which can be used to read UDP datagrams from
    tunnel-like file descriptors managed by a L{MemoryIOSystem}.
    c                 ó    — || _         || _        y rª   )Ú_systemÚ_fileno)rH   r@   r†   s      r   rJ   z_FakePort.__init__û  s   € ØˆŒØˆ�r   c                 ó~  ‡
‡— | j                   j                  | j                     j                  j	                  «       }g Š
t        «       }ˆ
fd„}||_        t        «       }|j                  d|«       t        «       Š‰j                  d|«       | j                   j                  | j                     j                  }|t        j                  j                  z  r)t        «       }|j                  d‰«       |j                  }nˆfd„}|t        j                  j                  z   }	|	r	|t         d } ||«       ‰
d   d| S )a_  
        Receive a datagram sent to this port using the L{MemoryIOSystem} which
        created this object.

        This behaves like L{socket.socket.recv} but the data being I{sent} and
        I{received} only passes through various memory buffers managed by this
        object and L{MemoryIOSystem}.

        @see: L{socket.socket.recv}
        c                 ó(   •— ‰j                  | «       y rª   )rW   )rY   r    Ú	datagramss     €r   Úcapturez_FakePort.recv.<locals>.capture  s   ø€ Ø×Ñ˜XÕ&r   i90  é   r    c                 ó.   •— ‰j                  | d d d d «      S rª   )ÚdatagramReceived)r–   Úips    €r   ú<lambda>z _FakePort.recv.<locals>.<lambda>   s   ø€ ¨B×,?Ñ,?Ø�d˜D $¨ó-€ r   Nr   )r®   r„   r¯   rF   r_   r   r¶   r   ÚaddProtor   rB   r   rT   rU   r   r]   r^   )rH   Únbytesr–   Úreceiverr³   Úudpr�   Úetherr¶   Ú	dataHasPIr²   r·   s             @@r   Úrecvz_FakePort.recvÿ  s  ù€ ð �|‰|×&Ñ& t§|¡|Ñ4×@Ñ@×HÑHÓJˆàˆ	Ü#Ó%ˆô	'ð %,ˆÔ!äÓˆØ�‰�U˜HÔ%ä‹\ˆØ
�‰�B˜Ôà�|‰|×&Ñ& t§|¡|Ñ4×?Ñ?ˆØ”+×%Ñ%×+Ñ+Ò+Ü$Ó&ˆEØ�N‰N˜5 "Ô%Ø$×5Ñ5Ñó Ðð ¤× 5Ñ 5× ;Ñ ;Ñ;Ð<ˆ	áàœ˜	�?ˆDá˜ÔØ˜‰|˜G˜VÐ$Ð$r   N)ri   rj   rk   rl   rJ   r¿   rs   r   r   r§   r§   õ  s   „ ñò
ó,%r   r§   )+rl   r.   r   Úcollectionsr   Úerrnor   r   r   r   r   r	   r
   r   Ú	functoolsr   Úzope.interfacer   Útwisted.internet.protocolr   Útwisted.pair.ethernetr   Útwisted.pair.ipr   Útwisted.pair.rawudpr   Útwisted.pair.tuntapr   r   r   r   Útwisted.python.compatr   r^   r   rV   r'   r8   r<   r>   r{   r}   r§   rs   r   r   ú<module>rÊ      s›   ðñó Û Ý ß S× SÓ SÝ å &å 6Ý 2Ý &Ý .ß WÓ WÝ .ð €ò
 ð 	€ò.ò,/òd÷<Hñ HòVñ* Ð Ó!÷}'ð }'ó "ð}'÷@6%ò 6%r   