File: //lib/python3/dist-packages/twisted/internet/__pycache__/tcp.cpython-38.pyc
U
^h�b�� � @ s" d Z ddlZddlZddlZddlZddlmZmZmZm Z m
Z
ddlmZm
Z
ddlZddlmZmZmZmZ ddlmZmZmZ ddlmZmZ ddlmZ dd lmZ z$dd
lm Z!m"Z#m$Z% ddlm&Z& W nD e'k
�r eZ&G dd
� d
�Z#G dd� d�Z!G dd� d�Z%Y nX edk�rte(� Z)ddl*m+Z,m-Z.m/Z0m1Z2m3Z4m5Z6m7Z8 e(� Z9e(� Z:e8Z;ddl*m<Z= ddl>m?Z@ n�ddl*m)Z) ddl*m0Z0 ddl*m8Z8 ddl*m.Z. ddl*m,Z, ddl*m2Z2 ddl*m6Z6 ddl*m4Z4 ddl*m9Z9 ddl*m:Z: dd l*m;Z; dd!l*m=Z= dd"lm@Z@ dd#l*mAZA dd$lBmCZCmDZDmEZEmFZFmGZGmHZH dd%lImJZJ dd&lKm
Z
dd'lLmMZM dd(lmNZNmOZOmPZP dd)lQmRZR eSed*d�ZTd+d,� ZUd-d.� ZVd/d0� ZWG d1d2� d2�ZXG d3d4� d4�ZYe
e&ee�G d5d6� d6e#eCjZeXeY��Z[G d7d8� d8�Z\G d9d:� d:e\e!e[�Z]ej^eTB Z_d;d<� Z`G d=d>� d>�ZaG d?d@� d@eae]�ZbG dAdB� dBe%e[�ZcG dCdD� dDe�ZdG dEdF� dFe
�Zee
ed�ejfdGdH�G dIdJ� dJ���Zge
ed�G dKdL� dL��Zhedk�r�eh� ZinegdMdN� �Zie4e6e9e:e=fZjejfdGdH�G dOdP� dP��ZkdQdR� Zle
e�G dSdT� dTeEjmeX��ZnG dUdV� dVeEjo�ZpdS )Wzt
Various asynchronous TCP/IP classes.
End users shouldn't use this module directly - use the reactor APIs instead.
� N)�Callable�ClassVar�List�Optional�Protocol)� Interface�implementer)�IHalfCloseableProtocol�IListeningPort�
ISystemHandle�
ITCPTransport)�ILogObserver�LogEvent�Logger)� deprecate�versions)�
lazyByteSlice)�platformType)�ClientMixin�ConnectionMixin�ServerMixin)�
ITLSTransportc @ s e Zd ZdZdS )�_TLSConnectionMixinFN)�__name__�
__module__�__qualname__�TLS� r r �6/usr/lib/python3/dist-packages/twisted/internet/tcp.pyr / s r c @ s e Zd ZdS )�_TLSClientMixinN�r r r r r r r r 2 s r c @ s e Zd ZdS )�_TLSServerMixinNr r r r r r! 5 s r! �win32)�WSAEALREADY�WSAEINPROGRESS� WSAEINVAL�
WSAEISCONN� WSAEMFILE�
WSAENOBUFS�WSAEWOULDBLOCK)�
WSAECONNRESET)�formatError)�EPERM)�EINVAL)�EWOULDBLOCK)�EINPROGRESS)�EALREADY)�EISCONN)�ENOBUFS)�EMFILE)�ENFILE)�ENOMEM)�EAGAIN)�ECONNABORTED)�strerror)� errorcode)�abstract�address�base�error�fdesc�main)�CannotListenError)r )�
deferLater)�failure�log�reflect)�untilConcludes�AI_NUMERICSERVc C sN t | �dkr>t�| tjtjB �d }t|gt| dd� � �S | dd� S dS )ai
Return a 2-tuple of socket IP and port for IPv4 and a 4-tuple of
socket IP, port, flowInfo, and scopeID for IPv6. For IPv6, it
returns the interface portion (the part after the %) as a part of
the IPv6 address, which Python 3.7+ does not include.
@param addr: A 2-tuple for IPv4 information or a 4-tuple for IPv6
information.
� r � N� )�len�socket�getnameinfo�NI_NUMERICHOST�NI_NUMERICSERV�tuple�list)�addr�hostr r r �_getrealnamem s
�rS c C s t | �� �S �z
See L{_getrealname}.
)rS �getpeername��sktr r r �_getpeername� s rX c C s t | �� �S rT )rS �getsocknamerV r r r �_getsockname� s rZ c @ s e Zd ZdZdZdd� ZdS )�
_SocketCloserz�
@ivar _shouldShutdown: Set to C{True} if C{shutdown} should be called
before calling C{close} on the underlying socket.
@type _shouldShutdown: C{bool}
Tc C sz | j }z8|r| jr<|�d� n| j �t jt jt�ddd�� W n tk
rR Y nX z|� � W n tk
rt Y nX d S )NrI ZiirH r )
rK �_shouldShutdown�shutdown�
setsockopt�
SOL_SOCKET� SO_LINGER�structZpack�OSError�close)�selfZorderlyrW r r r �_closeSocket� s �z_SocketCloser._closeSocketN)r r r �__doc__r\ re r r r r r[ � s r[ c @ s e Zd ZdZdZdd� ZdS )�_AbortingMixinz�
Common implementation of C{abortConnection}.
@ivar _aborting: Set to C{True} when C{abortConnection} is called.
@type _aborting: C{bool}
Fc C sZ | j s| jrdS d| _| �� | �� dd� | _dd� | _| j�d| jt �
t�� �� dS )zf
Aborts the connection immediately, dropping any buffered data.
@since: 11.1
NTc _ s d S �Nr ��args�kwargsr r r �<lambda>� � z0_AbortingMixin.abortConnection.<locals>.<lambda>c _ s d S rh r ri r r r rl � rm r )
�disconnected� _aborting�stopReading�stopWriting�doRead�doWrite�reactor� callLater�connectionLostrB �Failurer= �ConnectionAborted�rd r r r �abortConnection� s
�z_AbortingMixin.abortConnectionN)r r r rf ro rz r r r r rg � s rg c @ s~ e Zd ZdZddd�Zdd� Zdd� Zd d
� Zdd� Zd
d� Z dd� Z
dd� ZdZdd� Z
dd� Zdd� Zdd� Zdd� ZdS )�
Connectiona
Superclass of all socket-based FileDescriptors.
This is an abstract superclass of all objects which represent a TCP/IP
connection based socket.
@ivar logstr: prefix used when logging events related to this connection.
@type logstr: C{str}
Nc C s4 t jj| |d� || _| j�d� |j| _|| _d S )N�rt r )r: �FileDescriptor�__init__rK �setblocking�fileno�protocol)rd rW r� rt r r r r~ � s
zConnection.__init__c C s | j S )z&Return the socket for this connection.)rK ry r r r � getHandle� s zConnection.getHandlec
C sf z| j �| j�}W nH tk
rZ } z*|jd tkr<W Y �dS tj W Y �S W 5 d}~X Y nX | �|�S )a\ Calls self.protocol.dataReceived with all available data.
This reads up to self.bufferSize bytes of data from its socket, then
calls self.dataReceived(data) to process it. If the connection is not
lost through an error in the physical recv(), this function will return
the result of the dataReceived call.
r N) rK �recvZ
bufferSizerb rj r. r? �CONNECTION_LOST�
_dataReceived)rd �data�ser r r rr � s
zConnection.doReadc C sV |s
t jS | j�|�}|d k rR| jj}d}tj|t�dddd�|d�}t�||� |S )NzPReturning a value other than None from %(fqpn)s is deprecated since %(version)s.�Twisted� r )�format) r? �CONNECTION_DONEr� ZdataReceivedr �getDeprecationWarningStringr �Version�warnAboutFunction)rd r� Zrval�offenderZ
warningFormat�
warningStringr r r r� � s � �zConnection._dataReceivedc
C sp t |d| j�}zt| jj|�W S tk
rj } z.|jd ttfkrLW Y �dS t j
W Y �S W 5 d}~X Y nX dS )a
Write as much as possible of the given data to this TCP connection.
This sends up to C{self.SEND_LIMIT} bytes from C{data}. If the
connection is lost, an exception is returned. Otherwise, the number
of bytes successfully written is returned.
r N)r Z
SEND_LIMITrE rK �sendrb rj r. r2 r? r� )rd r� ZlimitedDatar� r r r �
writeSomeData s
zConnection.writeSomeDatac C sv z| j �d� W n tk
r$ Y nX t| jd �}|rrz|�� W n. tk
rp t�� }t �
� | �|� Y nX d S �NrH )rK r] rb r r� ZwriteConnectionLost�
BaseExceptionrB rw rC �errrv )rd �p�fr r r �_closeWriteConnection s z Connection._closeWriteConnectionc C sX t | jd �}|rJz|�� W qT tk
rF t�� | �t�� � Y qTX n
| �|� d S rh ) r r� �readConnectionLostr� rC r� rv rB rw )rd �reasonr� r r r r� + s zConnection.readConnectionLostc C sP t | d�sdS tj�| |� | �|�tj� � | j}| `| ` | `
|�|� dS )z-See abstract.FileDescriptor.connectionLost().rK N)�hasattrr: r} rv re Zcheckr= rx r� rK r� )rd r� r� r r r rv 6 s
zConnection.connectionLostZ
Uninitializedc C s | j S )z<Return the prefix to log with when I own the logging thread.)�logstrry r r r � logPrefixI s zConnection.logPrefixc C s t | j�tjtj��S rh )�boolrK �
getsockopt�IPPROTO_TCP�TCP_NODELAYry r r r �
getTcpNoDelayM s zConnection.getTcpNoDelayc C s | j �t jt j|� d S rh )rK r^ r� r� �rd Zenabledr r r �
setTcpNoDelayP s zConnection.setTcpNoDelayc C s t | j�tjtj��S rh )r� rK r� r_ �SO_KEEPALIVEry r r r �getTcpKeepAliveS s zConnection.getTcpKeepAlivec C s | j �t jt j|� d S rh )rK r^ r_ r� r� r r r �setTcpKeepAliveV s zConnection.setTcpKeepAlive)N)r r r rf r~ r� rr r� r� r� r� rv r� r� r� r� r� r� r r r r r{ � s
r{ c @ sL e Zd ZdZejZejZdd� Z dd� Z
dd� Zdd � Zd
d� Z
dd
� ZdS )�_BaseBaseClienta�
Code shared with other (non-POSIX) reactors for management of general
outgoing connections.
Requirements upon subclasses are documented as instance variables rather
than abstract methods, in order to avoid MRO confusion, since this base is
mixed in to unfortunately weird and distinctive multiple-inheritance
hierarchies and many of these attributes are provided by peer classes
rather than descendant classes in those hierarchies.
@ivar addressFamily: The address family constant (C{socket.AF_INET},
C{socket.AF_INET6}, C{socket.AF_UNIX}) of the underlying socket of this
client connection.
@type addressFamily: C{int}
@ivar socketType: The socket type constant (C{socket.SOCK_STREAM} or
C{socket.SOCK_DGRAM}) of the underlying socket.
@type socketType: C{int}
@ivar _requiresResolution: A flag indicating whether the address of this
client will require name resolution. C{True} if the hostname of said
address indicates a name that must be resolved by hostname lookup,
C{False} if it indicates an IP address literal.
@type _requiresResolution: C{bool}
@cvar _commonConnection: Subclasses must provide this attribute, which
indicates the L{Connection}-alike class to invoke C{__init__} and
C{connectionLost} on.
@type _commonConnection: C{type}
@ivar _stopReadingAndWriting: Subclasses must implement in order to remove
this transport from its reactor's notifications in response to a
terminated connection attempt.
@type _stopReadingAndWriting: 0-argument callable returning L{None}
@ivar _closeSocket: Subclasses must implement in order to close the socket
in response to a terminated connection attempt.
@type _closeSocket: 1-argument callable; see L{_SocketCloser._closeSocket}
@ivar _collectSocketDetails: Clean up references to the attached socket in
its underlying OS resource (such as a file descriptor or file handle),
as part of post connection-failure cleanup.
@type _collectSocketDetails: 0-argument callable returning L{None}.
@ivar reactor: The class pointed to by C{_commonConnection} should set this
attribute in its constructor.
@type reactor: L{twisted.internet.interfaces.IReactorTime},
L{twisted.internet.interfaces.IReactorCore},
L{twisted.internet.interfaces.IReactorFDSet}
c C s8 |r$| j �| |d|� |�d|� n|�d| j|� dS )ax
Called by subclasses to continue to the stage of initialization where
the socket connect attempt is made.
@param whenDone: A 0-argument callable to invoke once the connection is
set up. This is L{None} if the connection could not be prepared
due to a previous error.
@param skt: The socket object to use to perform the connection.
@type skt: C{socket._socketobject}
@param error: The error to fail the connection with.
@param reactor: The reactor to use for this client.
@type reactor: L{twisted.internet.interfaces.IReactorTime}
Nr )�_commonConnectionr~ ru �failIfNotConnected)rd �whenDonerW r= rt r r r �_finishInit� s z_BaseBaseClient._finishInitc sL � j r<� j�� jd �}|�� fdd�� |�� j� j� n� �� j� dS )a�
Resolve the name that was passed to this L{_BaseBaseClient}, if
necessary, and then move on to attempting the connection once an
address has been determined. (The connection will be attempted
immediately within this function if either name resolution can be
synchronous or the address was an IP address literal.)
@note: You don't want to call this method from outside, as it won't do
anything useful; it's just part of the connection bootstrapping
process. Also, although this method is on L{_BaseBaseClient} for
historical reasons, it's not used anywhere except for L{Client}
itself.
@return: L{None}
r c s | f� j dd � S r� )rQ )�nry r r rl � rm z0_BaseBaseClient.resolveAddress.<locals>.<lambda>N)�_requiresResolutionrt ZresolverQ ZaddCallbackZaddCallbacks�_setRealAddressr� )rd �dr ry r �resolveAddress� s
z_BaseBaseClient.resolveAddressc C sT t |�dkrBt�|tjtjB �d }t|gt|dd� � �| _n|| _| �� dS )a�
Set the resolved address of this L{_BaseBaseClient} and initiate the
connection attempt.
@param address: Depending on whether this is an IPv4 or IPv6 connection
attempt, a 2-tuple of C{(host, port)} or a 4-tuple of C{(host,
port, flow, scope)}. At this point it is a fully resolved address,
and the 'host' portion will always be an IP address, not a DNS
name.
rG r rH N) rJ rK rL rM rN rO rP �realAddress� doConnect)rd r; �hostnamer r r r� � s
��z_BaseBaseClient._setRealAddressc C sh | j s| jst| d�sdS | �� z| �d� W n tk
rD Y n
X | �� | j�t �
|�� | `dS )z�
Generic method called when the attempts to connect failed. It basically
cleans everything it can: call connectionFailed, stop read and write,
delete socket related members.
� connectorNT)� connectedrn r� �_stopReadingAndWritingre �AttributeError�_collectSocketDetailsr� ZconnectionFailedrB rw )rd r� r r r r� � s z"_BaseBaseClient.failIfNotConnectedc C s | � t�� � dS )z�
If a connection attempt is still outstanding (i.e. no connection is
yet established), immediately stop attempting to connect.
N)r� r= � UserErrorry r r r �stopConnecting� s z_BaseBaseClient.stopConnectingc C s8 | j s| �tj|d�� n| j�| |� | j�|� dS )a�
Invoked by lower-level logic when it's time to clean the socket up.
Depending on the state of the connection, either inform the attached
L{Connector} that the connection attempt has failed, or inform the
connected L{IProtocol} that the established connection has been lost.
@param reason: the reason that the connection was terminated
@type reason: L{Failure}
��stringN)r� r� r= �ConnectErrorr� rv r� �rd r� r r r rv � s
z_BaseBaseClient.connectionLostN)r r r rf rK �AF_INET�
addressFamily�SOCK_STREAM�
socketTyper� r� r� r� r� rv r r r r r� Z s 3r� c @ s@ e Zd ZdZeZeZdd� Zdd� Zdd� Z dd � Z
d
d� ZdS )
�
BaseClienta�
A base class for client TCP (and similar) sockets.
@ivar realAddress: The address object that will be used for socket.connect;
this address is an address tuple (the number of elements dependent upon
the address family) which does not contain any names which need to be
resolved.
@type realAddress: C{tuple}
@ivar _base: L{Connection}, which is the base class of this class which has
all of the useful file descriptor methods. This is used by
L{_TLSServerMixin} to call the right methods to directly manipulate the
transport, as is necessary for writing TLS-encrypted bytes (whereas
those methods on L{Server} will go through another layer of TLS if it
has been enabled).
c C s t | d�r| �� | �� dS )z�
Implement the POSIX-ish (i.e.
L{twisted.internet.interfaces.IReactorFDSet}) method of detaching this
socket from the reactor for L{_BaseBaseClient}.
rt N)r� rp rq ry r r r r� s
z!BaseClient._stopReadingAndWritingc C s | ` | `dS )zn
Clean up references to the socket and its file descriptor.
@see: L{_BaseBaseClient}
N)rK r� ry r r r r� s z BaseClient._collectSocketDetailsc C s, t � | j| j�}|�d� t�|�� � |S )zc(internal) Create a non-blocking socket using
self.addressFamily, self.socketType.
r )rK r� r� r r>