o
    >hkO                     @  s  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 zddl6m7Z8 W n e9y   dZ:Y nw e8Z:erddl;m<Z< e ej=e"ej>iZ?ee&ej@ejAG dd dejBe1e,ZCe:dureeCejD G dd de-e.eCZEG dd deCZFG dd de+Z*eejGG dd de1eZHdS )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                   @  s   e Zd ZdZdZd/ddZdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd ZedurFd0dd Zd!d" Zd#d$ Zd/d%d&Zd'd( Zd)d* Zd+d, Zd-d. ZdS )1
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                 C  s&   t j| | || _|j| _|| _d S N)r   
FileHandle__init__socketfilenogetFileHandleprotocol)selfsockprotoreactor r3   /var/www/vedio/testing/chatpythonscript.ninositsolution.com/env/lib/python3.10/site-packages/twisted/internet/iocpreactor/tcp.pyr*   F   s   
zConnection.__init__c                 C     | j S r(   )r+   r/   r3   r3   r4   	getHandleL   s   zConnection.getHandlec                 C  s@   t |trnt |trt|}ntdt| | j| dS )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typer.   dataReceived)r/   rbufferr3   r3   r4   r=   O   s   


zConnection.dataReceivedc                 C  s   t |  ||S r(   )_iocprecvr-   )r/   bufflistevtr3   r3   r4   readFromHandle^   s   zConnection.readFromHandlec                 C  s(   t |}t|  |d| 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   )
memoryviewr?   sendr-   
SEND_LIMITtobytes)r/   buffrB   	writeViewr3   r3   r4   writeToHandlea   s   zConnection.writeToHandlec                 C  sx   z| j d W n	 ty   Y nw t| jd }|r:z|  W d S  ty9   t	 }t
  | | Y d S w d S )N   )r+   shutdownOSErrorr   IHalfCloseableProtocolr.   writeConnectionLostBaseExceptionr"   Failurer#   errconnectionLost)r/   pfr3   r3   r4   _closeWriteConnectionk   s   z Connection._closeWriteConnectionc                 C  sZ   t | jd }|r&z|  W d S  ty%   t  | t	  Y d S w | | d S r(   )
r   rN   r.   readConnectionLostrP   r#   rR   rS   r"   rQ   )r/   reasonrT   r3   r3   r4   rW   y   s   zConnection.readConnectionLostc                 C  sX   | j rd S tj| | |d u p|tj }| | | j}| `| `	| `
|| d S r(   )disconnectedr   r)   rS   checkr
   ConnectionAborted_closeSocketr.   r+   r-   )r/   rX   isCleanr.   r3   r3   r4   rS      s   
zConnection.connectionLostc                 C  r5   )zN
        Return the prefix to log with when I own the logging thread.
        )logstrr6   r3   r3   r4   	logPrefix      zConnection.logPrefixc                 C     t | jtjtjS r(   )boolr+   
getsockoptIPPROTO_TCPTCP_NODELAYr6   r3   r3   r4   getTcpNoDelay      zConnection.getTcpNoDelayc                 C     | j t jt j| d S r(   )r+   
setsockoptrd   re   r/   enabledr3   r3   r4   setTcpNoDelay      zConnection.setTcpNoDelayc                 C  ra   r(   )rb   r+   rc   
SOL_SOCKETSO_KEEPALIVEr6   r3   r3   r4   getTcpKeepAlive   rg   zConnection.getTcpKeepAlivec                 C  rh   r(   )r+   ri   rn   ro   rj   r3   r3   r4   setTcpKeepAlive   rm   zConnection.setTcpKeepAliveTc                 C  s   t | ||tj dS )z9
            @see: L{ITLSTransport.startTLS}
            N)	_startTLSr   r)   )r/   contextFactorynormalr3   r3   r4   r%      s   zConnection.startTLSc                 C  2   | j rdS | jr| j| dS tj| | dS )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)rY   TLSr.   writer   r)   )r/   datar3   r3   r4   rw      
   zConnection.writec                 C  ru   )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)rY   rv   r.   writeSequencer   r)   )r/   iovecr3   r3   r4   rz      ry   zConnection.writeSequencec                 C  s:   | j r| jr| js| j  dS dS dS tj| | dS )z
        Close the underlying handle or, if TLS has been started, first shut it
        down.

        @see: L{twisted.internet.interfaces.ITransport.loseConnection}
        N)rv   	connecteddisconnectingr.   loseConnectionr   r)   )r/   rX   r3   r3   r4   r~      s
   zConnection.loseConnectionc                 C  s,   | j r| j|| dS tj| || dS )zc
        Register a producer.

        If TLS is enabled, the TLS connection handles this.
        N)rv   r.   registerProducerr   r)   )r/   producer	streamingr3   r3   r4   r      s   zConnection.registerProducerc                 C  s$   | j r
