o 5@g@sdZddlZddlZddlZddlZddlmZmZmZm Z m Z ddl m Z m Z ddlZddlmZmZmZmZddlmZmZmZddlmZmZddlmZdd lmZzdd lm Z!m"Z#m$Z%dd lm&Z&Wn e'ye Z&Gd d d Z#GdddZ!GdddZ%Ynwedkre(Z)ddl*m+Z,m-Z.m/Z0m1Z2m3Z4m5Z6m7Z8e(Z9e(Z:e8Z;ddl*mm?Z@nNddl*m)Z)ddl*m0Z0ddl*m8Z8ddl*m.Z.ddl*m,Z,ddl*m2Z2ddl*m6Z6ddl*m4Z4ddl*m9Z9ddl*m:Z:dd l*m;Z;dd!l*m=Z=dd"lm@Z@dd#l*mAZAdd$lBmCZCmDZDmEZEmFZFmGZGmHZHdd%lImJZJdd&lKm Z dd'lLmMZMdd(lmNZNmOZOmPZPdd)lQmRZReSed*dZTd+d,ZUd-d.ZVd/d0ZWGd1d2d2ZXGd3d4d4ZYe e&eeGd5d6d6e#eCjZeXeYZ[Gd7d8d8Z\Gd9d:d:e\e!e[Z]ej^eTBZ_d;d<Z`Gd=d>d>ZaGd?d@d@eae]ZbGdAdBdBe%e[ZcGdCdDdDe ZdGdEdFdFe Zee edejfdGdHGdIdJdJZge edGdKdLdLZhedkrehZinegdMdNZie4e6e9e:e=fZjejfdGdHGdOdPdPZkdQdRZle eGdSdTdTeEjmeXZnGdUdVdVeEjoZpdS)Wzt Various asynchronous TCP/IP classes. End users shouldn't use this module directly - use the reactor APIs instead. N)CallableClassVarListOptionalProtocol) Interface implementer)IHalfCloseableProtocolIListeningPort ISystemHandle ITCPTransport) ILogObserverLogEventLogger) deprecateversions) lazyByteSlice) platformType) ClientMixinConnectionMixin ServerMixin) ITLSTransportc@eZdZdZdS)_TLSConnectionMixinFN)__name__ __module__ __qualname__TLSrr6/usr/lib/python3/dist-packages/twisted/internet/tcp.pyr/rc@ eZdZdS)_TLSClientMixinNrrrrrrrr"2r"c@r!)_TLSServerMixinNr#rrrrr%5r$r%win32) WSAEALREADYWSAEINPROGRESS WSAEINVAL WSAEISCONN WSAEMFILE WSAENOBUFSWSAEWOULDBLOCK) WSAECONNRESET) formatError)EPERM)EINVAL) EWOULDBLOCK) EINPROGRESS)EALREADY)EISCONN)ENOBUFS)EMFILE)ENFILE)ENOMEM)EAGAIN) ECONNABORTED)strerror) errorcode)abstractaddressbaseerrorfdescmain)CannotListenError)r) deferLater)failurelogreflect)untilConcludesAI_NUMERICSERVcCsJt|dkrt|tjtjBd}t|gt|ddS|ddS)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. rN)lensocket getnameinfoNI_NUMERICHOSTNI_NUMERICSERVtuplelist)addrhostrrr _getrealnamems  rWcC t|Sz See L{_getrealname}. )rW getpeernamesktrrr _getpeername r]cCrXrY)rW getsocknamer[rrr _getsocknamer^r`c@eZdZdZdZddZdS) _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 Csv|j}z|r|jr|dn|jtjtjtdddWn ty(Ynwz| WdSty:YdSw)NrMiirLr) rO_shouldShutdownshutdown setsockopt SOL_SOCKET SO_LINGERstructpackOSErrorclose)selforderlyr\rrr _closeSockets$   z_SocketCloser._closeSocketN)rrr__doc__rdrorrrrrbs rbc@ra)_AbortingMixinz Common implementation of C{abortConnection}. @ivar _aborting: Set to C{True} when C{abortConnection} is called. @type _aborting: C{bool} FcCsZ|js|jrdSd|_||dd|_dd|_|jd|jt t dS)zf Aborts the connection immediately, dropping any buffered data. @since: 11.1 NTc_dSNrargskwargsrrrz0_AbortingMixin.abortConnection..c_rrrsrrtrrrrwrxr) disconnected _aborting stopReading stopWritingdoReaddoWritereactor callLaterconnectionLostrFFailurerAConnectionAbortedrmrrrabortConnections   z_AbortingMixin.abortConnectionN)rrrrprzrrrrrrqs rqc@s~eZdZdZdddZddZddZd d Zd d Zd dZ ddZ ddZ dZ ddZ ddZddZddZddZdS) 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} NcCs4tjj||d||_|jd|j|_||_dS)Nrr)r>FileDescriptor__init__rO setblockingfilenoprotocol)rmr\rrrrrrs   zConnection.__init__cC|jS)z&Return the socket for this connection.)rOrrrr getHandlezConnection.getHandlec Csdz |j|j}Wn#ty,}z|jdtkrWYd}~dStjWYd}~Sd}~ww||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. rN) rOrecv bufferSizerkrur2rCCONNECTION_LOST _dataReceived)rmdataserrrr}s zConnection.doReadcCsV|stjS|j|}|dur)|jj}d}tj|tdddd|d}t|||S)NzPReturning a value other than None from %(fqpn)s is deprecated since %(version)s.Twisted r)format) rCCONNECTION_DONEr dataReceivedrgetDeprecationWarningStringrVersionwarnAboutFunction)rmrrvaloffender warningFormat warningStringrrrrs  zConnection._dataReceivedc Csjt|d|j}zt|jj|WSty4}z|jdttfvr'WYd}~dSt j WYd}~Sd}~ww)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. rN) r SEND_LIMITrIrOsendrkrur2r6rCr)rmr limitedDatarrrr writeSomeData s zConnection.writeSomeDatacCsvz|jdWn tyYnwt|jd}|r9z|WdSty8t}t | |YdSwdSNrL) rOrerkr rwriteConnectionLost BaseExceptionrFrrGerrr)rmpfrrr_closeWriteConnections   z Connection._closeWriteConnectioncCsXt|jd}|r%z|WdSty$t|tYdSw||dSrs) r rreadConnectionLostrrGrrrFr)rmreasonrrrrr+s  zConnection.readConnectionLostcCsPt|dsdStj||||tj |j}|`|` |` ||dS)z-See abstract.FileDescriptor.connectionLost().rON) hasattrr>rrrocheckrArrrOr)rmrrrrrr6s zConnection.connectionLost UninitializedcCr)z.N)_requiresResolutionrresolverU addCallback addCallbacks_setRealAddressr)rmdrrrresolveAddresss z_BaseBaseClient.resolveAddresscCsTt|dkr!t|tjtjBd}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. rKrrLN) rNrOrPrQrRrSrT realAddress doConnect)rmr?hostnamerrrrs   z_BaseBaseClient._setRealAddresscCsf|js |js t|ds dS|z|dWn ty!Ynw||jt ||`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) connectedryr_stopReadingAndWritingroAttributeError_collectSocketDetailsrconnectionFailedrFr)rmrrrrrs z"_BaseBaseClient.failIfNotConnectedcCs|tdS)z If a connection attempt is still outstanding (i.e. no connection is yet established), immediately stop attempting to connect. N)rrA UserErrorrrrrstopConnectingsz_BaseBaseClient.stopConnectingcCs:|js|tj|ddS|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)rrrA ConnectErrorrrrrmrrrrrs z_BaseBaseClient.connectionLostN)rrrrprOAF_INET addressFamily SOCK_STREAM socketTyperrrrrrrrrrrZs3 rc@s@eZdZdZeZeZddZddZddZ dd Z d d Z d S) 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). cCs"t|dr||dSdS)z Implement the POSIX-ish (i.e. L{twisted.internet.interfaces.IReactorFDSet}) method of detaching this socket from the reactor for L{_BaseBaseClient}. rN)rr{r|rrrrrs  z!BaseClient._stopReadingAndWritingcCs |`|`dS)zn Clean up references to the socket and its file descriptor. @see: L{_BaseBaseClient} N)rOrrrrrrs z BaseClient._collectSocketDetailscCs,t|j|j}|dt||S)zc(internal) Create a non-blocking socket using self.addressFamily, self.socketType. r)rOrrrrB_setCloseOnExecrrmsrrrcreateInternetSocket's zBaseClient.createInternetSocketc Cs|j|_|j|_t|dsdS|jtjtj}|r(|t |t |fdSz |j |j }WntyH}z |jd}WYd}~nd}~ww|rw|tkrPn'|tttfvs_|tkritdkri||dS|t |t |fdS|`|`|||dS)z Initiate the outgoing connection attempt. @note: Applications do not need to call this method; it will be invoked internally as part of L{IReactorTCP.connectTCP}. rNrr&)rr~r}rrOrrgSO_ERRORrrAgetConnectErrorr< connect_exrrkrur5r2r3r4r1r startReading startWritingr{r| _connectDone)rmr connectResultrrrrr0s>   zBaseClient.doConnectcCsd|j||_d|_||j}d||_|jdur&t|_|dS| |j |dS)a This is a hook for when a connection attempt has succeeded. Here, we build the protocol from the L{twisted.internet.protocol.ClientFactory} that was passed in, compute a log string, begin reading so as to send traffic to the newly built protocol, and finally hook up the protocol itself. This hook is overridden by L{ssl.Client} to initiate the TLS protocol. rLz %s,clientN) r buildProtocolgetPeerrr _getLogPrefixrrloseConnectionrmakeConnection)rmrrrrrhs     zBaseClient._connectDoneN) rrrrpr_baserrrrrrrrrrrs  8rcCst||dddtddS)av Resolve an IPv6 literal into an IPv6 address. This is necessary to resolve any embedded scope identifiers to the relevant C{sin6_scope_id} for use with C{socket.connect()}, C{socket.listen()}, or C{socket.bind()}; see U{RFC 3493 } for more information. @param ip: An IPv6 address literal. @type ip: C{str} @param port: A port number. @type port: C{int} @return: a 4-tuple of C{(host, port, flow, scope)}, suitable for use as an IPv6 address. @raise socket.gaierror: if either the IP or port is not numeric as it should be. rrK)rO getaddrinfo _NUMERIC_ONLY)ipportrrr _resolveIPv6src@s>eZdZdZejZd ddZddZddZ d e fd d Z dS) _BaseTCPClienta Code shared with other (non-POSIX) reactors for management of outgoing TCP connections (both TCPv4 and TCPv6). @note: In order to be functional, this class must be mixed into the same hierarchy as L{_BaseBaseClient}. It would subclass L{_BaseBaseClient} directly, but the class hierarchy here is divided in strange ways out of the need to share code along multiple axes; specifically, with the IOCP reactor and also with UNIX clients in other reactors. @ivar _addressType: The Twisted _IPAddress implementation for this client @type _addressType: L{IPv4Address} or L{IPv6Address} @ivar connector: The L{Connector} which is driving this L{_BaseTCPClient}'s connection attempt. @ivar addr: The address that this socket will be connecting to. @type addr: If IPv4, a 2-C{tuple} of C{(str host, int port)}. If IPv6, a 4-C{tuple} of (C{str host, int port, int ignored, int scope}). @ivar createInternetSocket: Subclasses must implement this as a method to create a python socket object of the appropriate address family and socket type. @type createInternetSocket: 0-argument callable returning C{socket._socketobject}. Nc Cs>||_||f|_|j}d}d}t|rd|_nt|r/d|_t|||_tj |_ t j |_ nd|_z|}Wn tyX} zt| jd| jd}d}WYd} ~ nd} ~ ww|r|durzt|drlt|} n|} || Wn ty} zt| jd| jd}d}WYd} ~ nd} ~ ww|||||dS)NFTrrL)rrUrr> isIPAddressr isIPv6AddressrrOAF_INET6rr? IPv6Address _addressTyperrkrAConnectBindErrorrubindr) rmrVr bindAddressrrrrr\rbindinforrrrs@        z_BaseTCPClient.__init__cCs|jdgt|jRS)z~ Returns an L{IPv4Address} or L{IPv6Address}. This indicates the address from which I am connecting. TCP)rr`rOrrrrgetHostsz_BaseTCPClient.getHostcC|jdg|jRS)zz Returns an L{IPv4Address} or L{IPv6Address}. This indicates the address that I am connected to. r)rrrrrrrz_BaseTCPClient.getPeerreturncCs&d|jd|jdt|dd}|S)N) __class__rUidrrrr__repr__s"z_BaseTCPClient.__repr__rs) rrrrpr? IPv4Addressrrrrstrrrrrrrs #rc@r)Clientz A transport for a TCP protocol; either TCPv4 or TCPv6. Do not create these directly; use L{IReactorTCP.connectTCP}. N)rrrrprrrrrr rc@sLeZdZdZeZejZddZ de fddZ e ddZ d d Zd d Zd S)Servera< Serverside socket-stream connection class. This is a serverside network connection transport; a socket which came from an accept() on a server. @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). cCst||||t|dkrtj|_||_||_||_|d|_ | |j }|d|d|j |_ |jdurEd |j jj|j|jj|_|d|_dS)a  Server(sock, protocol, client, server, sessionno) Initialize it 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. rMr,N<{} #{} on {}>rL)rrrNr?rrserverclient sessionnorrrrrr r_realPortNumberrepstrrr)rmsockrrrrrrrrrrs"     zServer.__init__rcCr)z= A string representation of this connection. )rrrrrr,szServer.__repr__c Cstj}|tjkr tj}t||tj}t|}|dg|R}|d} | |} | dur4| dS||| |d|d|} d | j j j| j| | _| | | S)a Create a new L{Server} based on an existing connected I{SOCK_STREAM} socket. Arguments are the same as to L{Server.__init__}, except where noted. @param fileDescriptor: An integer file descriptor associated with a connected socket. The socket must be in non-blocking mode. Any additional attributes desired, such as I{FD_CLOEXEC}, must also be set already. @param addressFamily: The address family (sometimes called I{domain}) of the existing socket. For example, L{socket.AF_INET}. @return: A new instance of C{cls} wrapping the socket given by C{fileDescriptor}. rrLNr)r?rrOrrfromfdrr]r_rrlrrr rrrr) clsfileDescriptorrfactoryr addressTyper\rU protocolAddr localPortrrmrrr_fromConnectedSocket2s&    zServer._fromConnectedSocketcCt|j}|jdg|RS)zl Returns an L{IPv4Address} or L{IPv6Address}. This indicates the server's address. rr`rOrrmrUrrrr[s zServer.getHostcCr)zl Returns an L{IPv4Address} or L{IPv6Address}. This indicates the client's address. r)rrrrrrrdrzServer.getPeerN)rrrrprrr?rrrrr classmethodr"rrrrrrrs ( rc@0eZdZdZddZddZddZdd Zd S) _IFileDescriptorReservationaT An open file that represents an emergency reservation in the process' file descriptor table. If L{Port} encounters C{EMFILE} on C{accept(2)}, it can close this file descriptor, retry the C{accept} so that the incoming connection occupies this file descriptor's space, and then close that connection and reopen this one. Calling L{_IFileDescriptorReservation.reserve} attempts to open the reserve file descriptor if it is not already open. L{_IFileDescriptorReservation.available} returns L{True} if the underlying file is open and its descriptor claimed. L{_IFileDescriptorReservation} instances are context managers; entering them releases the underlying file descriptor, while exiting them attempts to reacquire it. The block can take advantage of the free slot in the process' file descriptor table accept and close a client connection. Because another thread might open a file descriptor between the time the context manager is entered and the time C{accept} is called, opening the reserve descriptor is best-effort only. cCdS)z Is the reservation available? @return: L{True} if the reserved file descriptor is open and can thus be closed to allow a new file to be opened in its place; L{False} if it is not open. Nrrrrr availablerxz%_IFileDescriptorReservation.availablecCr))a! Attempt to open the reserved file descriptor; if this fails because of C{EMFILE}, internal state is reset so that another reservation attempt can be made. @raises Exception: Any exception except an L{OSError} whose errno is L{EMFILE}. Nrrrrrreserverxz#_IFileDescriptorReservation.reservecCr))z} Release the underlying file descriptor so that code within the context manager can open a new file. Nrrrrr __enter__rxz%_IFileDescriptorReservation.__enter__cCr))z Attempt to re-open the reserved file descriptor. See L{reserve} for caveats. @param excType: See L{object.__exit__} @param excValue: See L{object.__exit__} @param traceback: See L{object.__exit__} Nr)excTypeexcValue tracebackrrr__exit__rxz$_IFileDescriptorReservation.__exit__Nrrrrpr*r+r,r0rrrrr(ms   r(c@seZdZdefddZdS) _HasClosercCrrrsrrrrrrlsz_HasClose.closeN)rrrobjectrlrrrrr2sr2T) auto_attribsc@sneZdZUdZeZeeed<ege fed<e j dddZ e e ed<dd Zd d Zd d ZddZdS)_FileDescriptorReservationa  L{_IFileDescriptorReservation} implementation. @ivar fileFactory: A factory that will be called to reserve a file descriptor. @type fileFactory: A L{callable} that accepts no arguments and returns an object with a C{close} method. _log _fileFactoryFN)initdefault_fileDescriptorcCs |jduS)z See L{_IFileDescriptorReservation.available}. @return: L{True} if the reserved file descriptor is open and can thus be closed to allow a new file to be opened in its place; L{False} if it is not open. N)r:rrrrr*s z$_FileDescriptorReservation.availablec Csf|jdur1z|}Wn ty+}z|jtkr|jdnWYd}~dSd}~ww||_dSdS)z= See L{_IFileDescriptorReservation.reserve}. Nz2Could not reserve EMFILE recovery file descriptor.)r:r7rkerrnor7r6rF)rmrerrrr+s    z"_FileDescriptorReservation.reservecCs&|jdur td|jd|_dS)z? See L{_IFileDescriptorReservation.__enter__}. Nz5No file reserved. Have you called my reserve method?)r: RuntimeErrorrlrrrrr,s   z$_FileDescriptorReservation.__enter__cCs0z|WdSty|jdYdSw)z> See L{_IFileDescriptorReservation.__exit__}. z5Could not re-reserve EMFILE recovery file descriptor.N)r+ Exceptionr6rFrmr-r.r/rrrr0s  z#_FileDescriptorReservation.__exit__)rrrrprr6r__annotations__rr2attribr:rr*r+r,r0rrrrr5s    r5c@r') _NullFileDescriptorReservationzB A null implementation of L{_IFileDescriptorReservation}. cCr))z The reserved file is never available. See L{_IFileDescriptorReservation.available}. @return: L{False} Frrrrrr*sz(_NullFileDescriptorReservation.availablecCr))zJ Do nothing. See L{_IFileDescriptorReservation.reserve}. Nrrrrrr+rxz&_NullFileDescriptorReservation.reservecCr))ze Do nothing. See L{_IFileDescriptorReservation.__enter__} @return: L{False} Nrrrrrr,rxz(_NullFileDescriptorReservation.__enter__cCr))z Do nothing. See L{_IFileDescriptorReservation.__exit__}. @param excType: See L{object.__exit__} @param excValue: See L{object.__exit__} @param traceback: See L{object.__exit__} Nrr?rrrr0 rxz'_NullFileDescriptorReservation.__exit__Nr1rrrrrCs   rCcCs ttjSrs)openosdevnullrrrrrw1s rwc@sPeZdZUdZeed<eed<eje e dZ e e ed<ddZdd Zd S) _BuffersLogsa@ A context manager that buffers any log events until after its block exits. @ivar _namespace: The namespace of the buffered events. @type _namespace: L{str}. @ivar _observer: The observer to which buffered log events will be written @type _observer: L{twisted.logger.ILogObserver}. _namespace _observer)r9_logscCst|j|jjdS)z Enter a log buffering context. @return: A logger that buffers log events. @rtype: L{Logger}. ) namespaceobserver)rrHrJappendrrrrr,Xsz_BuffersLogs.__enter__cCs|jD]}||qdS)z Exit a log buffering context and log all buffered events to the provided observer. @param excType: See L{object.__exit__} @param excValue: See L{object.__exit__} @param traceback: See L{object.__exit__} N)rJrI)rmr.r-r/eventrrrr0as z_BuffersLogs.__exit__N)rrrrprr@r rArBFactoryrTrJrrr,r0rrrrrGFs   rGc csH|D]}z|\}}Wnty}z|jdttfvr&WYd}~dS|jdtkr3WYd}~q|jdtkr{|r{|d|&t ||||}|D]\} } | |jd| dqO|dWdn1snwYWYd}~dS|jdt vr|jdt |jddWYd}~dSd}~ww||fVqdS) a Return a generator that yields client sockets from the provided listening socket until there are none left or an unrecoverable error occurs. @param logger: A logger to which C{accept}-related events will be logged. This should not log to arbitrary observers that might open a file descriptor to avoid claiming the C{EMFILE} file descriptor on UNIX-like systems. @type logger: L{Logger} @param accepts: An iterable iterated over to limit the number consecutive C{accept}s. @type accepts: An iterable. @param listener: The listening socket. @type listener: L{socket.socket} @param reservedFD: A reserved file descriptor that can be used to recover from C{EMFILE} on UNIX-like systems. @type reservedFD: L{_IFileDescriptorReservation} @return: A generator that yields C{(socket, addr)} tuples from L{socket.socket.accept} rNz7EMFILE encountered; releasing reserved file descriptor.z-EMFILE recovery: Closed socket from {address})r?z-Re-reserving EMFILE recovery file descriptor.z/Could not accept new connection ({acceptError})) acceptError) acceptrkrur2r:r0r7r*info_acceptrl_ACCEPT_ERRORSr=) loggeracceptslistener reservedFD_rr?r<clientsToClose clientToClose closedAddressrrrrSnsF      )rSc@seZdZUdZejZeZdZ dZ dZ dZ dZ eeed<dZejZejZeZd!dd Zed d Zd efd dZddZddZddZ ddZ!e"#e$j%fddZ&e&Z'ddZ(ddZ)ddZ*dd Z+dS)"Porta. A TCP server port, listening for connections. When a connection is accepted, this will call a factory's buildProtocol with the incoming address as an argument, according to the specification described in L{twisted.internet.interfaces.IProtocolFactory}. If you wish to change the sort of transport that will be used, the C{transport} attribute will be called with the signature expected for C{Server.__init__}, so it can be replaced. @ivar deferred: a deferred created when L{stopListening} is called, and that will fire when connection is lost. This is not to be used it directly: prefer the deferred returned by L{stopListening} instead. @type deferred: L{defer.Deferred} @ivar disconnecting: flag indicating that the L{stopListening} method has been called and that no connections should be accepted anymore. @type disconnecting: C{bool} @ivar connected: flag set once the listen has successfully been called on the socket. @type connected: C{bool} @ivar _type: A string describing the connections which will be created by this port. Normally this is C{"TCP"}, since this is a TCP port, but when the TLS implementation re-uses this class it overrides the value with C{"TLS"}. Only used for logging. @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}). r2rNrcCsFtjj||d||_||_||_t|rtj |_ t j |_ ||_dS)z,Initialize with a numeric port to listen on.rN)r@BasePortrrrbacklogr>rrOrrr?rr interface)rmrrrarbrrrrrs  z Port.__init__cCs6t|||j}t|d}|d|d||}||_|S)a} Create a new L{Port} based on an existing listening I{SOCK_STREAM} socket. Arguments are the same as to L{Port.__init__}, except where noted. @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. @param addressFamily: The address family (sometimes called I{domain}) of the existing socket. For example, L{socket.AF_INET}. @return: A new instance of C{cls} wrapping the socket given by C{fd}. rN)rOrrr`_preexistingSocket)rrfdrrrrbrmrrr_fromListeningDescriptors  zPort._fromListeningDescriptorrcCs2|jdurd|j|jj|jSd|j|jjS)Nz<{} of {} on {}>z<{} of {} (not listening)>)rrr rrrrrrs z Port.__repr__cCs4tj|}tdkrtjdkr|tjtj d|S)NposixcygwinrL) r@r`rrsysplatformrfrOrg SO_REUSEADDRrrrrr s zPort.createInternetSocketc Cst|jdurDz|}|jtjkrt|j|j }n|j|j f}| |Wnt y<}zt |j|j |d}~ww| |jn |j}d|_d|_|d|_td||j|jf|jd|_||_|jj|_d|_|dS)zCreate 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. NFrLz%s starting on %sTd) _reservedFDr+rcrrrOrrrbrrrkrDlistenrardr_rrGmsgrrdoStartrr numberAcceptsr)rmr\rUlerrrstartListening&s8      zPort.startListeningcCs|jdg|RS)Nr)r)rmr?rrr _buildAddrSszPort._buildAddrc Csdztdkr |j}nd}t|jj|jjp}d}t|t||jt }t |dD]V\}\}}t | t|dkrRt|tjtjB}t|dgt|dd}|j||}|durd|q&|j} | d|_|||||| |j} || q&Wdn1swY||jkr|jd7_WdStd||_WdStytYdSw)z Called when my socket is ready for reading. This accepts a connection and calls self.protocol() to handle the wire-level protocol. rfrLrrKN) rrprG_loggerrKrLrSrangerOrl enumeraterBrrrNrPrQrRrSrTrrrsrlr transportrrmaxrrGdeferr) rm numAcceptsbufferingLoggeracceptedclientsr\rUrVrrrxrrrr}VsJ      " z Port.doReadcCs2d|_||jrt|jd|j||_|jSdS)a Stop accepting connections on this port. This will shut down the socket and call self.connectionLost(). It returns a deferred which will fire successfully when the port is actually closed, or with a failure if an error occurs shutting down. TrN) disconnectingr{rrErrdeferred)rmconnDonerrrrs zPort.loseConnectioncCs td|jd|jddS)z. Log message for closing port (z Port z Closed)N)rGrn_typerrrrr_logConnectionLostMsgs zPort._logConnectionLostMsgcCsT|d|_tj||d|_|d|`|`z |j Wd|_ dSd|_ w)z' Cleans up the socket. NFT) rrr@r`rrrorOrrdoStoprrrrrrs  zPort.connectionLostcCst|jjS)z9Returns the name of my class, to prefix log entries with.)rHqualrr rrrrrszPort.logPrefixcCr#)zs Return an L{IPv4Address} or L{IPv6Address} indicating the listening address of this port. rr$r%rrrrs z Port.getHost)r_r^N),rrrrprOrrrrxrrbrarrrintr@rcrrr?rrrrurr&rerrrrrrsr}rFrrCrr stopListeningrrrrrrrrr]s6 #   -A r]c@s0eZdZdZejZd ddZddZddZ dS) Connectora6 A L{Connector} provides of L{twisted.internet.interfaces.IConnector} for all POSIX-style reactors. @ivar _addressType: the type returned by L{Connector.getDestination}. Either L{IPv4Address} or L{IPv6Address}, depending on the type of address. @type _addressType: C{type} Nc Cst|tr&zt|d}Wnty%}z tj|d|ddd}~ww|||_|_t |r6t j |_ ||_tj||||dS)Ntcpz ()r) isinstancerrO getservbynamerkrAServiceNameUnknownErrorrVrr>rr?rrrr@ BaseConnectorr)rmrVrrtimeoutrrr<rrrrs  zConnector.__init__cCst|j|j|j||jS)z| Create a L{Client} bound to this L{Connector}. @return: a new L{Client} @rtype: L{Client} )rrVrrrrrrr_makeTransportszConnector._makeTransportcCs|d|j|jS)zQ @see: L{twisted.internet.interfaces.IConnector.getDestination}. r)rrVrrrrrgetDestinationszConnector.getDestinationrs) rrrrpr?rrrrrrrrrrs   r)qrprErOrirhtypingrrrrrzope.interfacerrrAtwisted.internet.interfacesr r r r twisted.loggerr rrtwisted.pythonrrtwisted.python.compatrtwisted.python.runtimertwisted.internet._newtlsrr"rrrr%r ImportErrorr3r0r;r'r4r(r3r)r1r*r5r+r7r,r6r-r2r8r9r:r.r;twisted.python.win32r/r<r=twisted.internetr>r?r@rArBrCtwisted.internet.errorrDtwisted.internet.protocoltwisted.internet.taskrErFrGrHtwisted.python.utilrIgetattr_AI_NUMERICSERVrWr]r`rbrqrrrrAI_NUMERICHOSTrrrrrr(r2rr5rCrlrTrGrSr`r]rrrrrrs   $                      #    & Vo= = ?  'I