
    VhkO                       d Z ddlmZ ddlZddlZddlZddlmZmZm	Z	 ddl
mZmZ ddlmZmZmZmZmZ ddlmZmZ ddlmZmZ dd	lmZ dd
lmZmZ ddl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+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1 ddl2m3Z3m4Z4m5Z5 	 ddl6m7Z8 e8Z9erddl;m<Z< e ejz                  e"ej|                  iZ? ee&ej                  ej                         G d dej                  e1e,             ZCe9 eeCej                          G d de-e.eC      ZE G d deC      ZF G d de+      Z* eej                         G d de1e             ZHy# e:$ r dZ9Y w xY w)z
TCP support for IOCP reactor
    )annotationsN)TYPE_CHECKINGOptionalUnion)classImplementsimplementer)addressdefererror
interfacesmain)	_LogOwnerisIPv6Address)IPv4AddressIPv6Address)	IProtocol)abstractiocpsupport)ERROR_CONNECTION_REFUSEDERROR_IO_PENDINGERROR_NETWORK_UNREACHABLESO_UPDATE_ACCEPT_CONTEXTSO_UPDATE_CONNECT_CONTEXT)IReadWriteHandle)Protocol)	Connector_AbortingMixin_BaseBaseClient_BaseTCPClient_getsockname_resolveIPv6_SocketCloser)failurelogreflect)startTLS)IOCPReactorc                      e Zd ZdZdZddZd Zd Zd 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dZd Zd Zd Zd Zy)
Connectionz
    @ivar TLS: C{False} to indicate the connection is in normal TCP mode,
        C{True} to indicate that TLS has been started and that operations must
        be routed through the L{TLSMemoryBIOProtocol} instance.
    FNc                    t         j                  j                  | |       || _        |j                  | _        || _        y N)r   
