
    VhB                       d Z ddlmZ ddlZddl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 ed
k(  r3ddlmZ ddlmZ ddlmZmZmZmZmZmZmZ eeeegZeeeegZeZeZeZ eZ!nddlm Z mZm!Z!mZmZm"Z" e e!e"gZegZddl#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z) ddl*m+Z+  ee)jX                  e)jZ                  e)j\                         G d de&j^                               Z0 ee)jb                         G d de
e0             Z2y)a  
Various asynchronous UDP classes.

Please do not use this module directly.

@var _sockErrReadIgnore: list of symbolic error constants (from the C{errno}
    module) representing socket errors where the error is temporary and can be
    ignored.

@var _sockErrReadRefuse: list of symbolic error constants (from the C{errno}
    module) representing socket errors that indicate connection refused.
    )annotationsN)Optional)implementer)MulticastMixin)IReactorMulticast)AbstractDatagramProtocol)platformTypewin32)WSAEINPROGRESS)WSAEWOULDBLOCK)WSAECONNREFUSEDWSAECONNRESETWSAEINTRWSAEMSGSIZEWSAENETRESETWSAENOPROTOOPTWSAETIMEDOUT)EAGAINECONNREFUSEDEINTREMSGSIZEENOPROTOOPTEWOULDBLOCK)abstractaddressbasedefererror
interfaces)logc                      e Zd ZU dZej
                  Zded<   ej                  Z	ded<   dZ
dZded	<   dZdd
Zed        Zd dZd Zd Zd Zd Zd Zd!dZd Zd Zd Zd Zd Zd!dZd Zd Zd Zd Z d Z!d Z"y)"Porta  
    UDP port, listening for packets.

    @ivar maxThroughput: Maximum number of bytes read in one event
        loop iteration.

    @ivar addressFamily: L{socket.AF_INET} or L{socket.AF_INET6}, depending on
        whether this port is listening on an IPv4 address or an IPv6 address.

    @ivar _realPortNumber: Actual port number being listened on. The
        value will be L{None} until this L{Port} is listening.

    @ivar _preexistingSocket: If not L{None}, a L{socket.socket} instance which
        was created and initialized outside of the reactor and will be used to
        listen for connections (instead of a new socket being created by this
        L{Port}).
    zsocket.AddressFamilyaddressFamilyzsocket.SocketKind
socketTypei   NzOptional[int]_realPortNumberc                    t         j                  j                  | |       || _        || _        || _        || _        | j                          d| _        | j                          y)a  
        @param port: A port number on which to listen.
        @type port: L{int}

        @param proto: A C{DatagramProtocol} instance which will be
            connected to the given C{port}.
        @type proto: L{twisted.internet.protocol.DatagramProtocol}

        @param interface: The local IPv4 or IPv6 address to which to bind;
            defaults to '', ie all IPv4 addresses.
        @type interface: L{str}

        @param maxPacketSize: The maximum packet size to accept.
        @type maxPacketSize: L{int}

        @param reactor: A reactor which will notify this C{Port} when
            its socket is ready for reading or writing. Defaults to
            L{None}, ie the default global reactor.
        @type reactor: L{interfaces.IReactorFDSet}
        N)
