o b.@sLdZddlZddlZddlZddlZddlmZddlmZm Z m Z ddl m Z m Z ddlmZddlmZmZmZmZmZddlmZmZdd lmZmZmZmZdd lmZm Z m!Z!m"Z"m#Z#dd l$m%Z%m&Z&m'Z'm(Z(z dd l)m*Z*m+Z+Wn e,ydZ+dZ*Ynwdd l-m.Z.ddl/m0Z0ddl1m2Z2ddl3m4Z4ddl5m6Z6m7Z7ddl8m9Z9m:Z:ddl;mZ>ddl?m@Z@ddlAmBZBddlCmDZDddlEmFZFddlGmHZHmIZIzddlJmKZLddlMmNZNmOZOmPZPmQZQmRZRmSZSddlTmUZVWn e,ydZUYnweVZUgdZWGddde(ZXGd d!d!e%ZYe ejZGd"d#d#Z[Gd$d%d%ej\ej]ej^Z_Gd&d'd'e@e_d(Z`Gd)d*d*e'ZaGd+d,d,e Zbe ejcGd-d.d.Zde ejZGd/d0d0ZeGd1d2d2eeZfGd3d4d4eeZge ejcGd5d6d6Zhe ejcGd7d8d8Zie eGd9d:d:Zje ejcGd;d<d<Zke ejZGd=d>d>Zle ejcGd?d@d@Zme ejZGdAdBdBZne ejcGdCdDdDZoe ejZGdEdFdFZpddIdJZqddMdNZr O   G H  ddPdQZse e6e#GdRdSdSZte e6e#GdTdUdUZue e6e#GdVdWdWZveqeresdXZwexdY\ZyZzdZd[Z{d\d]Z|efelend^Z}ehemeod^Z~d_d`ZdadbZdcddZdedfZdgdhZdidjZdkdlZdmdnZdodpZdqdrZdsdtZeeed^ZdudvZdwdxZe ejcGdydzdzZe ejZGd{d|d|Zd}d~Z      dddZe e6e"GdddZdS)a7 Implementations of L{IStreamServerEndpoint} and L{IStreamClientEndpoint} that wrap the L{IReactorTCP}, L{IReactorSSL}, and L{IReactorUNIX} interfaces. This also implements an extensible mini-language for describing endpoints, parsed by the L{clientFromString} and L{serverFromString} functions. @since: 10.1 N) normalize)directlyProvides implementerprovider) NamedConstantNames)Version)defererrorfdesc interfacesthreads) isIPAddress isIPv6Address)HostnameAddress IPv4Address IPv6Address_ProcessAddress)IHostnameResolverIReactorPluggableNameResolverIResolutionReceiver,IStreamClientEndpointStringParserWithReactor!IStreamServerEndpointStringParser) ClientFactoryFactoryProcessProtocolProtocol) PipeAddress StandardIO)HostResolution)Deferred) LoopingCall)Logger)IPlugin getPlugins) deprecatelog)_matchingString iterbytes nativeString)proxyForInterface)Failure)FilePath) ListenFDs) _idnaBytes _idnaText)Error) CertificateCertificateOptionsKeyPairPrivateCertificateoptionsForClientTLStrustRootFromCertificatesTLSMemoryBIOFactory)clientFromStringserverFromStringTCP4ServerEndpointTCP6ServerEndpointTCP4ClientEndpointTCP6ClientEndpointUNIXServerEndpointUNIXClientEndpointSSL4ServerEndpointSSL4ClientEndpointAdoptedStreamServerEndpointStandardIOEndpointProcessEndpointHostnameEndpointStandardErrorBehaviorconnectProtocol wrapClientTLSc@sXeZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ dS)_WrappingProtocolz_ Wrap another protocol in order to notify my user when a connection has been made. cCs<||_||_tjtjtjfD] }||jrt||qdS)z @param connectedDeferred: The L{Deferred} that will callback with the C{wrappedProtocol} when it is connected. @param wrappedProtocol: An L{IProtocol} provider that will be connected. N)_connectedDeferred_wrappedProtocolr IHalfCloseableProtocolIFileDescriptorReceiverIHandshakeListener providedByr)selfconnectedDeferredwrappedProtocolifacerV} that is managing the current or previous connection attempt. cCs||_tj|jd|_dS)z @param wrappedFactory: A provider of I{IProtocolFactory} whose buildProtocol method will be called and whose resulting protocol will be wrapped.  cancellerN)_wrappedFactoryr r _canceller _onConnection)rRwrappedFactoryrVrVrWrXsz_WrappingFactory.__init__cC ||_dS)z~ A connection attempt was started. Remember the connector which started said attempt, for use later. N) _connector)rR connectorrVrVrWstartedConnectings z"_WrappingFactory.startedConnectingcCs$|t|j|jdS)a; The outgoing connection attempt was cancelled. Fail that L{Deferred} with an L{error.ConnectingCancelledError}. @param deferred: The L{Deferred } that was cancelled; should be the same as C{self._onConnection}. @type deferred: L{Deferred } @note: This relies on startedConnecting having been called, so it may seem as though there's a race condition where C{_connector} may not have been set. However, using public APIs, this condition is impossible to catch, because a connection API (C{connectTCP}/C{SSL}/C{UNIX}) is always invoked before a L{_WrappingFactory}'s L{Deferred } is returned to C{connect()}'s caller. @return: L{None} N)errbackr ConnectingCancelledErrorr{getDestinationstopConnecting)rRdeferredrVrVrWrwsz_WrappingFactory._cancellercCrk)zY Start notifications are passed straight through to the wrapped factory. N)rvdoStartr]rVrVrWrz_WrappingFactory.doStartcCrk)zX Stop notifications are passed straight through to the wrapped factory. N)rvdoStopr]rVrVrWrrz_WrappingFactory.doStopcCsNz|j|}|durtWnty|jYdSw||j|S)a Proxy C{buildProtocol} to our C{self._wrappedFactory} or errback the C{self._onConnection} L{Deferred} if the wrapped factory raises an exception or returns L{None}. @return: An instance of L{_WrappingProtocol} or L{None} N)rv buildProtocolr NoProtocol BaseExceptionrxr~protocol)rRaddrprotorVrVrWrs  z_WrappingFactory.buildProtocolcCs|jjs |j|dSdS)zi Errback the C{self._onConnection} L{Deferred} when the client connection fails. N)rxcalledr~)rRr|rjrVrVrWclientConnectionFailed sz'_WrappingFactory.clientConnectionFailedN) r\rprqrrrKrrXr}rwrrrrrVrVrVrWrss  rsc@s$eZdZdZeZddZddZdS)rEz A Standard Input/Output endpoint @ivar _stdio: a callable, like L{stdio.StandardIO}, which takes an L{IProtocol} provider and a C{reactor} keyword argument (interface dependent upon your platform). cCrz)z? @param reactor: The reactor for the endpoint. N)_reactorrRreactorrVrVrWrX" zStandardIOEndpoint.__init__cCstj|j|t|jdS)zU Implement L{IStreamServerEndpoint.listen} to listen on stdin/stdout )r)r execute_stdiorrr)rRstdioProtocolFactoryrVrVrWlisten(s  zStandardIOEndpoint.listenN)r\rprqrrrrrXrrVrVrVrWrEs  rEc@eZdZdZdS))_IProcessTransportWithConsumerAndProducera) An L{_IProcessTransportWithConsumerAndProducer} combines various interfaces to work around the issue that L{interfaces.IProcessTransport} is incompletely defined and doesn't specify flow-control interfaces, and that L{proxyForInterface} doesn't allow for multiple interfaces. Nr\rprqrrrVrVrVrWr3src@r)_ProcessEndpointTransportaj An L{ITransport}, L{IProcessTransport}, L{IConsumer}, and L{IPushProducer} provider for the L{IProtocol} instance passed to the process endpoint. @ivar _process: An active process transport which will be used by write methods on this object to write data to a child process. @type _process: L{interfaces.IProcessTransport} provider NrrVrVrVrWr>sr_processc@s0eZdZdZddZddZddZdd Zd S) _WrapIProtocolz An L{IProcessProtocol} provider that wraps an L{IProtocol}. @ivar transport: A L{_ProcessEndpointTransport} provider that is hooked to the wrapped L{IProtocol} provider. @see: L{protocol.ProcessProtocol} cCs||_||_||_dS)z @param proto: An L{IProtocol} provider. @param errFlag: A constant belonging to L{StandardErrorBehavior} that determines if stderr is logged or dropped. @param executable: The file name (full path) to spawn. N)rerrFlag executable)rRrrrrVrVrWrXXs z_WrapIProtocol.__init__cCst||_|j|jS)z Call L{IProtocol} provider's makeConnection method with an L{ITransport} provider. @param process: An L{IProcessTransport} provider. )rr_rr^)rRprocessrVrVrWr^cs z_WrapIProtocol.makeConnectioncCsJ|dkr |j|S|dkr!|jtjkr#tjd|j|j|ddSdSdS)z This is called with data from the process's stdout or stderr pipes. It checks the status of the errFlag to setermine if stderr should be logged (default) or dropped. r.zGProcess %(executable)r wrote stderr unhandled by %(protocol)s: %(data)s)formatrrrdN)rrcrrHLOGr&msgr)rRchildFDrdrVrVrWchildDataReceivedms  z _WrapIProtocol.childDataReceivedcCs>|tjtjkr|jjdkr|jttS|j|S)z If the process ends with L{error.ProcessDone}, this method calls the L{IProtocol} provider's L{connectionLost} with a L{error.ConnectionDone} @see: L{ProcessProtocol.processEnded} r) checkr ProcessDonevaluestatusrrhr+ConnectionDonerirVrVrW processEnded~s  z_WrapIProtocol.processEndedN)r\rprqrrrXr^rrrVrVrVrWrNs    rc@seZdZdZeZeZdS)rHz Constants used in ProcessEndpoint to decide what to do with stderr. @cvar LOG: Indicates that stderr is to be logged. @cvar DROP: Indicates that stderr is to be dropped (and not logged). @since: 13.1 N)r\rprqrrrrDROPrVrVrVrWrHs rHc@s4eZdZdZdidddddejfddZddZdS) rFz An endpoint for child processes @ivar _spawnProcess: A hook used for testing the spawning of child process. @since: 13.1 rVNrc CsJ||_||_||_||_||_||_||_||_| |_| |_ |jj |_ dS)z See L{IReactorProcess.spawnProcess}. @param errFlag: Determines if stderr should be logged. @type errFlag: L{endpoints.StandardErrorBehavior} N) r _executable_args_env_path_uid_gid_usePTY _childFDs_errFlag spawnProcess _spawnProcess) rRrrargsenvpathuidgidusePTYchildFDsrrVrVrWrXszProcessEndpoint.__init__c Csl|t}z|t||j|j|j|j|j|j|j |j |j |j Wn t y0tYSwt|S)a3 Implement L{IStreamClientEndpoint.connect} to launch a child process and connect it to a protocol created by C{protocolFactory}. @param protocolFactory: A factory for an L{IProtocol} provider which will be notified of all events related to the created process. )rrrrrrrrrrrrrrr failsucceed)rRprotocolFactoryrrVrVrWconnects"   zProcessEndpoint.connect)r\rprqrrrHrrXrrVrVrVrWrFs  rFc@ eZdZdZddZddZdS)_TCPServerEndpointz) A TCP server endpoint interface cC||_||_||_||_dS)a+ @param reactor: An L{IReactorTCP} provider. @param port: The port number used for listening @type port: int @param backlog: Size of the listen queue @type backlog: int @param interface: The hostname to bind to @type interface: str N)r_port_backlog _interfacerRrportbacklog interfacerVrVrWrXs  z_TCPServerEndpoint.__init__cCstj|jj|j||j|jdS)z] Implement L{IStreamServerEndpoint.listen} to listen on a TCP socket )rr)r rr listenTCPrrrrRrrVrVrWrsz_TCPServerEndpoint.listenNr\rprqrrrXrrVrVrVrWrs rc@eZdZdZdddZdS)r<zC Implements TCP server endpoint with an IPv4 configuration 2cCt|||||dS)aA @param reactor: An L{IReactorTCP} provider. @param port: The port number used for listening @type port: int @param backlog: Size of the listen queue @type backlog: int @param interface: The hostname to bind to, defaults to '' (all) @type interface: str NrrXrrVrVrWrX  zTCP4ServerEndpoint.__init__Nrrr\rprqrrrXrVrVrVrWr<r<c@r)r=zC Implements TCP server endpoint with an IPv6 configuration r::cCr)aD @param reactor: An L{IReactorTCP} provider. @param port: The port number used for listening @type port: int @param backlog: Size of the listen queue @type backlog: int @param interface: The hostname to bind to, defaults to C{::} (all) @type interface: str NrrrVrVrWrX rzTCP6ServerEndpoint.__init__NrrrrVrVrVrWr=rr=c@s"eZdZdZdddZddZdS) r>z9 TCP client endpoint with an IPv4 configuration. NcC"||_||_||_||_||_dS)a @param reactor: An L{IReactorTCP} provider @param host: A hostname, used when connecting @type host: str @param port: The port number, used when connecting @type port: int @param timeout: The number of seconds to wait before assuming the connection has failed. @type timeout: L{float} or L{int} @param bindAddress: A (host, port) tuple of local address to bind to, or None. @type bindAddress: tuple Nr_hostr_timeout _bindAddressrRrhostrtimeout bindAddressrVrVrWrX6s  zTCP4ClientEndpoint.__init__cCsJzt|}|jj|j|j||j|jd|jWSty$t YSw)zP Implement L{IStreamClientEndpoint.connect} to connect via TCP. rr) rsr connectTCPrrrrrxrr rrRrwfrVrVrWrNs  zTCP4ClientEndpoint.connectrNr\rprqrrrXrrVrVrVrWr>0s  r>c@sNeZdZdZeejZeej Z dZ dZ dddZ dd Zd d Zd d ZdS)r?a TCP client endpoint with an IPv6 configuration. @ivar _getaddrinfo: A hook used for testing name resolution. @ivar _deferToThread: A hook used for testing deferToThread. @ivar _GAI_ADDRESS: Index of the address portion in result of getaddrinfo to be used. @ivar _GAI_ADDRESS_HOST: Index of the actual host-address in the 5-tuple L{_GAI_ADDRESS}. rrNcCr)z @param host: An IPv6 address literal or a hostname with an IPv6 address @see: L{twisted.internet.interfaces.IReactorTCP.connectTCP} NrrrVrVrWrXus  zTCP6ClientEndpoint.__init__csLtjrj|}|Sj}|fdd|j||S)z~ Implement L{IStreamClientEndpoint.connect} to connect via TCP, once the hostname resolution is done. cs|djjS)Nr) _GAI_ADDRESS_GAI_ADDRESS_HOSTresultr]rVrWsz,TCP6ClientEndpoint.connect..)rr_resolvedHostConnect_nameResolution addCallback)rRrdrVr]rWrs   zTCP6ClientEndpoint.connectcCs||j|dtjS)zd Resolve the hostname string into a tuple containing the host IPv6 address. r)_deferToThread _getaddrinfosocketAF_INET6rRrrVrVrWrsz"TCP6ClientEndpoint._nameResolutioncCsHzt|}|jj||j||j|jd|jWSty#t YSw)zD Connect to the server using the resolved hostname. r) rsrrrrrrxrr r)rR resolvedHostrrrVrVrWrs  z'TCP6ClientEndpoint._resolvedHostConnectr)r\rprqrr staticmethodr getaddrinforr deferToThreadrrrrXrrrrVrVrVrWr?`s     r?c@s.eZdZdZeZddZ   d ddZdS) _SimpleHostnameResolvera^ An L{IHostnameResolver} provider that invokes a provided callable to resolve hostnames. @ivar _nameResolution: the callable L{resolveHostName} invokes to resolve hostnames. @type _nameResolution: A L{callable} that accepts two arguments: the host to resolve and the port number to include in the result. cCrz)z? Create a L{_SimpleHostnameResolver} instance. N)r)rRnameResolutionrVrVrWrXrz _SimpleHostnameResolver.__init__rNTCPc s^t|}fdd}fdd}|||||fddS)a Initiate a hostname resolution. @param resolutionReceiver: an object that will receive each resolved address as it arrives. @type resolutionReceiver: L{IResolutionReceiver} @param hostName: see interface @param portNumber: see interface @param addressTypes: Ignored in this implementation. @param transportSemantics: Ignored in this implementation. @return: The resolution in progress. @rtype: L{IResolutionReceiver} csZ|D](\}}}}}|tjkrtdg|Rq|tjkr*tdg|RqdS)Nr)rraddressResolvedrAF_INETr) gairesultfamilysocktyper canonnamesockaddrresolutionReceiverrVrW cbDelivers  z:_SimpleHostnameResolver.resolveHostName..cbDelivercsjjd|jddS)Nz'while looking up {name} with {callable})namecallable)_logfailurer)r )hostNamerRrVrWebLogs  z6_SimpleHostnameResolver.resolveHostName..ebLogcsSN)resolutionCompleteignoredrrVrWrsz9_SimpleHostnameResolver.resolveHostName..)resolutionBeganrrr addErrbackaddBoth) rRrr portNumber addressTypestransportSemanticsrr rrV)rrrRrWresolveHostNames    z'_SimpleHostnameResolver.resolveHostName)rNr)r\rprqrrr"r rXrrVrVrVrWrs  rc@sfeZdZdZeejZeej Z dZ dddZ de fdd Zd d Zed d ZddZddZdS)rGaB A name-based endpoint that connects to the fastest amongst the resolved host addresses. @cvar _DEFAULT_ATTEMPT_DELAY: The default time to use between attempts, in seconds, when no C{attemptDelay} is given to L{HostnameEndpoint.__init__}. @ivar _hostText: the textual representation of the hostname passed to the constructor. Used to pass to the reactor's hostname resolver. @type _hostText: L{unicode} @ivar _hostBytes: the encoded bytes-representation of the hostname passed to the constructor. Used to construct the L{HostnameAddress} associated with this endpoint. @type _hostBytes: L{bytes} @ivar _hostStr: the native-string representation of the hostname passed to the constructor, used for exception construction @type _hostStr: native L{str} @ivar _badHostname: a flag - hopefully false! - indicating that an invalid hostname was passed to the constructor. This might be a textual hostname that isn't valid IDNA, or non-ASCII bytes. @type _badHostname: L{bool} g333333?rNcCsh||_|||_||\|_|_|_ttur|jn|j|_ ||_ ||_ ||_ |dur/|j }||_dS)a Create a L{HostnameEndpoint}. @param reactor: The reactor to use for connections and delayed calls. @type reactor: provider of L{IReactorTCP}, L{IReactorTime} and either L{IReactorPluggableNameResolver} or L{IReactorPluggableResolver}. @param host: A hostname to connect to. @type host: L{bytes} or L{unicode} @param port: The port number to connect to. @type port: L{int} @param timeout: For each individual connection attempt, the number of seconds to wait before assuming the connection has failed. @type timeout: L{float} or L{int} @param bindAddress: the local address of the network interface to make the connections from. @type bindAddress: L{bytes} @param attemptDelay: The number of seconds to delay between connection attempts. @type attemptDelay: L{float} @see: L{twisted.internet.interfaces.IReactorTCP.connectTCP} N)r_getNameResolverAndMaybeWarn _nameResolver_hostAsBytesAndText _badHostname _hostBytes _hostTextbytesstr_hostStrrrr_DEFAULT_ATTEMPT_DELAY _attemptDelay)rRrrrrr attemptDelayrVrVrWrXs  zHostnameEndpoint.__init__returncCsL|jr|j}nt|jrd|jd}nt|j}dd|dt|jdgS)zh Produce a string representation of the L{HostnameEndpoint}. @return: A L{str} []rz)rr#rr)rjoinr"rrrVrVrW__repr__>s   zHostnameEndpoint.__repr__cCsHt|s!tj|jtddddddd}tj|tdd t |j S|j S) a Retrieve a C{nameResolver} callable and warn the caller's caller that using a reactor which doesn't provide L{IReactorPluggableNameResolver} is deprecated. @param reactor: The reactor to check. @return: A L{IHostnameResolver} provider. TwistedrzPassing HostnameEndpoint a reactor that does not provide IReactorPluggableNameResolver (%(fqpn)s) was deprecated in %(version)sz5a reactor that provides IReactorPluggableNameResolver)r replacement) stacklevel) rrQr%getDeprecationWarningStringr[rwarningswarnDeprecationWarningr_fallbackNameResolution nameResolver)rRr warningStringrVrVrWrRs   z-HostnameEndpoint._getNameResolverAndMaybeWarncCst|tr,t|s t|rd||dfSzd|t|fWSty+|d}Yn(wtd|}t|s9t|rAd|d|fSzdt ||fWStyRYnw|dd}d||dfS)a For various reasons (documented in the C{@ivar}'s in the class docstring) we need both a textual and a binary representation of the hostname given to the constructor. For compatibility and convenience, we accept both textual and binary representations of the hostname, save the form that was passed, and convert into the other form. This is mostly just because L{HostnameAddress} chose somewhat poorly to define its attribute as bytes; hopefully we can find a compatible way to clean this up in the future and just operate in terms of text internally. @param host: A hostname to convert. @type host: L{bytes} or C{str} @return: a 3-tuple of C{(invalid, bytes, text)} where C{invalid} is a boolean indicating the validity of the hostname, C{bytes} is a binary representation of C{host}, and C{text} is a textual representation of C{host}. FasciicharmapNFCbackslashreplaceT) isinstancer!rrdecoder0 UnicodeErrorrencoder/)r asciibytesrVrVrWrms$     z$HostnameEndpoint._hostAsBytesAndTextcsjrttdjStgttGfddd}jj |j j d fddj fdd} tfd d j fd d }S) a Attempts a connection to each resolved address, and returns a connection which is established first. @param protocolFactory: The protocol factory whose protocol will be connected. @type protocolFactory: L{IProtocolFactory} @return: A L{Deferred} that fires with the connected protocol or fails a connection-related error. zinvalid hostname: cs:eZdZeddZefddZefddZdS)z2HostnameEndpoint.connect..EndpointReceivercSsdSrrV)resolutionInProgressrVrVrWrszBHostnameEndpoint.connect..EndpointReceiver.resolutionBeganc|dSrappend)address) addressesrVrWrzBHostnameEndpoint.connect..EndpointReceiver.addressResolvedcsdSrr`rVrIrrVrWrrJzEHostnameEndpoint.connect..EndpointReceiver.resolutionCompleteN)r\rprqrrrrrVrLrVrWEndpointReceivers rM)rcsttdjdS)NzCouldn't find the hostname '')r rr DNSLookupErrorr#rr]rVrWrsz*HostnameEndpoint.connect..c3s\|D](}t|trtj|j|jjjVt|tr+t j|j|jjjVqdSr) r?rr?rrrrrrr>)rI eachAddressr]rVrWresolvedAddressesToEndpointss(  z>HostnameEndpoint.connect..resolvedAddressesToEndpointscs|ttjjdSr)r~r rrrr)rr]rVrWrws  z,HostnameEndpoint.connect.._cancellercs|s tdjt|ggtjdfddd_d_tfddj _  j j fd d }S) aQ Given a sequence of endpoints obtained via name resolution, start connecting to a new one every C{self._attemptDelay} seconds until one of the connections succeeds, all of them fail, or the attempt is cancelled. @param endpoints: a list of all the endpoints we might try to connect to, as determined by name resolution. @type endpoints: L{list} of L{IStreamServerEndpoint} @return: a Deferred that fires with the result of the C{endpoint.connect} method that completes the fastest, or fails with the first connection error it encountered if none of them succeed. @rtype: L{Deferred} failing with L{error.ConnectingCancelledError} or firing with L{IProtocol} z no results for hostname lookup: rtcs&sjsjr dSdSr) completed endpointsLeftr~poprV) checkDonefailurespendingwinnerrVrWrUszLHostnameEndpoint.connect..startConnectionAttempts..checkDoneFTcsttd}|durd_dS|jfdd}jfdd}jfdd}dS)NFcs|Sr)remover) eachAttemptrWrVrWnoLongerPendings zkHostnameEndpoint.connect..startConnectionAttempts..iterateEndpoint..noLongerPendingcrErrKr)rXrVrW succeededrJzeHostnameEndpoint.connect..startConnectionAttempts..iterateEndpoint..succeededcs|dSrrF)rj)rUrVrVrWfailed!s  zbHostnameEndpoint.connect..startConnectionAttempts..iterateEndpoint..failed)nextrSrrGrrr)endpointr[r\r])rUrV iterEndpointsrWrrX)rZrWiterateEndpoint s   zRHostnameEndpoint.connect..startConnectionAttempts..iterateEndpointcs2d_ddD]}|q jr|SNT)rRcancelrunningstop)r remaining)rUrarWrVrWcancelRemainingPending)s  zYHostnameEndpoint.connect..startConnectionAttempts..cancelRemainingPending)r rOr#iterr r rRrSr!rclockstartr%r) endpointsrg)rwrrR)rUrVr`rarWrXrWstartConnectionAttemptss$   z9HostnameEndpoint.connect..startConnectionAttempts)rr r ValueErrorr#r rrrrr rrrlist)rRrrMrQrlrV)rwrIrrrRrWrs&      KzHostnameEndpoint.connectcCs||j||dtjS)a Resolve the hostname string into a tuple containing the host address. This is method is only used when the reactor does not provide L{IReactorPluggableNameResolver}. @param host: A unicode hostname to resolve. @param port: The port to include in the resolution. @return: A L{Deferred} that fires with L{_getaddrinfo}'s return value. r)rrr SOCK_STREAM)rRrrrVrVrWr86rz(HostnameEndpoint._fallbackNameResolution)rNN)r\rprqrrrrrrr rrr$rXr"r-rrrr8rVrVrVrWrGs   , , rGc@"eZdZdZd ddZddZdS) rBzE SSL secured TCP server endpoint with an IPv4 configuration. rrcCr)a @param reactor: An L{IReactorSSL} provider. @param port: The port number used for listening @type port: int @param sslContextFactory: An instance of L{interfaces.IOpenSSLContextFactory}. @param backlog: Size of the listen queue @type backlog: int @param interface: The hostname to bind to, defaults to '' (all) @type interface: str N)rr_sslContextFactoryrr)rRrrsslContextFactoryrrrVrVrWrXLs  zSSL4ServerEndpoint.__init__cC"tj|jj|j||j|j|jdS)zf Implement L{IStreamServerEndpoint.listen} to listen for SSL on a TCP socket. )contextFactoryrr)r rr listenSSLrrqrrrrVrVrWrbszSSL4ServerEndpoint.listenNrrrVrVrVrWrBFs  rBc@s$eZdZdZ dddZddZdS) rCzD SSL secured TCP client endpoint with an IPv4 configuration rNcCs(||_||_||_||_||_||_dS)ao @param reactor: An L{IReactorSSL} provider. @param host: A hostname, used when connecting @type host: str @param port: The port number, used when connecting @type port: int @param sslContextFactory: SSL Configuration information as an instance of L{interfaces.IOpenSSLContextFactory}. @param timeout: Number of seconds to wait before assuming the connection has failed. @type timeout: int @param bindAddress: A (host, port) tuple of local address to bind to, or None. @type bindAddress: tuple N)rrrrqrr)rRrrrrrrrrVrVrWrXws  zSSL4ClientEndpoint.__init__cCsNzt|}|jj|j|j||j|j|jd|jWSt y&t YSw)zb Implement L{IStreamClientEndpoint.connect} to connect with SSL over TCP. r) rsr connectSSLrrrqrrrxrr rrrVrVrWrs  zSSL4ClientEndpoint.connectrrrVrVrVrWrCqs  rCc@s"eZdZdZd ddZddZd S) r@z% UnixSocket server endpoint. rrcCr)a @param reactor: An L{IReactorUNIX} provider. @param address: The path to the Unix socket file, used when listening @param backlog: number of connections to allow in backlog. @param mode: mode to set on the unix socket. This parameter is deprecated. Permissions should be set on the directory which contains the UNIX socket. @param wantPID: If True, create a pidfile for the socket. N)r_addressr_mode_wantPID)rRrrHrmodewantPIDrVrVrWrXs   zUNIXServerEndpoint.__init__cCrs)zW Implement L{IStreamServerEndpoint.listen} to listen on a UNIX socket. )rr{r|)r rr listenUNIXrxrryrzrrVrVrWrszUNIXServerEndpoint.listenN)rrwrrrVrVrVrWr@s  r@c@rp) rAz% UnixSocket client endpoint. rrcCr)a @param reactor: An L{IReactorUNIX} provider. @param path: The path to the Unix socket file, used when connecting @type path: str @param timeout: Number of seconds to wait before assuming the connection has failed. @type timeout: int @param checkPID: If True, check for a pid file to verify that a server is listening. @type checkPID: bool N)rrr _checkPID)rRrrrcheckPIDrVrVrWrXs zUNIXClientEndpoint.__init__cCsFzt|}|jj|j||j|jd|jWSty"t YSw)za Implement L{IStreamClientEndpoint.connect} to connect via a UNIX Socket )rr) rsr connectUNIXrrr~rxrr rrrVrVrWrs  zUNIXClientEndpoint.connectN)rrrrVrVrVrWrAs  rAc@s0eZdZdZejZeej Z ddZ ddZ dS)rDz An endpoint for listening on a file descriptor initialized outside of Twisted. @ivar _used: A C{bool} indicating whether this endpoint has been used to listen with a factory yet. C{True} if so. cCs||_||_||_d|_dS)a @param reactor: An L{IReactorSocket} provider. @param fileno: An integer file descriptor corresponding to a listening I{SOCK_STREAM} socket. @param addressFamily: The address family of the socket given by C{fileno}. FN)rfileno addressFamily_used)rRrrrrVrVrWrXs  z$AdoptedStreamServerEndpoint.__init__cCsp|jr ttSd|_z||j|j|j|j |}| |jWn t y2tYSwt |S)z{ Implement L{IStreamServerEndpoint.listen} to start listening on, and then close, C{self._fileno}. T) rr rr AlreadyListened_setNonBlockingrradoptStreamPortr_closerr)rRfactoryrrVrVrWrs     z"AdoptedStreamServerEndpoint.listenN) r\rprqrroscloserrr setNonBlockingrrXrrVrVrVrWrDs   rDrrcCst||f|t|dfS)a Internal parser function for L{_parseServer} to convert the string arguments for a TCP(IPv4) stream endpoint into the structured arguments. @param factory: the protocol factory being parsed, or L{None}. (This was a leftover argument from when this code was in C{strports}, and is now mostly None and unused.) @type factory: L{IProtocolFactory} or L{None} @param port: the integer port number to bind @type port: C{str} @param interface: the interface IP to listen on @param backlog: the length of the listen queue @type backlog: C{str} @return: a 2-tuple of (args, kwargs), describing the parameters to L{IReactorTCP.listenTCP} (or, modulo argument 2, the factory, arguments to L{TCP4ServerEndpoint}. rr)int)rrrrrVrVrW _parseTCP&sr666TcCs&||ft|dt|tt|dfS)a Internal parser function for L{_parseServer} to convert the string arguments for a UNIX (AF_UNIX/SOCK_STREAM) stream endpoint into the structured arguments. @param factory: the protocol factory being parsed, or L{None}. (This was a leftover argument from when this code was in C{strports}, and is now mostly None and unused.) @type factory: L{IProtocolFactory} or L{None} @param address: the pathname of the unix socket @type address: C{str} @param backlog: the length of the listen queue @type backlog: C{str} @param lockfile: A string '0' or '1', mapping to True and False respectively. See the C{wantPID} argument to C{listenUNIX} @return: a 2-tuple of (args, kwargs), describing the parameters to L{twisted.internet.interfaces.IReactorUNIX.listenUNIX} (or, modulo argument 2, the factory, arguments to L{UNIXServerEndpoint}. )r{rr|)rbool)rrHr{rlockfilerVrVrW _parseUNIX?sr server.pemc sddlm|dur |}i} |durtj|| d<t|} t|} j| d| } |durVtj dt t|tj d} fdd | D}|sUt d |fnd}|durdj t|}jd | jj| j||d | }t|||f|t|d fS)a Internal parser function for L{_parseServer} to convert the string arguments for an SSL (over TCP/IPv4) stream endpoint into the structured arguments. @param factory: the protocol factory being parsed, or L{None}. (This was a leftover argument from when this code was in C{strports}, and is now mostly None and unused.) @type factory: L{IProtocolFactory} or L{None} @param port: the integer port number to bind @type port: C{str} @param interface: the interface IP to listen on @param backlog: the length of the listen queue @type backlog: C{str} @param privateKey: The file name of a PEM format private key file. @type privateKey: C{str} @param certKey: The file name of a PEM format certificate file. @type certKey: C{str} @param sslmethod: The string name of an SSL method, based on the name of a constant in C{OpenSSL.SSL}. Must be one of: "SSLv23_METHOD", "SSLv2_METHOD", "SSLv3_METHOD", "TLSv1_METHOD". @type sslmethod: C{str} @param extraCertChain: The path of a file containing one or more certificates in PEM format that establish the chain from a root CA to the CA that signed your C{certKey}. @type extraCertChain: L{str} @param dhParameters: The file name of a file containing parameters that are required for Diffie-Hellman key exchange. If this is not specified, the forward secret C{DHE} ciphers aren't available for servers. @type dhParameters: L{str} @return: a 2-tuple of (args, kwargs), describing the parameters to L{IReactorSSL.listenSSL} (or, modulo argument 2, the factory, arguments to L{SSL4ServerEndpoint}. rsslNmethod z=(-----BEGIN CERTIFICATE-----\n.+?\n-----END CERTIFICATE-----))flagscsg|] }j|jqSrV)r2loadPEMoriginal).0 chainCertPEMrrVrW sz_parseSSL..zOSpecified chain file '%s' doesn't contain any valid certificates in PEM format.) privateKey certificateextraCertChain dhParametersrrV)twisted.internetrgetattrSSLr, getContentr5rrefindallr)DOTALLrmDiffieHellmanParametersfromFiler3rrr)rrrcertKey sslmethodrrrrkwcertPEMkeyPEMprivateCertificatematcheschainCertificatescfrVrrW _parseSSL^sN 5   rc@s$eZdZdZdZddZddZdS)_StandardIOParserz Stream server endpoint string parser for the Standard I/O type. @ivar prefix: See L{IStreamServerEndpointStringParser.prefix}. stdiocCst|S)z Internal parser function for L{_parseServer} to convert the string arguments into structured arguments for the L{StandardIOEndpoint} @param reactor: Reactor for the endpoint )rErrVrVrW _parseServersz_StandardIOParser._parseServercOs ||SrrrRrrkwargsrVrVrWparseStreamServers z#_StandardIOParser.parseStreamServerNr\rprqrrprefixrrrVrVrVrWrs  rc@s,eZdZdZeZdZddZddZ dS)_SystemdParsera Stream server endpoint string parser for the I{systemd} endpoint type. @ivar prefix: See L{IStreamServerEndpointStringParser.prefix}. @ivar _sddaemon: A L{ListenFDs} instance used to translate an index into an actual file descriptor. systemdcCs0t|}|j|}ttd|}t|||S)a| Internal parser function for L{_parseServer} to convert the string arguments for a systemd server endpoint into structured arguments for L{AdoptedStreamServerEndpoint}. @param reactor: An L{IReactorSocket} provider. @param domain: The domain (or address family) of the socket inherited from systemd. This is a string like C{"INET"} or C{"UNIX"}, ie the name of an address family from the L{socket} module, without the C{"AF_"} prefix. @type domain: C{str} @param index: An offset into the list of file descriptors inherited from systemd. @type index: C{str} @return: A two-tuple of parsed positional arguments and parsed keyword arguments (a tuple and a dictionary). These can be used to construct an L{AdoptedStreamServerEndpoint}. AF_)r _sddaemoninheritedDescriptorsrrrD)rRrdomainindexrrrVrVrWrs z_SystemdParser._parseServercO|j|g|Ri|SrrrrVrVrWrsz _SystemdParser.parseStreamServerN) r\rprqrrr-fromEnvironmentrrrrrVrVrVrWrs   rc@s&eZdZdZdZd ddZddZd S) _TCP6ServerParserz Stream server endpoint string parser for the TCP6ServerEndpoint type. @ivar prefix: See L{IStreamServerEndpointStringParser.prefix}. tcp6rrcCst|}t|}t||||S)a Internal parser function for L{_parseServer} to convert the string arguments into structured arguments for the L{TCP6ServerEndpoint} @param reactor: An L{IReactorTCP} provider. @param port: The port number used for listening @type port: int @param backlog: Size of the listen queue @type backlog: int @param interface: The hostname to bind to @type interface: str )rr=rrVrVrWrsz_TCP6ServerParser._parseServercOrrrrrVrVrWr&sz#_TCP6ServerParser.parseStreamServerNrrrVrVrVrWrs   r)tcpunixrrc cstd|}td|}td|}td|}|}||}|||||i}tt|}|D](} | t|vrDt|fVt| fV|}|| }q+| |krO|t|7}q+|| 7}q+t|fVdS)a Tokenize a strports string and yield each token. @param description: a string as described by L{serverFromString} or L{clientFromString}. @type description: L{str} or L{bytes} @return: an iterable of 2-tuples of (C{_OP} or C{_STRING}, string). Tuples starting with C{_OP} will contain a second element of either ':' (i.e. 'next parameter') or '=' (i.e. 'assign parameter value'). For example, the string 'hello:greeting=world' would result in a generator yielding these values:: _STRING, 'hello' _OP, ':' _STRING, 'greet=ing' _OP, '=' _STRING, 'world' rr*=\N)r'rhr(_STRING_OPr^) descriptionemptycolonequals backslashcurrentopsnextOpsiterdescnrVrVrW _tokenize5s&          rcspgitd|}fdd}d}t|D]\}}|tur%||f7}q||kr/||d}q||fS)a Convert a description string into a list of positional and keyword parameters, using logic vaguely like what Python does. @param description: a string as described by L{serverFromString} or L{clientFromString}. @return: a 2-tuple of C{(args, kwargs)}, where 'args' is a list of all ':'-separated C{str}s not containing an '=' and 'kwargs' is a map of all C{str}s which do contain an '='. For example, the result of C{_parse('a:b:d=1:c')} would be C{(['a', 'b', 'c'], {'d': '1'})}. r*cs6t|dkr|ddS|dt|d<dS)Nr.r)lenrGr))sofarrrrVrWaddos z_parse..addrV)r'rr)rrrrtyperrVrrW_parse_s  r)rrUNIXcCsnt|\}}|d}t|}|dur#ttt|}||dd|fS|f||g|ddRi|S)a Parse a strports description into a 2-tuple of arguments and keyword values. @param description: A description in the format explained by L{serverFromString}. @type description: C{str} @param factory: A 'factory' argument; this is left-over from twisted.application.strports, it's not really used. @type factory: L{IProtocolFactory} or L{None} @return: a 3-tuple of (plugin or name, arguments, keyword arguments) rNr.)r_serverParsersget_matchPluginToPrefixr$rupper)rrrr endpointTypeparserpluginrVrVrWrs  (rcCs>|}|D]}t|j||kr|Sqtd|d)z! Match plugin to prefix. zUnknown endpoint type: 'rN)lowerr'rrm)pluginsrrrVrVrWrs rcCsnt|d\}}}t|tur|}|j|g|Ri|S|}|dd|dd}t||g|Ri|S)a_ Construct a stream server endpoint from an endpoint description string. The format for server endpoint descriptions is a simple byte string. It is a prefix naming the type of endpoint, then a colon, then the arguments for that endpoint. For example, you can call it like this to create an endpoint that will listen on TCP port 80:: serverFromString(reactor, "tcp:80") Additional arguments may be specified as keywords, separated with colons. For example, you can specify the interface for a TCP server endpoint to bind to like this:: serverFromString(reactor, "tcp:80:interface=127.0.0.1") SSL server endpoints may be specified with the 'ssl' prefix, and the private key and certificate files may be specified by the C{privateKey} and C{certKey} arguments:: serverFromString( reactor, "ssl:443:privateKey=key.pem:certKey=crt.pem") If a private key file name (C{privateKey}) isn't provided, a "server.pem" file is assumed to exist which contains the private key. If the certificate file name (C{certKey}) isn't provided, the private key file is assumed to contain the certificate as well. You may escape colons in arguments with a backslash, which you will need to use if you want to specify a full pathname argument on Windows:: serverFromString(reactor, "ssl:443:privateKey=C\:/key.pem:certKey=C\:/cert.pem") finally, the 'unix' prefix may be used to specify a filesystem UNIX socket, optionally with a 'mode' argument to specify the mode of the socket file created by C{listen}:: serverFromString(reactor, "unix:/var/run/finger") serverFromString(reactor, "unix:/var/run/finger:mode=660") This function is also extensible; new endpoint types may be registered as L{IStreamServerEndpointStringParser} plugins. See that interface for more information. @param reactor: The server endpoint will be constructed with this reactor. @param description: The strports description to parse. @type description: L{str} @return: A new endpoint which can be used to listen with the parameters given by C{description}. @rtype: L{IStreamServerEndpoint} @raise ValueError: when the 'description' string cannot be parsed. @since: 10.2 Nr.r)rrr"r_endpointServerFactories)rr nameOrPluginrrrr rVrVrWr;s> r;cCs*d\}}||fD] }||||}q|S)a Quote an argument to L{serverFromString} and L{clientFromString}. Since arguments are separated with colons and colons are escaped with backslashes, some care is necessary if, for example, you have a pathname, you may be tempted to interpolate into a string like this:: serverFromString(reactor, "ssl:443:privateKey=%s" % (myPathName,)) This may appear to work, but will have portability issues (Windows pathnames, for example). Usually you should just construct the appropriate endpoint type rather than interpolating strings, which in this case would be L{SSL4ServerEndpoint}. There are some use-cases where you may need to generate such a string, though; for example, a tool to manipulate a configuration file which has strports descriptions in it. To be correct in those cases, do this instead:: serverFromString(reactor, "ssl:443:privateKey=%s" % (quoteStringArgument(myPathName),)) @param argument: The part of the endpoint description string you want to pass through. @type argument: C{str} @return: The quoted argument. @rtype: C{str} z\:)replace)argumentrrcrVrVrWquoteStringArguments rcOst|dkrt|d|d<|d|d<nt|dkr.d|vr(t|d|d<n|d|d<z t|d|d<Wn tyAYnwz t|d|d<Wn tyUYnwz |ddf|d<W|StykY|Sw)a$ Perform any argument value coercion necessary for TCP client parameters. Valid positional arguments to this function are host and port. Valid keyword arguments to this function are all L{IReactorTCP.connectTCP} arguments. @return: The coerced values as a C{dict}. rr.rrrrr)rrKeyErrorrrrVrVrW_parseClientTCP!s0      rc Csi}|D]9}|dddksqz|}Wn ty'Yqwzt|}Wn t y8Yqw||| <qt | S)z Load certificate-authority certificate objects in a given directory. @param directoryPath: a L{unicode} or L{bytes} pointing at a directory to load .pem files from, or L{None}. @return: an L{IOpenSSLTrustRoot} provider. .pem) children asTextModebasenamesplitrrOSErrorr2rSSLErrordigestr7values) directoryPathcaCertschildrdtheCertrVrVrW_loadCAsFromDirHs      rcCs|durdStt|S)z Parse a string referring to a directory full of certificate authorities into a trust root. @param pathName: path name @type pathName: L{unicode} or L{bytes} or L{None} @return: L{None} or L{IOpenSSLTrustRoot} N)rr,)pathNamerVrVrW_parseTrustRootPathds  rcCsL|durdSt|}|durt|Stt|tt|dS)ax Parse a certificate path and key path, either or both of which might be L{None}, into a certificate object. @param certificatePath: the certificate path @type certificatePath: L{bytes} or L{unicode} or L{None} @param keyPath: the private key path @type keyPath: L{bytes} or L{unicode} or L{None} @return: a L{PrivateCertificate} or L{None} Nr.)r,rr5rfromCertificateAndKeyPairr2r4load)certificatePathkeyPath certBytesrVrVrW_privateCertFromPathsss   r cCs|dd}t|dd|dd}t|dd}|dur)tt|||d}n|dur5|jj}|j}nd}d}t|||d}||d<|S) a Parse common arguments for SSL endpoints, creating an L{CertificateOptions} instance. @param kwargs: A dict of keyword arguments to be parsed, potentially containing keys C{certKey}, C{privateKey}, C{caCertsDir}, and C{hostname}. See L{_parseClientSSL}. @type kwargs: L{dict} @return: The remaining arguments, including a new key C{sslContextFactory}. hostnameNrr caCertsDir trustRootclientCertificate)rrrrr)rTr rr6r0rrr3)rr rr configurationprivateKeyOpenSSLcertificateOpenSSLrVrVrW_parseClientSSLOptionss. rcOst|i|}t|S)a Perform any argument value coercion necessary for SSL client parameters. Valid keyword arguments to this function are all L{IReactorSSL.connectSSL} arguments except for C{contextFactory}. Instead, C{certKey} (the path name of the certificate file) C{privateKey} (the path name of the private key associated with the certificate) are accepted and used to construct a context factory. Valid positional arguments to this function are host and port. @keyword caCertsDir: The one parameter which is not part of L{IReactorSSL.connectSSL}'s signature, this is a path name used to construct a list of certificate authority certificates. The directory will be scanned for files ending in C{.pem}, all of which will be considered valid certificate authorities for this connection. @type caCertsDir: L{str} @keyword hostname: The hostname to use for validating the server's certificate. @type hostname: L{unicode} @return: The coerced values as a L{dict}. )rrrrVrVrW_parseClientSSLsrcOsrt|dkr |d|d<z tt|d|d<Wn ty"Ynwz t|d|d<W|Sty8Y|Sw)a Perform any argument value coercion necessary for UNIX client parameters. Valid keyword arguments to this function are all L{IReactorUNIX.connectUNIX} keyword arguments except for C{checkPID}. Instead, C{lockfile} is accepted and has the same meaning. Also C{path} is used instead of C{address}. Valid positional arguments to this function are C{path}. @return: The coerced values as a C{dict}. r.rrrrr)rrrrTrrrVrVrW_parseClientUNIXs   rcCsrt|\}}|d}|}|tvr&ttt|}|j|g|Ri|St||i|}t||fi|S)a Construct a client endpoint from a description string. Client description strings are much like server description strings, although they take all of their arguments as keywords, aside from host and port. You can create a TCP client endpoint with the 'host' and 'port' arguments, like so:: clientFromString(reactor, "tcp:host=www.example.com:port=80") or, without specifying host and port keywords:: clientFromString(reactor, "tcp:www.example.com:80") Or you can specify only one or the other, as in the following 2 examples:: clientFromString(reactor, "tcp:host=www.example.com:80") clientFromString(reactor, "tcp:www.example.com:port=80") or an SSL client endpoint with those arguments, plus the arguments used by the server SSL, for a client certificate:: clientFromString(reactor, "ssl:web.example.com:443:" "privateKey=foo.pem:certKey=foo.pem") to specify your certificate trust roots, you can identify a directory with PEM files in it with the C{caCertsDir} argument:: clientFromString(reactor, "ssl:host=web.example.com:port=443:" "caCertsDir=/etc/ssl/certs") Both TCP and SSL client endpoint description strings can include a 'bindAddress' keyword argument, whose value should be a local IPv4 address. This fixes the client socket to that IP address:: clientFromString(reactor, "tcp:www.example.com:80:" "bindAddress=192.0.2.100") NB: Fixed client ports are not currently supported in TCP or SSL client endpoints. The client socket will always use an ephemeral port assigned by the operating system You can create a UNIX client endpoint with the 'path' argument and optional 'lockfile' and 'timeout' arguments:: clientFromString( reactor, b"unix:path=/var/foo/bar:lockfile=1:timeout=9") or, with the path as a positional argument with or without optional arguments as in the following 2 examples:: clientFromString(reactor, "unix:/var/foo/bar") clientFromString(reactor, "unix:/var/foo/bar:lockfile=1:timeout=9") This function is also extensible; new endpoint types may be registered as L{IStreamClientEndpointStringParserWithReactor} plugins. See that interface for more information. @param reactor: The client endpoint will be constructed with this reactor. @param description: The strports description to parse. @type description: L{str} @return: A new endpoint which can be used to connect with the parameters given by C{description}. @rtype: L{IStreamClientEndpoint} @since: 10.2 r) rrTr_clientParsersrr$rparseStreamClient_endpointClientFactories)rrrranamer rrVrVrWr:s H r:cs Gfdddt}||S)a Connect a protocol instance to an endpoint. This allows using a client endpoint without having to create a factory. @param endpoint: A client endpoint to connect to. @param protocol: A protocol instance. @return: The result of calling C{connect} on the endpoint, i.e. a L{Deferred} that will fire with the protocol when connected, or an appropriate error. @since: 13.1 cseZdZfddZdS)z'connectProtocol..OneShotFactorycsSrrV)rRrrrVrWrXsz5connectProtocol..OneShotFactory.buildProtocolN)r\rprqrrVrrVrWOneShotFactoryWsr)rr)r_rrrVrrWrIFs rIc@r)_WrapperEndpointz2 An endpoint that wraps another endpoint. cC||_||_dS)z2 Construct a L{_WrapperEndpoint}. N_wrappedEndpoint_wrapperFactoryrRwrappedEndpointwrapperFactoryrVrVrWrXd z_WrapperEndpoint.__init__cCs|j||ddS)K Connect the given protocol factory and unwrap its result. cSs|jSr)rTrrVrVrWrqsz*_WrapperEndpoint.connect..)r rr!rrrVrVrWrks  z_WrapperEndpoint.connectNrrVrVrVrWr^ rc@r)_WrapperServerEndpointz? A server endpoint that wraps another server endpoint. cCr)z8 Construct a L{_WrapperServerEndpoint}. Nrr"rVrVrWrXzr%z_WrapperServerEndpoint.__init__cCs|j||S)r&)r rr!rrVrVrWrsz_WrapperServerEndpoint.listenNrrVrVrVrWr(tr'r(cs"tdurtdt|fddS)a Wrap an endpoint which upgrades to TLS as soon as the connection is established. @since: 16.0 @param connectionCreator: The TLS options to use when connecting; see L{twisted.internet.ssl.optionsForClientTLS} for how to construct this. @type connectionCreator: L{twisted.internet.interfaces.IOpenSSLClientConnectionCreator} @param wrappedEndpoint: The endpoint to wrap. @type wrappedEndpoint: An L{IStreamClientEndpoint} provider. @return: an endpoint that provides transport level encryption layered on top of C{wrappedEndpoint} @rtype: L{twisted.internet.interfaces.IStreamClientEndpoint} Nz6OpenSSL not available. Try `pip install twisted[tls]`.cs td|Srbr8)rconnectionCreatorrVrWrszwrapClientTLS..)r9NotImplementedErrorr)r*r#rVr)rWrJs rJ30c Ks| r tdt| t|tr|n|d}t|ts |dur"|n|d}t|}t|}tt|t |t ||d|durEt ||St |t ||||S)a Internal method to construct an endpoint from string parameters. @param reactor: The reactor passed to L{clientFromString}. @param host: The hostname to connect to. @type host: L{bytes} or L{unicode} @param port: The port to connect to. @type port: L{bytes} or L{unicode} @param timeout: For each individual connection attempt, the number of seconds to wait before assuming the connection has failed. @type timeout: L{bytes} or L{unicode} @param bindAddress: The address to which to bind outgoing connections. @type bindAddress: L{bytes} or L{unicode} @param certificate: a string representing a filesystem path to a PEM-encoded certificate. @type certificate: L{bytes} or L{unicode} @param privateKey: a string representing a filesystem path to a PEM-encoded certificate. @type privateKey: L{bytes} or L{unicode} @param endpoint: an optional string endpoint description of an endpoint to wrap; if this is passed then C{host} is used only for certificate verification. @type endpoint: L{bytes} or L{unicode} @return: a client TLS endpoint @rtype: L{IStreamClientEndpoint} z&unrecognized keyword arguments presentzutf-8Nr) TypeErrorrnkeysr?r"r@rrJr6rr r:rGr/) rrrrrrr trustRootsr_rrVrVrW_parseClientTLSs,.r0c@s eZdZdZdZeddZdS)_TLSClientEndpointParserz Stream client endpoint string parser for L{wrapClientTLS} with L{HostnameEndpoint}. @ivar prefix: See L{IStreamClientEndpointStringParserWithReactor.prefix}. tlscOst|g|Ri|S)a Redirects to another function L{_parseClientTLS}; tricks zope.interface into believing the interface is correctly implemented, since the signature is (C{reactor}, C{*args}, C{**kwargs}). See L{_parseClientTLS} for the specific signature description for this endpoint parser. @param reactor: The reactor passed to L{clientFromString}. @param args: The positional arguments in the endpoint description. @type args: L{tuple} @param kwargs: The named arguments in the endpoint description. @type kwargs: L{dict} @return: a client TLS endpoint @rtype: L{IStreamClientEndpoint} )r0)rrrrVrVrWrsz*_TLSClientEndpointParser.parseStreamClientN)r\rprqrrrrrrVrVrVrWr1s r1)rr)rrT)rNNrrNN)r,NNNNN)rrrrrr5 unicodedatarzope.interfacerrr constantlyrr incrementalrrr r r r r twisted.internet.abstractrrtwisted.internet.addressrrrrtwisted.internet.interfacesrrrrrtwisted.internet.protocolrrrrtwisted.internet.stdiorr ImportErrortwisted.internet._resolverrtwisted.internet.deferr twisted.internet.taskr!twisted.loggerr"twisted.pluginr#r$twisted.pythonr%r&twisted.python.compatr'r(r)twisted.python.componentsr*twisted.python.failurer+twisted.python.filepathr,twisted.python.systemdr-_idnar/r0 OpenSSL.SSLr1rtwisted.internet.sslr2r3r4r5r6r7twisted.protocols.tlsr9_TLSMemoryBIOFactory__all__rKrsIStreamServerEndpointrEIProcessTransport IConsumer IPushProducerrrrrHIStreamClientEndpointrFrr<r=r>r?rrGrBrCr@rArDrrrrrrrrangerrrrrrrrr;rrrrr rrrrr:rIrr(rJr0r1rVrVrVrWs                Q_   @C%/IFV*7#( / " ^0& *# I#'(T# D