FileHandle__init__socketfilenogetFileHandleprotocol)selfsockprotoreactors       P/home/dcms/DCMS/lib/python3.12/site-packages/twisted/internet/iocpreactor/tcp.pyr-   zConnection.__init__F   s2    $$T73![[    c                    | j                   S r+   )r.   r2   s    r6   	getHandlezConnection.getHandleL   s    {{r7   c                    t        |t              rn3t        |t              rt        |      }nt        dt	        |      z         | j
                  j                  |       y)z`
        @param rbuffer: Data received.
        @type rbuffer: L{bytes} or L{bytearray}
        z%data must be bytes or bytearray, not N)
isinstancebytes	bytearray	TypeErrortyper1   dataReceived)r2   rbuffers     r6   rA   zConnection.dataReceivedO   sK    
 gu%+GnGCd7mSTT""7+r7   c                L    t        j                  | j                         ||      S r+   )_iocprecvr0   )r2   bufflistevts      r6   readFromHandlezConnection.readFromHandle^   s    zz$,,.#>>r7   c                    t        |      }t        j                  | j                         |d| j                   j                         |      S )z
        Send C{buff} to current file handle using C{_iocp.send}. The buffer
        sent is limited to a size of C{self.SEND_LIMIT}.
        r   )
memoryviewrD   sendr0   
SEND_LIMITtobytes)r2   buffrG   	writeViews       r6   writeToHandlezConnection.writeToHandlea   sC    
 t$	zz )A"@"H"H"JC
 	
r7   c                R   	 | j                   j                  d       t        j                  | j
                  d       }|r	 |j                          y y # t        $ r Y @w xY w# t        $ r< t        j                         }t        j                          | j                  |       Y y w xY w)N   )r.   shutdownOSErrorr   IHalfCloseableProtocolr1   writeConnectionLostBaseExceptionr#   Failurer$   errconnectionLost)r2   pfs      r6   _closeWriteConnectionz Connection._closeWriteConnectionk   s    	KK  # --dmmTB'%%'   		 ! 'OO%	##A&'s$   A  A! 	AA!AB&%B&c                   t        j                  | j                  d       }|r	 |j                          y | j                  |       y # t        $ r: t        j                          | j                  t        j                                Y y w xY wr+   )
r   rU   r1   readConnectionLostrW   r$   rY   rZ   r#   rX   )r2   reasonr[   s      r6   r_   zConnection.readConnectionLosty   sk    --dmmTB7$$&
 '	 ! 7	##GOO$567s   A A B
	B
c                   | j                   ry t        j                  j                  | |       |d u xs  |j	                  t
        j                         }| j                  |       | j                  }| `| `	| `
|j                  |       y r+   )disconnectedr   r,   rZ   checkr   ConnectionAborted_closeSocketr1   r.   r0   )r2   r`   isCleanr1   s       r6   rZ   zConnection.connectionLost   sy    **48D.MU5L5L(M$M'"==MK'r7   c                    | j                   S )zN
        Return the prefix to log with when I own the logging thread.
        )logstrr9   s    r6   	logPrefixzConnection.logPrefix        {{r7   c                    t        | j                  j                  t        j                  t        j                              S r+   )boolr.   
getsockoptIPPROTO_TCPTCP_NODELAYr9   s    r6   getTcpNoDelayzConnection.getTcpNoDelay   s*    DKK**6+=+=v?Q?QRSSr7   c                v    | j                   j                  t         j                  t         j                  |       y r+   )r.   
setsockoptrn   ro   r2   enableds     r6   setTcpNoDelayzConnection.setTcpNoDelay   s$    v1163E3EwOr7   c                    t        | j                  j                  t        j                  t        j                              S r+   )rl   r.   rm   
SOL_SOCKETSO_KEEPALIVEr9   s    r6   getTcpKeepAlivezConnection.getTcpKeepAlive   s*    DKK**6+<+<f>Q>QRSSr7   c                v    | j                   j                  t         j                  t         j                  |       y r+   )r.   rr   rw   rx   rs   s     r6   setTcpKeepAlivezConnection.setTcpKeepAlive   s$    v00&2E2EwOr7   c                <    t        | ||t        j                         y)z9
            @see: L{ITLSTransport.startTLS}
            N)	_startTLSr   r,   )r2   contextFactorynormals      r6   r&   zConnection.startTLS   s     dNFH4G4GHr7   c                    | j                   ry| j                  r| j                  j                  |       yt        j
                  j                  | |       y)z
        Write some data, either directly to the underlying handle or, if TLS
        has been started, to the L{TLSMemoryBIOProtocol} for it to encrypt and
        send.

        @see: L{twisted.internet.interfaces.ITransport.write}
        N)rb   TLSr1   writer   r,   )r2   datas     r6   r   zConnection.write   s?     88MM%%%dD1r7   c                    | j                   ry| j                  r| j                  j                  |       yt        j
                  j                  | |       y)z
        Write some data, either directly to the underlying handle or, if TLS
        has been started, to the L{TLSMemoryBIOProtocol} for it to encrypt and
        send.

        @see: L{twisted.internet.interfaces.ITransport.writeSequence}
        N)rb   r   r1   writeSequencer   r,   )r2   iovecs     r6   r   zConnection.writeSequence   s?     88MM''.--dE:r7   c                    | j                   r5| j                  r(| j                  s| j                  j	                          yyyt
        j                  j	                  | |       y)z
        Close the underlying handle or, if TLS has been started, first shut it
        down.

        @see: L{twisted.internet.interfaces.ITransport.loseConnection}
        N)r   	connecteddisconnectingr1   loseConnectionr   r,   )r2   r`   s     r6   r   zConnection.loseConnection   sI     88~~d&8&8,,. '9~ ..tV<r7   c                    | j                   r| j                  j                  ||       yt        j                  j                  | ||       y)zc
        Register a producer.

        If TLS is enabled, the TLS connection handles this.
        N)r   r1   registerProducerr   r,   )r2   producer	streamings      r6   r   zConnection.registerProducer   s9     88
 MM**8Y?00xKr7   c                    | j                   r| j                  j                          yt        j                  j                  |        y)ze
        Unregister a producer.

        If TLS is enabled, the TLS connection handles this.
        N)r   r1   unregisterProducerr   r,   r9   s    r6   r   zConnection.unregisterProducer   s/     88MM,,.2248r7   c                     y r+    r9   s    r6   getHostzConnection.getHost       r7   c                     y r+   r   r9   s    r6   getPeerzConnection.getPeer   r   r7   r+   )T)__name__
__module____qualname____doc__r   r-   r:   rA   rH   rP   r]   r_   rZ   ri   rp   ru   ry   r{   r}   r&   r   r   r   r   r   r   r   r   r7   r6   r)   r)   <   s     C,?
'	(
(TPTP 	I2;=L	9r7   r)   c                  l    e Zd ZdZej
                  Zej                  ZdZ	e