| j  dS tj|  dS )ze
        Unregister a producer.

        If TLS is enabled, the TLS connection handles this.
        N)rv   r.   unregisterProducerr   r)   r6   r3   r3   r4   r      s   zConnection.unregisterProducerc                 C     d S r(   r3   r6   r3   r3   r4   getHost      zConnection.getHostc                 C  r   r(   r3   r6   r3   r3   r4   getPeer   r   zConnection.getPeerr(   )T)__name__
__module____qualname____doc__rv   r*   r7   r=   rC   rJ   rV   rW   rS   r_   rf   rl   rp   rq   rr   r%   rw   rz   r~   r   r   r   r   r3   r3   r3   r4   r'   <   s2    



r'   c                   @  sT   e Zd ZdZejZejZdZ	e
Zdd Zdd Zdd Zd	d
 Zdd Zdd ZdS )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                 C  s*   |d u rd}|| _ t| ||||| d S )N) r   )r2   r   r*   )r/   hostportbindAddress	connectorr2   r3   r3   r4   r*   	  s   zClient.__init__c                 C  s   | j | j| jS )zd
        Create a socket registered with the IOCP reactor.

        @see: L{_BaseTCPClient}
        )r2   createSocketaddressFamily
socketTyper6   r3   r3   r4   createInternetSocket  s   zClient.createInternetSocketc                 C  s   | ` | `dS )z
        Clean up potentially circular references to the socket and to its
        C{getFileHandle} method.

        @see: L{_BaseBaseClient}
        N)r+   r-   r6   r3   r3   r4   _collectSocketDetails  s   zClient._collectSocketDetailsc                 C  s   | j |  dS )z^
        Remove the active handle from the reactor.

        @see: L{_BaseBaseClient}
        N)r2   removeActiveHandler6   r3   r3   r4   _stopReadingAndWriting!  s   zClient._stopReadingAndWritingc              	   C  s   |rt ||}| t|tj|df d S | jtj	t
td| j  | j|  | _d| _| | j}|d | _| jd u rOt | _|   d S | j|  |   d S )NzUnknown errorPTz,client)connectExErrorsgetfailIfNotConnectedr
   getConnectErrorerrno	errorcoder+   ri   rn   r   structpackr,   r   buildProtocolr   r.   r|   _getLogPrefixr^   r   r~   makeConnectionstartReading)r/   rcrx   rB   r_   r3   r3   r4   	cbConnect)  s&   

zClient.cbConnectc                 C  sn   t | dsd S tjsJ | j|  t| j| }t| j	 | j
|}|r3|tkr5| |d| d S d S d S )Nr   r   )hasattrr?   have_connectexr2   addActiveHandleEventr   connectr+   r,   realAddressr   )r/   rB   r   r3   r3   r4   	doConnectG  s   

zClient.doConnectN)r   r   r   r   r+   AF_INETr   SOCK_STREAMr   _tlsClientDefaultr'   _commonConnectionr*   r   r   r   r   r   r3   r3   r3   r4   r      s    	r   c                   @  s8   e Zd ZdZdZdddZdddZdd Zdd ZdS )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.
    Fr0   socket.socketr.   r   
