Ϫf dZddlmZddlZddlZddlZddlZddlmZm Z m Z m Z m Z ddl mZmZddlZddlZddlmZmZmZmZmZmZddlmZmZmZddlmZmZdd lm Z dd l!m"Z" dd l#m$Z%m&Z'm(Z)dd lm*Z*e"dk(r6e,Z-ddl.m/Z0m1Z2m3Z4m5Z6m7Z8m9Z:m;Z<e,Z=e,Z>eZ>dd!l.m?Z?dd"l.mAZAdd#lmDZDdd$l.mEZEdd%lFmGZGmHZHmIZImJZJmKZKmLZLdd&lMmNZNdd'lOmPZPdd(lQmRZRdd)lmSZSmTZTmUZUdd*lVmWZWeXed+dZYd,ZZd-Z[d.Z\Gd/d0Z]Gd1d2Z^ee*eeGd3d4e'eGje]e^Z`Gd5d6ZaGd7d8eae%e`ZbejeYzZdd9ZeGd:d;ZfGd<d=efebZgGd>d?e)e`ZhGd@dAeZiGdBdCejZjeeiejdDEGdFdGZleeiGdHdIZme"dk(remZnn eldJZne8e:e=e>eAfZoejdDEGdKdLZpdMZqeeGdNdOeIje]ZsGdPdQeIjZuy#e+$r$eZ*Gd dZ'GddZ%GddZ)YWwxYw)Rzt Various asynchronous TCP/IP classes. End users shouldn't use this module directly - use the reactor APIs instead. ) annotationsN)CallableClassVarListOptionalUnion) Interface implementer)IHalfCloseableProtocolIListeningPort IProtocol IReactorTCP ISystemHandle ITCPTransport) ILogObserverLogEventLogger) deprecateversions) lazyByteSlice) platformType) ClientMixinConnectionMixin ServerMixin) ITLSTransportceZdZdZy)_TLSConnectionMixinFN)__name__ __module__ __qualname__TLS6/usr/lib/python3/dist-packages/twisted/internet/tcp.pyrr2sr#rc eZdZy)_TLSClientMixinNrrr r"r#r$r&r&5 r#r&c eZdZy)_TLSServerMixinNr'r"r#r$r*r*8r(r#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)Protocol) deferLater)failurelogreflect)untilConcludesAI_NUMERICSERVct|dk(rStj|tjtjzd}t |gt |ddzS|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)addrhosts r$ _getrealnamer^psc 4yA~!!$(=(=@U@U(UV  dVd48n,--BQxr#c4t|jSz See L{_getrealname}. )r^ getpeernameskts r$ _getpeernamerd ) **r#c4t|jSr`)r^ getsocknamerbs r$ _getsocknamerhrer#ceZdZdZdZdZy) _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 X|j} |r|jr`|jdnN|jjtjtj t jddd |jy#t$rYwxYw#t$rYywxYw)NrTiirSr) rV_shouldShutdownshutdown setsockopt SOL_SOCKET SO_LINGERstructpackOSErrorclose)selforderlyrcs r$ _closeSocketz_SocketCloser._closeSockets kk ''LLO  &&%%v'7'7T1a9P   IIK      s$A.B=B BB B)(B)N)rrr __doc__rmrxr"r#r$rjrjs Or#rjceZdZdZdZdZy)_AbortingMixinz Common implementation of C{abortConnection}. @ivar _aborting: Set to C{True} when C{abortConnection} is called. @type _aborting: C{bool} Fc<|js |jryd|_|j|jd|_d|_|j jd|jtjtjy)zf Aborts the connection immediately, dropping any buffered data. @since: 11.1 NTcyNr"argskwargss r$z0_AbortingMixin.abortConnection..r#cyr~r"rs r$rz0_AbortingMixin.abortConnection..rr#r) disconnected _aborting stopReading stopWritingdoReaddoWritereactor callLaterconnectionLostrLFailurerFConnectionAbortedrvs r$abortConnectionz_AbortingMixin.abortConnectionst      2 3   t""GOOE4K4K4M$N r#N)rrr ryrrr"r#r$r{r{sI r#r{cdeZdZdZddZdZdZdZdZdZ d Z d Z d Z d Z d ZdZdZdZy) 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} Nctjj||||_|jj d|j |_||_y)Nrr)rCFileDescriptor__init__rV setblockingfilenoprotocol)rvrcrrs r$rzConnection.__init__sF((w(?  "jj   r#c|jS)z&Return the socket for this connection.)rVrs r$ getHandlezConnection.getHandle {{r#c |jj|j}|j|S#t$r5}|jdt k(rYd}~yt jcYd}~Sd}~wwxYw)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) rVrecv bufferSizertrr7rHCONNECTION_LOST _dataReceived)rvdatases r$rzConnection.doReadsc ,;;##DOO4D!!$''  ,wwqz[(+++  ,s!%8 A6A1A1+A61A6c |stjS|jj|}|\|jj}d}t j |t jdddd|}t j|||S)NzPReturning a value other than None from %(fqpn)s is deprecated since %(version)s.Twisted r)format) rHCONNECTION_DONEr dataReceivedrgetDeprecationWarningStringrVersionwarnAboutFunction)rvrrvaloffender warningFormat warningStrings r$rzConnection._dataReceiveds'' '}}))$/  }}11H0 &AA(**9b!Q? M  ' '- @ r#ct|d|j} t|jj|S#t $r:}|j dttfvrYd}~ytjcYd}~Sd}~wwxYw)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_LIMITrOrVsendrtrr7r;rHr)rvr limitedDatars r$ writeSomeDatazConnection.writeSomeData sf$D!T__=  ,!$++"2"2K@ @ ,wwqzk733+++  ,s!9 A<A7"A71A<7A<c> |jjdt|jd}|r |j yy#t$rY6wxYw#t $r<tj}tj|j|YywxYwNrS) rVrnrtr rwriteConnectionLost BaseExceptionrLrrMerrr)rvpfs r$_closeWriteConnectionz Connection._closeWriteConnection s  KK  # #4==$ 7  '%%'     ! 'OO% ##A& 's#AA AAABBct|jd}|r |jy|j |y#t$r:t j |j tjYywxYwr~) r rreadConnectionLostrrMrrrLr)rvreasonrs r$rzConnection.readConnectionLost.se "4==$ 7  7$$&    ' ! 7 ##GOO$56 7s=AB?Bct|dsytjj|||j |j t j |j}|`|` |` |j|y)z-See abstract.FileDescriptor.connectionLost().rVN) hasattrrCrrrxcheckrFrrrVr)rvrrs r$rzConnection.connectionLost9smtX& ..tV< fll5+B+BCCD== M K K'r# Uninitializedc|jS)zQ>QRSSr#cv|jjtjtj|yr~)rVrorprrs r$setTcpKeepAlivezConnection.setTcpKeepAliveYs$ v00&2E2EwOr#r~)rrr ryrrrrrrrrrrrrrrr"r#r$rrsS!($ ,( ' (("FTPTPr#rcdeZdZdZej ZejZdZ dZ dZ dZ dZ dZy) _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|r1|jj||d||jd|y|jd|j|y)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)_commonConnectionrrfailIfNotConnected)rvwhenDonercrFrs r$ _finishInitz_BaseBaseClient._finishInitsI"   " " + +D#tW E   a *   a!8!8% @r#cjrcjjjd}|j fd|j j jyj jy)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} rc*|fjddzSr)r\)nrvs r$rz0_BaseBaseClient.resolveAddress..sQD499QR=$8r#N)_requiresResolutionrresolver\ addCallback addCallbacks_setRealAddressr)rvds` r$resolveAddressz_BaseBaseClient.resolveAddresssc  # # $$TYYq\2A MM8 9 NN4//1H1H I   +r#ct|dk(rYtj|tjtjzd}t |gt |ddz|_n||_|jy)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. rRrrSN) rUrVrWrXrYrZr[ realAddress doConnect)rvrDhostnames r$rz_BaseBaseClient._setRealAddresssq w<1 ))..1F1FFH %hZ$wqr{2C%CDD &D  r#c0|js|js t|dsy|j |j d|j |jjtj||`y#t $rY>T..gdK6P  ##% )   d #  & & ( ''(<= N    sB BBcJ|jtjy)z If a connection attempt is still outstanding (i.e. no connection is yet established), immediately stop attempting to connect. N)rrF UserErrorrs r$stopConnectingz_BaseBaseClient.stopConnectings  12r#c|js&|jtj|y|jj |||j j |y)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)rrrF ConnectErrorrrrrvrs r$rz_BaseBaseClient.connectionLostsL~~  # #E$6$6f$E F  " " 1 1$ ? NN ) )& 1r#N)rrr ryrVAF_INET addressFamily SOCK_STREAM socketTyperrrrrrr"r#r$rr]s=1fNNM##JA.,.*&32r#rc6eZdZdZeZeZdZdZdZ dZ dZ y) 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^t|dr!|j|jyy)z Implement the POSIX-ish (i.e. L{twisted.internet.interfaces.IReactorFDSet}) method of detaching this socket from the reactor for L{_BaseBaseClient}. rN)rrrrs r$rz!BaseClient._stopReadingAndWritings+ 4 #         $r#c |`|`y)zn Clean up references to the socket and its file descriptor. @see: L{_BaseBaseClient} N)rVrrs r$rz BaseClient._collectSocketDetails"s Kr#ctj|j|j}|jdt j |j |S)zc(internal) Create a non-blocking socket using self.addressFamily, self.socketType. r)rVrrrrG_setCloseOnExecrrvss r$createInternetSocketzBaseClient.createInternetSocket*sC MM$,,doo > a ahhj)r#c8|j|_|j|_t|dsy|jj tj tj}|r0|jtj|t|fy |jj|j}|r|t k(rnv|t"t$t&fvs|t(k(r*t*dk(r!|j-|j/y|jtj|t|fy|`|`|j1|j3|j5y#t$r}|jd}Yd}~d}~wwxYw)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+)rrrrrVrrpSO_ERRORrrFgetConnectErrorrA connect_exrrtrr:r7r8r9r6r startReading startWritingrr _connectDone)rvr connectResultrs r$rzBaseClient.doConnect3sU~~ nn t[) kk$$V%6%6H   # #E$9$93 :N$O P  ' KK2243C3CDM ' Kh#GG'LG,C!!#!!#''))=(=:Q*RS L K   5 'GGAJM 's%E77 FFFcf|jj|j|_d|_|j |j}d|z|_|j t|_|jy|j|jj|y)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. rSz %s,clientN) r buildProtocolgetPeerrr _getLogPrefixrrJloseConnectionr makeConnection)rvrs r$rzBaseClient._connectDoneks44T\\^D &&t}}5 !I- == %JDM    !     MM ( ( .r#N) rrr ryr_baserrrrrrr"r#r$rrs." E" %6p/r#rcJtj||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. rrR)rV getaddrinfo _NUMERIC_ONLY)ipports r$ _resolveIPv6rs)*   b$1a ? B1 EEr#cDeZdZdZej ZddZdZdZ ddZ y) _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||_||f|_|j}d}d}tj|rd|_n_tj |rCd|_t|||_tj|_ tj|_ nd|_ |j}|r7|5 tj |dr t|} n|} |j'| |j)||||y#t$r<} t!j"| j$d| j$d}d}Yd} ~ d} ~ wwxYw#t$r<} t!j"| j$d| j$d}d}Yd} ~ d} ~ wwxYw)NFTrrS)rr\rrC isIPAddressr isIPv6AddressrrVAF_INET6rrD IPv6Address _addressTyperrtrFConnectBindErrorrbindr) rvr]r bindAddressrrrrrcrbindinfos r$rz_BaseTCPClient.__init__s["4L &&    %',D $  # #D )',D $$T40DI!'D  ' 3 3D '+D $ ++-C  / ))+a.9+[9H*H" 3W5 ((RWWQZ@CH  ,,RWWQZD s0C<34E< E2D<<E F  2FF cN|jdgt|jS)z~ Returns an L{IPv4Address} or L{IPv6Address}. This indicates the address from which I am connecting. TCP)r%rhrVrs r$getHostz_BaseTCPClient.getHosts% !t  Cdkk)BCCr#c<|jdg|jS)zz Returns an L{IPv4Address} or L{IPv6Address}. This indicates the address that I am connected to. r+)r%rrs r$rz_BaseTCPClient.getPeers" !t  :)9)9::r#cZd|jd|jdt|dd}|S)N) __class__r\idrs r$__repr__z_BaseTCPClient.__repr__s0tDII;d2d8A,a @r#r~returnstr) rrr ryrD IPv4Addressr%rr,rr4r"r#r$rrs*6&&L!6FD;r#rceZdZdZy)Clientz A transport for a TCP protocol; either TCPv4 or TCPv6. Do not create these directly; use L{IReactorTCP.connectTCP}. N)rrr ryr"r#r$r:r:sr#r:ceZdZUdZeZejZde d< d dZ d dZ e dZ dZdZy ) 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). z;Union[type[address.IPv4Address], type[address.IPv6Address]]r%ctj||||t|dk7rtj|_||_||_||_|d|_ |j|j}|d|d|j|_ |j Tdj|jjj|j|j j |_|j%d|_y)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. rTr,N<{} #{} on {}>rS)rrrUrDr$r%serverclient sessionnorrrrrr2r_realPortNumberrepstrr r)rvsockrrAr@rBrrs r$rzServer.__init__s D$': v;!  ' 3 3D   "q  &&t}}5 " 1YKq@ ;; "/66 ''00 ++ DK r#c|jS)z= A string representation of this connection. )rDrs r$r4zServer.__repr__9s{{r#ctj}|tjk(rtj}tj ||tj }t|}|dg|}|jd} |j|} | |jy||| |d|d|} dj| jjj| 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}. r+rSNr?)rDr8rVr#r$fromfdrrdrgrrurrr2rrBrDr) clsfileDescriptorrfactoryr addressTypercr\ protocolAddr localPortrrvs r$_fromConnectedSocketzServer._fromConnectedSocket?s&)) FOO +!--KmmNM6;M;MNC "5040 OO%a( ((6   IIK 3$d1gw?&-- MM # # , , NN   % r#cRt|j}|jdg|S)zl Returns an L{IPv4Address} or L{IPv6Address}. This indicates the server's address. r+rhrVr%rvr\s r$r,zServer.getHosths* DKK( t  ...r#c<|jdg|jS)zl Returns an L{IPv4Address} or L{IPv6Address}. This indicates the client's address. r+)r%rArs r$rzServer.getPeerqs !t  555r#N)rEz socket.socketrr rAztuple[object, ...]r@PortrBintrrr6Noner5)rrr ryrrrDr8r%__annotations__rr4 classmethodrOr,rr"r#r$r<r<s  E !!!# !  !  !! !F &&P/6r#r<c(eZdZdZdZdZdZdZy)_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. cy)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. Nr"r"r#r$ availablez%_IFileDescriptorReservation.availablerr#cy)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}. Nr"r"r#r$reservez#_IFileDescriptorReservation.reserverr#cy)z} Release the underlying file descriptor so that code within the context manager can open a new file. Nr"r"r#r$ __enter__z%_IFileDescriptorReservation.__enter__rr#cy)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 tracebacks r$__exit__z$_IFileDescriptorReservation.__exit__rr#Nrrr ryr\r^r`rer"r#r$rZrZzs0    r#rZceZdZddZy) _HasClosecyr~r"rs r$ruz_HasClose.closes r#N)r6object)rrr rur"r#r$rhrhs r#rhT) auto_attribsc~eZdZUdZeZded<ded<ejddZ d ed <d Z d Z d Z dZ y)_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. zClassVar[Logger]_logzCallable[[], _HasClose] _fileFactoryFN)initdefaultzOptional[_HasClose]_fileDescriptorc|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)rrrs r$r\z$_FileDescriptorReservation.availables##4//r#c|j |j}||_yy#t$r:}|jtk(r|j j dnYd}~yd}~wwxYw)z= See L{_IFileDescriptorReservation.reserve}. Nz2Could not reserve EMFILE recovery file descriptor.)rrrorterrnor<rnrL)rvrJes r$r^z"_FileDescriptorReservation.reserveso    ' 6!%!2!2!4(6$ ( 77f$II%%L  s' A*0A%%A*ct|j td|jjd|_y)z? See L{_IFileDescriptorReservation.__enter__}. Nz5No file reserved. Have you called my reserve method?)rr RuntimeErrorrurs r$r`z$_FileDescriptorReservation.__enter__s6    'VW W ""$#r#cz |jy#t$r|jjdYywxYw)z> See L{_IFileDescriptorReservation.__exit__}. z5Could not re-reserve EMFILE recovery file descriptor.N)r^ ExceptionrnrLrvrbrcrds r$rez#_FileDescriptorReservation.__exit__s5 W LLN W II  U V Ws $::)rrr ryrrnrWattribrrr\r^r`rer"r#r$rmrmsI$XD %))+2477t+LO(L06"$Wr#rmc(eZdZdZdZdZdZdZy)_NullFileDescriptorReservationzB A null implementation of L{_IFileDescriptorReservation}. cy)z The reserved file is never available. See L{_IFileDescriptorReservation.available}. @return: L{False} Fr"rs r$r\z(_NullFileDescriptorReservation.availablesr#cy)zJ Do nothing. See L{_IFileDescriptorReservation.reserve}. Nr"rs r$r^z&_NullFileDescriptorReservation.reserve rr#cy)ze Do nothing. See L{_IFileDescriptorReservation.__enter__} @return: L{False} Nr"rs r$r`z(_NullFileDescriptorReservation.__enter__rr#cy)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__} Nr"r{s r$rez'_NullFileDescriptorReservation.__exit__rr#Nrfr"r#r$rrs   r#rc4ttjSr~)openosdevnullr"r#r$rr>sT"**5Er#ceZdZUdZded<ded<ej ejeZ ded<d Z d Z y ) _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}. r7 _namespacer _observer)rqzList[LogEvent]_logscXt|j|jjS)z Enter a log buffering context. @return: A logger that buffers log events. @rtype: L{Logger}. ) namespaceobserver)rrrappendrs r$r`z_BuffersLogs.__enter__es$**:K:KLLr#cH|jD]}|j|y)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)rr)rvrcrbrdevents r$rez_BuffersLogs.__exit__ns#ZZ "E NN5 ! "r#N) rrr ryrWr|r}Factoryr[rr`rer"r#r$rrSs? O#DGGLDLL,>?E>?M "r#rc #K|D]} |j\}}||fy#t$r%}|jdttfvrYd}~y|jdt k(rYd}~f|jdt k(r|jr{|jd|5t||||}|D](\} } | j|jd| *|jddddn #1swYnxYwYd}~y|jdtvr-|jdt|jdYd}~yd}~wwxYww) 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})rDz-Re-reserving EMFILE recovery file descriptor.z/Could not accept new connection ({acceptError})) acceptError) acceptrtrr7r?r5r<r\info_acceptru_ACCEPT_ERRORSrB) loggeracceptslistener reservedFD_rArDrvclientsToClose clientToClose closedAddresss r$rr{sZ4,"+ "&oo/OFGT'/ !Y,"' vvay[&11e#f$)=)=)? P  Q%,VWh %SN8F4 }%++- N$1$ KK OPQQQn, E )!&&) 4O' smE% E EE EE&E+9E$A C:1 E:D ?EE z<{} of {} (not listening)>)rCrr2rKrs r$r4z Port.__repr__ sg    +%,, &&$$  066 && r#ctjj|}tdk(rBtj dk7r/|j tjtjd|S)NposixcygwinrS) rErrrsysplatformrorVrp SO_REUSEADDRrs r$rzPort.createInternetSocket-sJ MM . .t 4 7 "s||x'? LL**F,?,? Cr#cbtj|j |j}|jt j k(r!t|j|j}n|j|jf}|j||j|jn|j}d|_d|_|j!d|_t%j&|j)|j*d|j"|j*j-d|_||_|j j0|_d|_|j5y#t$r&}t|j|j|d}~wwxYw)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. NFrSz starting on Td) _reservedFDr^rrrrVr#rrrr'rtrIlistenrrmrgrCrMmsgrrKdoStartrr numberAcceptsr )rvrcr\les r$startListeningzPort.startListening3sT   " " * G//1%%8' BD NNDII6D JJt|| $))C&*D ##(D  #03 !!$,,/1E1E G   kk((   7 G' 2FF GsA7E?? F.!F))F.c(|jdg|S)Nr+)r%)rvrDs r$ _buildAddrzPort._buildAddr`s t  111r#c   tdk(r |j}nd}t|jj|jj 5}d}t |t||jt}t|dD]\}\}}tj|jt|dk(rStj|tj tj"z}t%|dgt'|ddz}|j(j+|j-|}||j/|j0} | dz|_|j3||||| |j4} |j7|  ddd|jk(r|xjdz c_yt9d||_y#1swY@xYw#t:$rt=j>YywxYw)z Called when my socket is ready for reading. This accepts a connection and calls self.protocol() to handle the wire-level protocol. rrSrrRN) rrr_loggerrrrrangerVr enumeraterGrrrUrWrXrYrZr[rKrrrurB transportrrmaxrrMdeferr) rv numAcceptsbufferingLoggeracceptedclientsrcr\r]rrrs r$rz Port.doReadcs8 w&!//   && (=(= 7 !#U:%6 [.7w-B7)HksD))#**,74yA~ &11 &"7"7&:O:O"O  %d1gYd12h%?@#||99$//$:OPH'  A%&UDN $XtT1dll!I++I6)7 7D4---""b("&)H%5"O 7 7P  JJL s1A G#E G,G#G#G G##HHcd|_|j|jr3t|jd|j ||_|j Sy)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) disconnectingrrrKrrdeferred)rvconnDones r$rzPort.loseConnectionsJ"  >>&t||Q8K8KXVDM==  r#cdtjd|jd|jdy)z. Log message for closing port (z Port z Closed)N)rMr_typerCrs r$_logConnectionLostMsgzPort._logConnectionLostMsgs* !DJJr#r)vry __future__rrrVrrrtypingrrrrrzope.interfacer r r|twisted.internet.interfacesr r r rrrtwisted.loggerrrrtwisted.pythonrrtwisted.python.compatrtwisted.python.runtimertwisted.internet._newtlsrr&rrrr*r ImportErrorrjr5rur,r9r-r8r.r6r/r:r0r<r1r;r2r7r=r>r?r3r@twisted.python.win32r4rArBtwisted.internetrCrDrErFrGrHtwisted.internet.errorrItwisted.internet.protocolrJtwisted.internet.taskrKrLrMrNtwisted.python.utilrOgetattr_AI_NUMERICSERVr^rdrhrjr{rrrrAI_NUMERICHOSTrrrr:r<rZrhrrmrrrrrrrTrrr"r#r$rs  # <<1 :9.//  :7 HEXF XF F3<!!"IH4.,00.&"2A6(++  F  8 ]M=9HP00-HP:HPVb2b2JC//:C/L%%7 F0SSl^Zv6_jv6r: ): z   ()T:W:W*:Wz ()! ! *! ~702K,-EFK$'66<@T$"$"$"NF"R ^Q/4==-Q/Q/h&>""&>W-  M      s&J%%%K K