Zd Zd Zd Zd Zd Zd Zy	)
Clientz
    @ivar _tlsClientDefault: Always C{True}, indicating that this is a client
        connection, and by default when TLS is negotiated this class will act as
        a TLS client.
    Tc                N    |d}|| _         t        j                  | |||||       y )N) r   )r5   r   r-   )r2   hostportbindAddress	connectorr5   s         r6   r-   zClient.__init__	  s,    !KdD+y'Rr7   c                b    | j                   j                  | j                  | j                        S )zd
        Create a socket registered with the IOCP reactor.

        @see: L{_BaseTCPClient}
        )r5   createSocketaddressFamily
socketTyper9   s    r6   createInternetSocketzClient.createInternetSocket  s%     ||((););T__MMr7   c                    | ` | `y)z
        Clean up potentially circular references to the socket and to its
        C{getFileHandle} method.

        @see: L{_BaseBaseClient}
        N)r.   r0   r9   s    r6   _collectSocketDetailszClient._collectSocketDetails  s     K+r7   c                :    | j                   j                  |        y)z^
        Remove the active handle from the reactor.

        @see: L{_BaseBaseClient}
        N)r5   removeActiveHandler9   s    r6   _stopReadingAndWritingzClient._stopReadingAndWriting!  s     	''-r7   c           	        |r[t         j                  ||      }| j                  t        j                  |t
        j                  j                  |d      f             y | j                  j                  t        j                  t        t        j                  d| j                  j                                      | j                  j                  | j!                               | _        d| _        | j'                  | j"                        }|dz   | _        | j"                   t+               | _        | j-                          y | j"                  j/                  |        | j1                          y )NzUnknown errorPTz,client)connectExErrorsgetfailIfNotConnectedr   getConnectErrorerrno	errorcoder.   rr   rw   r   structpackr/   r   buildProtocolr   r1   r   _getLogPrefixrh   r   r   makeConnectionstartReading)r2   rcr   rG   ri   s        r6   	cbConnectzClient.cbConnect)  s    $$R,B##%%r5??+>+>r?+S&TU KK""!!)C!3!3!56
 !NN88HDM!DN**4==9I#i/DK}}$ !)
##%,,T2!!#r7   c                j   t        | d      sy t        j                  sJ | j                  j	                  |        t        j
                  | j                  |       }t        j                  | j                  j                         | j                  |      }|r|t        k7  r| j                  |d|       y y y )Nr   r   )hasattrrD   have_connectexr5   addActiveHandleEventr   connectr.   r/   realAddressr   )r2   rG   r   s      r6   	doConnectzClient.doConnectG  s    t[) ####$$T*kk$..$/]]4;;--/1A1A3G"((NN2q#& )2r7   N)r   r   r   r   r.   AF_INETr   SOCK_STREAMr   _tlsClientDefaultr)   _commonConnectionr-   r   r   r   r   r   r   r7   r6   r   r      sI     NNM##J"SN,.$<'r7   r   c                  H    e Zd ZdZdZ	 	 	 	 	 	 	 	 	 	 	 	 ddZd	dZd Zd Zy)
ServeraV  
    Serverside socket-stream connection class.

    I am a serverside network connection transport; a socket which came from an
    accept() on a server.

    @ivar _tlsClientDefault: Always C{False}, indicating that this is a server
        connection, and by default when TLS is negotiated this class will act as
        a TLS server.
    Fc                   t         j                  | |||       || _        || _        || _        | j                  | j                        }| d| d| j                  j                   | _        dj                  | j                  j                  j                  | j                  | j                  j                        | _        d| _        | j                          y)a  
        Server(sock, protocol, client, server, sessionno)

        Initialize me with a socket, a protocol, a descriptor for my peer (a
        tuple of host, port describing the other end of the connection), an
        instance of Port, and a session number.
        ,z<{} #{} on {}>TN)r)   r-   