clientAddrUnion[IPv4Address, IPv6Address]
serverAddr	sessionnointr2   r&   c                 C  sv   t | ||| || _|| _|| _| | j}| d| d| jj | _d	| jj
j| j| jj| _d| _|   dS )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*   r   r   r   r   r.   r   r^   format	__class__r   r   repstrr|   r   )r/   r0   r.   r   r   r   r2   r_   r3   r3   r4   r*   c  s   zServer.__init__returnstrc                 C  r5   )z=
        A string representation of this connection.
        )r   r6   r3   r3   r4   __repr__  r`   zServer.__repr__c                 C  r5   )zW
        Returns an IPv4Address.

        This indicates the server's address.
        )r   r6   r3   r3   r4   r        zServer.getHostc                 C  r5   )zW
        Returns an IPv4Address.

        This indicates the client's address.
        )r   r6   r3   r3   r4   r     r   zServer.getPeerN)r0   r   r.   r   r   r   r   r   r   r   r2   r&   r   r   )	r   r   r   r   r   r*   r   r   r   r3   r3   r3   r4   r   U  s    

r   c                   @  s   e Zd Zdd ZdS )r   c                 C  s   t | j| j| j| | jS r(   )r   r   r   r   r2   r6   r3   r3   r4   _makeTransport  rm   zConnector._makeTransportN)r   r   r   r   r3   r3   r3   r4   r     s    r   c                   @  s   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	d
Zd"ddZdd ZeejfddZeZdd Zdd Zdd Zdd Zdd Zdd Z dd  Z!dS )#PortFr   NzOptional[int]_realPortNumberTCP2   r   c                 C  s>   || _ || _|| _|| _|| _t|rtj| _t	j
| _d S d S r(   )r   factorybacklog	interfacer2   r   r+   AF_INET6r   r   r   _addressType)r/   r   r   r   r   r2   r3   r3   r4   r*     s   zPort.__init__r   r   c                 C  s2   | j d urd| j| jj| j S d| j| jjS )Nz<{} of {} on {}>z<{} of {} (not listening)>)r   r   r   r   r6   r3   r3   r4   r     s   
zPort.__repr__c              
   C  s   z$| j | j| j}| jtjkrt| j| j}n| j| jf}|	| W n t
y9 } z	t| j| j|d }~ww t| | _| d | _td| | j| jf  | j  || j d| _d| _| j |  || _| jj| _|   d S )NrK   z%s starting on %sTF)r2   r   r   r   r+   r   r    r   r   bindrM   r
   CannotListenErrorr?   
maxAddrLenr,   addrLengetsocknamer   r#   msgr   r   doStartlistenr   r|   rY   r   r-   doAccept)r/   sktaddrler3   r3   r4   startListening  s2   

zPort.startListeningc                 C  s2   d| _ | jrt | _| jd| j| | jS dS )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deferredr2   	callLaterrS   )r/   connDoner3   r3   r4   r~     s   
zPort.loseConnectionc                 C  s    t d| j d| j d dS )z.
        Log message for closing port
        (z Port z Closed)N)r#   r   _typer   r6   r3   r3   r4   _logConnectionLostMsg  s    zPort._logConnectionLostMsgc                 C  s   |    d| _d}t| dr| j}| `d| _| j|  d| _| d | `	| `
z| j  W n tyH   d| _|durG|t  Y dS  w d| _|durW|d dS dS )z'
        Cleans up the socket.
        Nr   TF)r   r   r   r   rY   r2   r   r|   r\   r+   r-   r   doStoprP   r}   errbackr"   rQ   callback)r/   rX   dr3   r3   r4   rS     s0   

zPort.connectionLostc                 C  s   t | jjS )zK
        Returns the name of my class, to prefix log entries with.
        )r$   qualr   r   r6   r3   r3   r4   r_     s   zPort.logPrefixc                 C  s   | j dgt| jR  S )zf
        Returns an IPv4Address or IPv6Address.

        This indicates the server's address.
        r   )r   r   r+   r6   r3   r3   r4   r   #  s   zPort.getHostc                 C  s,   |  || | js| js|   d S d S d S r(   )handleAcceptr}   rY   r   )r/   r   rx   rB   r3   r3   r4   cbAccept+  s   zPort.cbAcceptc           
   	   C  sh  | j s| jrdS |rtdtj|d|f  dS |jt	j
ttd| j	  t|j |j\}}}|| jks>J d|d v rYt|d dd }|d |d d|f}d|d v rtt|d dd }|d |d d|f}| j| jdg|R  }|d u r|j  d	S | j}|d | _t|j|| jdg|R  | jdg|R  || j}	||	 d	S )
NFz*Could not accept new connection -- %s (%s)zunknown errorr   %r   rK   r   T)r}   rY   r#   r   r   r   r   newsktri   r+   rn   r   r   r   r,   r?   get_accept_addrsrH   r   r   splitr   r   r   closer   r   r2   r   )
r/   r   rB   familylAddrrAddrscoper.   s	transportr3   r3   r4   r   0  sL   


zPort.handleAcceptc                 C  s|   t | j| }td| jd   |_}| j| j| j	 |_
}t | j | ||}|r:|tkr<| || d S d S d S )N      )r?   r   r   r:   r   rH   r2   r   r   r   r   acceptr+   r,   r   r   )r/   rB   rH   r   r   r3   r3   r4   r   c  s   
zPort.doAccept)r   r   Nr   )"r   r   r   r|   rY   r}   r+   r   r   r   r   r   r   r   r   r   __annotations__r   r*   r   r   r"   rQ   r   CONNECTION_DONEr~   stopListeningr   rS   r_   r   r   r   r   r3   r3   r3   r4   r     s,   
 


 3r   )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   r?   "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%   
__startTLSImportErrorrr   $twisted.internet.iocpreactor.reactorr&   WSAECONNREFUSEDWSAENETUNREACHr   ITCPTransportISystemHandler)   r'   ITLSTransportr   r   IListeningPortr   r3   r3   r3   r4   <module>   sL   $	 <YC