r   BasePort__init__portprotocolmaxPacketSize	interface	setLogStr_connectedAddr_setAddressFamily)selfr)   protor,   r+   reactors         D/home/dcms/DCMS/lib/python3.12/site-packages/twisted/internet/udp.pyr(   zPort.__init__]   sS    * 	tW-	*""     c                    t        j                  ||| j                        }|j                         d   } | d||||      }||_        |S )a  
        Create a new L{Port} based on an existing listening
        I{SOCK_DGRAM} socket.

        @param reactor: A reactor which will notify this L{Port} when
            its socket is ready for reading or writing. Defaults to
            L{None}, ie the default global reactor.
        @type reactor: L{interfaces.IReactorFDSet}

        @param fd: An integer file descriptor associated with a listening
            socket.  The socket must be in non-blocking mode.  Any additional
            attributes desired, such as I{FD_CLOEXEC}, must also be set already.
        @type fd: L{int}

        @param addressFamily: The address family (sometimes called I{domain}) of
            the existing socket.  For example, L{socket.AF_INET}.
        @type addressFamily: L{int}

        @param protocol: A C{DatagramProtocol} instance which will be
            connected to the C{port}.
        @type protocol: L{twisted.internet.protocol.DatagramProtocol}

        @param maxPacketSize: The maximum packet size to accept.
        @type maxPacketSize: L{int}

        @return: A new instance of C{cls} wrapping the socket given by C{fd}.
        @rtype: L{Port}
        r   N)r,   r2   r+   )socketfromfdr$   getsockname_preexistingSocket)	clsr2   fdr#   r*   r+   r)   r,   r0   s	            r3   _fromListeningDescriptorzPort._fromListeningDescriptor{   sV    @ }}R?$$&q)	'
 #'r4   c                    | j                   'd| j                  j                   d| j                    dS d| j                  j                   dS )N<z on >z not connected>)r%   r*   	__class__r0   s    r3   __repr__zPort.__repr__   sO    +t}}../tD4H4H3IKKt}}../??r4   c                    | j                   S )z)
        Return a socket object.
        )r6   rA   s    r3   	getHandlezPort.getHandle        {{r4   c                D    | j                          | j                          y)z
        Create and bind my socket, and begin listening on it.

        This is called on unserialization, and must be called after creating a
        server to begin listening on the specified port.
        N)_bindSocket_connectToProtocolrA   s    r3   startListeningzPort.startListening   s     	!r4   c                (   | j                   9	 | j                         }|j                  | j                  | j                  f       n| j                   }d| _         |j                         d   | _	        t        j                  | j                  | j                        d| j                         d| _        || _        | j                  j                   | _        y# t
        $ r0}t        j                  | j                  | j                  |      d}~ww xY w)aJ  
        Prepare and assign a L{socket.socket} instance to
        C{self.socket}.

        Either creates a new SOCK_DGRAM L{socket.socket} bound to
        C{self.interface} and C{self.port} or takes an existing
        L{socket.socket} provided via the
        L{interfaces.IReactorSocket.adoptDatagramPort} interface.
        N   z starting on )r9   createInternetSocketbindr,   r)   OSErrorr   CannotListenErrorr8   r%   r    msg_getLogPrefixr*   	connectedr6   filenor0   sktles      r3   rG   zPort._bindSocket   s     ""*M//1$..$))45
 ))C&*D#  #03!!$--0$2F2FH	

 kk((%  M--dnndiiLLMs   7C 	D!+DDc                Z    | j                   j                  |        | j                          y N)r*   makeConnectionstartReadingrA   s    r3   rH   zPort._connectToProtocol   s     $$T*r4   c                <   d}|| j                   k  r	 | j                  j                  | j                        \  }}|t	        |      z  }| j
                  t        j                  k(  r|dd }	 | j                  j                  ||       || j                   k  ryy# t        $ r t        j                          Y 1w xY w# t        $ rU}|j                  d   }|t        v rY d}~y|t        v r+| j                   r| j                  j#                          Y d}~y d}~ww xY w)z=
        Called when my socket is ready for reading.
        r   N   )maxThroughputr6   recvfromr+   lenr#   AF_INET6r*   datagramReceivedBaseExceptionr    errrN   args_sockErrReadIgnore_sockErrReadRefuser.   connectionRefused)r0   readdataaddrsenos         r3   doReadzPort.doRead   s     T'''![[11$2D2DE