serverAddr
clientAddr	sessionnor   r1   r   rh   format	__class__r   r   repstrr   r   )r2   r3   r1   r   r   r   r5   ri   s           r6   r-   zServer.__init__c  s      	D$':$$"&&t}}5	"1YKq1E1E0FG+22MM##,,NNOO  

 r7   c                    | j                   S )z=
        A string representation of this connection.
        )r   r9   s    r6   __repr__zServer.__repr__  rj   r7   c                    | j                   S )zW
        Returns an IPv4Address.

        This indicates the server's address.
        )r   r9   s    r6   r   zServer.getHost       r7   c                    | j                   S )zW
        Returns an IPv4Address.

        This indicates the client's address.
        )r   r9   s    r6   r   zServer.getPeer  r   r7   N)r3   zsocket.socketr1   r   r   Union[IPv4Address, IPv6Address]r   r   r   intr5   r'   returnstr)	r   r   r   r   r   r-   r   r   r   r   r7   r6   r   r   U  s]    	   4	
 4  <r7   r   c                      e Zd Zd Zy)r   c                p    t        | j                  | j                  | j                  | | j                        S r+   )r   r   r   r   r5   r9   s    r6   _makeTransportzConnector._makeTransport  s'    diiD,<,<dDLLQQr7   N)r   r   r   r   r   r7   r6   r   r     s    Rr7   r   c                      e Zd ZU dZdZdZej                  Zej                  Z
ej                  ZdZdZded<   dZddZddZd	 Z ej,                  ej0                        fd
ZeZd Zd Zd Zd Zd Zd Z d Z!y)PortFr   NzOptional[int]_realPortNumberTCPc                    || _         || _        || _        || _        || _        t        |      r+t        j                  | _        t        j                  | _        y y r+   )r   factorybacklog	interfacer5   r   r.   AF_INET6r   r	   r   _addressType)r2   r   r   r   r   r5   s         r6   r-   zPort.__init__  sL    	"#!'D ' 3 3D $r7   c                    | j                   ;dj                  | j                  | j                  j                  | j                         S dj                  | j                  | j                  j                        S )Nz<{} of {} on {}>z<{} of {} (not listening)>)r   r   r   r   r9   s    r6   r   zPort.__repr__  sg    +%,,&&$$  066&& r7   c                   	 | j                   j                  | j                  | j                        }| j                  t        j
                  k(  r!t        | j                  | j                        }n| j                  | j                  f}|j                  |       t        j                  |j                               | _        |j#                         d   | _        t'        j(                  | j+                  | j,                        d| j$                         | j,                  j/                          |j1                  | j2                         d| _        d| _        | j                   j9                  |        || _        | j                  j                  | _        | j=                          y # t        $ r0}t        j                  | j                  | j                  |      d }~ww xY w)NrR   z starting on TF)r5   r   r   r   r.   r   r!   r   r   bindrT   r   CannotListenErrorrD   
maxAddrLenr/   addrLengetsocknamer   r$   msgr   r   doStartlistenr   r   rb   r   r0   doAccept)r2   sktaddrles       r6   startListeningzPort.startListening  s]   		I,,++D,>,>PC!!V__4#DNNDII>		2HHTN ''

5  #03!!$,,/1E1EG	

 	

4<< !$$T*![[//+  	I))$..$))RHH	Is   BF' '	G 0+GG c                    d| _         | j                  rLt        j                         | _        | j
                  j                  d| j                  |       | j                  S y)z
        Stop accepting connections on this port.

        This will shut down my socket and call self.connectionLost().
        It returns a deferred which will fire successfully when the
        port is actually closed.
        Tr   N)r   r   r
   Deferreddeferredr5   	callLaterrZ   )r2   connDones     r6   r   zPort.loseConnection  sL     ">>!NN,DMLL""1d&9&98D==  r7   c                d    t        j                  d| j                   d| j                   d       y)z.
        Log message for closing port
        (z Port z Closed)N)r$   r   _typer   r9   s    r6   _logConnectionLostMsgzPort._logConnectionLostMsg  s*     	!DJJ<vd&:&:%;8DEr7   c                   | j                          d| _        d}t        | d      r| j                  }| `d| _        | j
                  j                  |        d| _        | j                  d       | `	| `
	 | j                  j                          d| _        ||j                  d       yy# t        $ r0 d| _        |%|j!                  t#        j$                                Y y w xY w)z'
        Cleans up the socket.
        Nr   TF)r  r   r   r   rb   r5   r   r   re   r.   r0   r   doStopr   callbackrW   errbackr#   rX   )r2   r`   ds      r6   rZ   zPort.connectionLost  s     	""$#4$A ''-$K	!LL! "'D}