d D	!%%8  8DMM224>/ T'''0 % GGI+  WWQZ++++**779s5   (B= ,B B:9B:=	DD".DDDc                   | j                   r.|d| j                   fv sJ 	 | j                  j                  |      S |dk7  sJ t        j                  |d         s9t        j                  |d         s!|d   dk7  rt        j                   |d   d      t        j                  |d         s|d   dk(  r6| j"                  t        j$                  k(  rt        j                   |d   d      t        j                  |d         r6| j"                  t        j&                  k(  rt        j                   |d   d      	 | j                  j)                  ||      S # t        $ r{}|j                  d   }|t
        k(  r| j                  |      cY d}~S |t        k(  rt        j                  d      |t        k(  r| j                  j                          n Y d}~yd}~ww xY w# t        $ ra}|j                  d   }|t
        k(  r| j                  ||      cY d}~S |t        k(  rt        j                  d      |t        k(  rY d}~y d}~ww xY w)az  
        Write a datagram.

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

        @type addr: L{tuple} containing L{str} as first element and L{int} as
            second element, or L{None}
        @param addr: A tuple of (I{stringified IPv4 or IPv6 address},
            I{integer port number}); can be L{None} in connected mode.
        Nr   zmessage too longz<broadcast>z0write() only accepts IP addresses, not hostnamesz7IPv6 port write() called with IPv4 or broadcast addressz*IPv4 port write() called with IPv6 address)r.   r6   sendrN   rd   r   writer   r   MessageLengthErrorr   r*   rg   r   isIPAddressisIPv6AddressInvalidAddressErrorr#   r`   AF_INETsendto)r0   datagramrj   rk   rl   s        r3   rp   z
Port.write  s    D$"5"56666{{''11 4<<((a1 ..tAw7G},//GO  $$T!W-aM1I$$7//GV  %%d1g.43E3E3W//GI {{))(D99?  	WWQZ;::h//8^223EFF<'MM335 6	@  WWQZ;::h558^223EFF<' sN   E 8G 	G(GGAGG	I$)I I'I ?I  Ic                F    | j                  dj                  |      |       y)a  
        Write a datagram constructed from an iterable of L{bytes}.

        @param seq: The data that will make up the complete datagram to be
            written.
        @type seq: an iterable of L{bytes}

        @type addr: L{tuple} containing L{str} as first element and L{int} as
            second element, or L{None}
        @param addr: A tuple of (I{stringified IPv4 or IPv6 address},
            I{integer port number}); can be L{None} in connected mode.
        r4   N)rp   join)r0   seqrj   s      r3   writeSequencezPort.writeSequenceB  s     	

388C=$'r4   c                    | j                   rt        d      t        j                  |      s+t        j                  |      st        j                  |d      ||f| _         | j                  j                  ||f       y)z-
        'Connect' to remote server.
        z:already connected, reconnecting is not currently supportednot an IPv4 or IPv6 address.N)	r.   RuntimeErrorr   rr   rs   r   rt   r6   connect)r0   hostr)   s      r3   r   zPort.connectQ  sp     L  ##D)(2H2H2N++D2PQQ#TlT4L)r4   c                    | j                          | j                  r'| j                  j                  d| j                         y y )Nr   )stopReadingrR   r2   	callLaterconnectionLostrA   s    r3   _loseConnectionzPort._loseConnection^  s4    >>LL""1d&9&9: r4   c                z    | j                   rt        j                         x}| _        nd }| j	                          |S rX   )rR   r   Deferreddr   )r0   results     r3   stopListeningzPort.stopListeningc  s2    >>#nn..FTVFr4   c                \    t        j                  dt        d       | j                          y )Nz-Please use stopListening() to disconnect portr\   )
stacklevel)warningswarnDeprecationWarningr   rA   s    r3   loseConnectionzPort.loseConnectionk  s%    ;	

 	r4   c                h   t        j                  d| j                  z         d| _        d| _        t        j
                  j                  | |       | j                  j                          | j                  j                          | `	| `t        | d      r| j                  j                  d       | `yy)z&
        Cleans up my socket.
        z(UDP Port %s Closed)Nr   )r    rP   r%   r]   r   r'   r   r*   doStopr6   closerS   hasattrr   callback)r0   reasons     r3   r   zPort.connectionLosts  s     	&)=)==>#$$T62KK4FFOOD! r4   c                N    | j                  | j                        }d|z  | _        y)zP
        Initialize the C{logstr} attribute to be used by C{logPrefix}.
        z%s (UDP)N)rQ   r*   logstr)r0   	logPrefixs     r3   r-   zPort.setLogStr  s$     &&t}}5	 9,r4   c                0   t        j                  | j                        rt        j                  | _        yt        j                  | j                        rt        j                  | _        y| j                  r t        j                  | j                  d      y)z8
        Resolve address family for the socket.
        r}   N)
r   rs   r,   r6   r`   r#   rr   ru   r   rt   rA   s    r3   r/   zPort._setAddressFamily  si     !!$..1!'D!!$..1!'D^^++ >  r4   c                    | j                   S )z0
        Return the prefix to log with.
        )r   rA   s    r3   r   zPort.logPrefix  rE   r4   c                
   | j                   j                         }| j                  t         j                  k(  rt	        j
                  dg| S | j                  t         j                  k(  rt	        j                  dg|dd  S y)z
        Return the local address of the UDP connection

        @returns: the local address of the UDP connection
        @rtype: L{IPv4Address} or L{IPv6Address}
        UDPNr\   )r6   r8   r#   ru   r   IPv4Addressr`   IPv6Address)r0   rj   s     r3   getHostzPort.getHost  sq     {{&&(/&&u4t446??2&&u:Ra:: 3r4   c                v    | j                   j                  t         j                  t         j                  |       y)z
        Set whether this port may broadcast. This is disabled by default.

        @param enabled: Whether the port may broadcast.
        @type enabled: L{bool}
        N)r6   
setsockopt
SOL_SOCKETSO_BROADCAST)r0   enableds     r3   setBroadcastAllowedzPort.setBroadcastAllowed  s&     	v00&2E2EwOr4   c                    t        | j                  j                  t        j                  t        j                              S )z
        Checks if broadcast is currently allowed on this port.

        @return: Whether this port may broadcast.
        @rtype: L{bool}
        )boolr6   
getsockoptr   r   rA   s    r3   getBroadcastAllowedzPort.getBroadcastAllowed  s,     DKK**6+<+<f>Q>QRSSr4   )     N)returnstrrX   )#__name__
__module____qualname____doc__r6   ru   r#   __annotations__
SOCK_DGRAMr$   r]   r%   r9   r(   classmethodr<   rB   rD   rI   rG   rH   rm   rp   r{   r   r   r   r   r   r-   r/   r   r   r   r    r4   r3   r"   r"   @   s    $ +1..M'8$*$5$5J!5M%)O])!< ) )V@"!)F@<|(*;
 -;PTr4   r"   c                  D    e Zd ZdZ	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZy)MulticastPortz.
    UDP Port that supports multicasting.
    Nc                F    t         j                  | |||||       || _        y)zX
        @see: L{twisted.internet.interfaces.IReactorMulticast.listenMulticast}
        N)r"   r(   listenMultiple)r0   r)   r1   r,   r+   r2   r   s          r3   r(   zMulticastPort.__init__  s"     	dD%M7K,r4   c                   t         j                  |       }| j                  rq|j                  t        j
                  t        j                  d       t        t        d      r2	 |j                  t        j
                  t        j                  d       |S |S # t        $ r }|j                  t        k(  rn Y d}~|S d}~ww xY w)z
        Override L{Port.createInternetSocket} to configure the socket to honor
        the C{listenMultiple} argument to L{IReactorMulticast.listenMultiple}.
        rK   SO_REUSEPORTN)r"   rL   r   r   r6   r   SO_REUSEADDRr   r   rN   errnor   rT   s      r3   rL   z"MulticastPort.createInternetSocket  s    
 ''-NN6,,f.A.A1Ev~.NN6#4#4f6I6I1M 
s
  xx;.  
s   "/B 	B>B99B>)r   r   NF)r)   intr1   r   r,   r   r+   r   r2   zIReactorMulticast | Noner   r   r   None)r   zsocket.socket)r   r   r   r   r(   rL   r   r4   r3   r   r     sc     !,0$-- (- 	-
 - *- - 
-r4   r   )3r   
__future__r   r6   r   typingr   zope.interfacer   twisted.internet._multicastr   twisted.internet.interfacesr   twisted.internet.protocolr   twisted.python.runtimer	   r   r   r   r   r   r   r   r   r   r   r   re   rf   r   r   r   r   r   twisted.internetr   r   r   r   r   r   twisted.pythonr    IListeningPortIUDPTransportISystemHandler'   r"   IMulticastTransportr   r   r4   r3   <module>r      s  
 #    & 6 9 > /7$$   #NKP)=,U H"LFEUU %5& O N  z779Q9QwT4== wTwTt Z++,%ND % -%r4   