4    	!&D}		'//+,	s   3B) )5C" C"c                T    t        j                  | j                  j                        S )zK
        Returns the name of my class, to prefix log entries with.
        )r%   qualr   r   r9   s    r6   ri   zPort.logPrefix  s     ||DLL2233r7   c                N     | j                   dgt        | j                         S )zf
        Returns an IPv4Address or IPv6Address.

        This indicates the server's address.
        r   )r   r    r.   r9   s    r6   r   zPort.getHost#  s%     !t  Cdkk)BCCr7   c                |    | j                  ||       | j                  s| j                  s| j                          y y y r+   )handleAcceptr   rb   r   )r2   r   r   rG   s       r6   cbAcceptzPort.cbAccept+  s4    "c"""d&7&7MMO '8"r7   c           	     8   | j                   s| j                  ry|r;t        j                  dt        j
                  j                  |d      d|d       y|j                  j                  t        j                  t        t        j                  d| j                  j                                      t        j                   |j                  j                         |j"                        \  }}}|| j$                  k(  sJ d|d   v r,t'        |d   j)                  d      d	         }|d   |d	   d|f}d|d   v r,t'        |d   j)                  d      d	         }|d   |d	   d|f}| j*                  j-                   | j.                  d
g|       }||j                  j1                          y| j2                  }|d	z   | _        t5        |j                  | | j.                  d
g|  | j.                  d
g| || j6                        }	|j9                  |	       y)NFz#Could not accept new connection -- zunknown errorz ()r   %r   rR   r   T)r   rb   r$   r   r   r   r   newsktrr   r.   rw   r   r   r   r/   rD   get_accept_addrsrN   r   r   splitr   r   r   closer   r   r5   r   )
r2   r   rG   familylAddrrAddrscoper1   s	transports
             r6   r  zPort.handleAccept0  s   !2!2 GG??&&r?;RA  JJ!!!!(C!3!3!56
 $)#9#9#**:K:K:Msxx#X FE5T///// eAhE!HNN3/23q58Q6eAhE!HNN3/23q58Q6||112C$2C2CE2RE2RSH

  "  NN!"Q"JJ%D%%e4e4%D%%e4e4LL	 ''	2r7   c                   t        j                  | j                  |       }t        d| j                  dz   z        x|_        }| j                  j                  | j                  | j                        x|_
        }t        j                  | j                  j                         |j                         ||      }|r|t        k7  r| j                  ||       y y y )N      )rD   r   r  r>   r   rN   r5   r   r   r   r  acceptr.   r/   r   r  )r2   rG   rN   r  r   s        r6   r   zPort.doAcceptc  s    kk$--. $A):$;<<4"ll77
 	

V \\$++,,.sK"((b#& )2r7   )2   r   Nr   )"r   r   r   r   rb   r   r.   r   r   r   r   r	   r   r   r   r   __annotations__r   r-   r   r   r#   rX   r   CONNECTION_DONEr   stopListeningr  rZ   ri   r   r  r  r   r   r7   r6   r   r     s    ILMNNM##J&&LI &*O]) E4@ '6good6J6J&K ! #MF!>4D
1f'r7   r   )Ir   
__future__r   r   r.   r   typingr   r   r   zope.interfacer   r   twisted.internetr	   r
   r   r   r   twisted.internet.abstractr   r   twisted.internet.addressr   r   twisted.internet.interfacesr   twisted.internet.iocpreactorr   r   rD   "twisted.internet.iocpreactor.constr   r   r   r   r   'twisted.internet.iocpreactor.interfacesr   twisted.internet.protocolr   twisted.internet.tcpr   TCPConnectorr   r   r   r    r!   r"   twisted.pythonr#   r$   r%   twisted.internet._newtlsr&   
__startTLSr}   ImportError$twisted.internet.iocpreactor.reactorr'   WSAECONNREFUSEDWSAENETUNREACHr   ITCPTransportISystemHandler,   r)   ITLSTransportr   r   IListeningPortr   r   r7   r6   <module>r:     s[   #    1 1 7 D D > = 1 G  E .   1 0? I@ e33u33 z779Q9QRx$$m^ x Sxv J
 8 89V'_nj V'r@Z @FR R
 Z&&'Q'=) Q' (Q'e  Is   
E EE