ϪfD UdZddlZddlZddlZddlmZmZddlmZm Z m Z ddl m Z ddl mZddlmZmZmZmZmZmZmZmZmZmZmZmZddlmZmZdd lm Z m!Z!m"Z"m#Z#m$Z$m%Z%dd l&m'Z(m)Z*m+Z,dd l-m.Z.m/Z/dd l0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;mZ>m?Z?dd l@mAZAddlBmCZCmDZDddlEmFZFddlGmHZHmIZJddlKmLZLmMZMmNZNerddlOmPZPddlBmQZQeHjrddlSmTZTndZTee3GddZUee=GddZVee=GddZWedefZXeeXeeYdfeeZeYffZ[edeeZeXeeYdfeeZeYffZ\GddZ]ee8e9Gd d!Z^ed"eeZe\fZ_eedefeeYdfeeZeYffZ`ee6e;e?Gd#d$e^ZaeHjr eeae:ee2Gd%d&eZbGd'd(e jZdgZeeeZefd)<y)*z8 Very basic functionality for a Reactor implementation. N)ABCabstractmethod)heapifyheappopheappush) format_stack) FrameType) TYPE_CHECKINGAnyCallableDictListNewTypeOptionalSequenceSetTupleUnioncast)classImplements implementer)abstractdefererrorfdescmainthreads)ComplexResolverSimplifier GAIResolverSimpleResolverComplexifier)Deferred DeferredList)IAddress IConnector IDelayedCallIHostnameResolver IProtocol IReactorCoreIReactorFromThreadsIReactorPluggableNameResolverIReactorPluggableResolverIReactorThreads IReactorTimeIReadDescriptorIResolverSimpleIWriteDescriptor_ISupportsExitSignalCapturing) ClientFactory)logreflect)Failure)platformseconds)SignalHandling_WithoutSignalHandling_WithSignalHandling)Client) threadable) ThreadPoolceZdZUdZdZeeed<dZee eed<e fde de de fde ed eeefd e dgdfd e dgdfd e ge fd dfdZd e fdZddZde d dfdZde d dfdZddZd efdZded efdZded efdZd efdZy) DelayedCallFN_reprcreatortimefunc.argskwcancelresetr7returnc||||f\|_|_|_|_||_||_||_dx|_|_d|_ |jrtdd|_ yy)aR @param time: Seconds from the epoch at which to call C{func}. @param func: The callable to call. @param args: The positional arguments to pass to the callable. @param kw: The keyword arguments to pass to the callable. @param cancel: A callable which will be called with this DelayedCall before cancellation. @param reset: A callable which will be called with this DelayedCall after changing this DelayedCall's scheduled execution time. The callable should adjust any necessary scheduling details to ensure this DelayedCall is invoked at the new appropriate time. @param seconds: If provided, a no-argument callable which will be used to determine the current time any time that information is needed. rN) rCrDrErFresetter cancellerr7 cancelledcalled delayed_timedebugrrB)selfrCrDrErFrGrHr7s 7/usr/lib/python3/dist-packages/twisted/internet/base.py__init__zDelayedCall.__init__Wsj448tR3G0 49di  '(( ::'>#2.DL c4|j|jzS)z Return the time at which this call will fire @return: The number of seconds after the epoch at which this call is scheduled to be made. rCrQrSs rTgetTimezDelayedCall.getTimezsyy4,,,,rVc|jrtj|jrtj|j |d|_|j rt||_|` |` |` y)z Unschedule this call @raise AlreadyCancelled: Raised if this call has already been unscheduled. @raise AlreadyCalled: Raised if this call has already been made. r8N) rOrAlreadyCancelledrP AlreadyCalledrNrRreprrArDrErFrYs rTrGzDelayedCall.cancels\ >>(( ( [[%% % NN4 DNzz!$Z  49dgrVsecondsFromNowc |jrtj|jrtj|j |z}||j kr d|_||_|j|y||j z |_y)aY Reschedule this call for a different time @param secondsFromNow: The number of seconds from the time of the C{reset} call at which this call will be scheduled. @raise AlreadyCancelled: Raised if this call has been cancelled. @raise AlreadyCalled: Raised if this call has already been made. rKN) rOrr\rPr]r7rCrQrM)rSr_newTimes rTrHzDelayedCall.resetsr >>(( ( [[%% %lln~5G"$'!#  d#$+dii$7!rV secondsLaterc|jrtj|jrtj|xj |z c_|j dkr"|j |j|yy)aQ Reschedule this call for a later time @param secondsLater: The number of seconds after the originally scheduled time for which to reschedule this call. @raise AlreadyCancelled: Raised if this call has been cancelled. @raise AlreadyCalled: Raised if this call has already been made. rKN)rOrr\rPr]rQactivate_delayrM)rSrbs rTdelayzDelayedCall.delaysf >>(( ( [[%% %    -   3&##% d#'rVcP|xj|jz c_d|_y)NrKrXrYs rTrdzDelayedCall.activate_delays T&&& rVc8|jxs |j S)zDetermine whether this call is still pending @return: True if this call has not yet been made or cancelled, False otherwise. )rOrPrYs rTactivezDelayedCall.actives NN1dkk22rVotherc`t|tr|j|jkStS)z Implement C{<=} operator between two L{DelayedCall} instances. Comparison is based on the C{time} attribute (unadjusted by the delayed time).  isinstancer@rCNotImplementedrSris rT__le__zDelayedCall.__le__s' e[ )99 * *! !rVc`t|tr|j|jkStS)z Implement C{<} operator between two L{DelayedCall} instances. Comparison is based on the C{time} attribute (unadjusted by the delayed time). rkrns rT__lt__zDelayedCall.__lt__s' e[ )99uzz) )! !rVc |j |jSt|drtt|jdd}|9t|jdd}| t|jdd}||d|}|"t j |j}nd}|j }dt||j|z |j|jfzg}||jd|d f|jrh|jd j|jDcgc]}t j |c}|jr|jd |jrc|jd j|jj!Dcgc]\}}|d t j |!c}}|jd |j"-|jd dj|j"z|jddj|Scc}wcc}}w)z Implement C{repr()} for L{DelayedCall} instances. @returns: String containing details of the L{DelayedCall}. NrD __qualname____name__im_class.z.)rAhasattrgetattrrDr4 safe_reprr7idrCrPrOextendrEappendjoinrFitemsrB)rSrDimClassnowLekvs rT__repr__zDelayedCall.__repr__s :: !::  4 499nd;D|tyy*d;#%diiTBG*")!D62|((3Dlln <$xS$++t~~F G    HHc4% &yy$))#LQG$5$5a$8#LMN77HHTNwwIIEIWW]]_U6AqA3a 1 1! 456U HHSM << # HH8FKK #'#7#7#G j   0TZZo>?rVresultc$ |j|\}}|j|=|jt|tr0|j |j ||j y|j|y#t$rYywxYwr) rrGrlr5rrgetErrorMessagecallbackKeyError)rSrrrrrs rT _checkTimeoutzThreadedResolver._checkTimeout3s .'+';';N'K $L*$$^4    &'*$$TZZf6L6L6N%OP%%f-   sB BBtimeoutc|r t|}nd}t}tjt t |j t t|j jtj|}t t|j j||j||}||f|j|<|j|j ||}|S)a1 See L{twisted.internet.interfaces.IResolverSimple.getHostByName}. Note that the elements of C{timeout} are summed and the result is used as a timeout for the lookup. Any intermediate timeout or retry logic is left up to the platform via L{socket.gethostbyname}. <)sumr!rdeferToThreadPoolrr)rr, getThreadPoolsocket gethostbynamer- callLaterrraddBothr)rSrr timeoutDelayrrr_s rT getHostByNamezThreadedResolver.getHostByNameCs we?Z@ded-e5d.e6fd/e7d7e7deAf d8ZBd9eAddfd:ZCd9eAddfd;ZDde(eEfd<ZFdLd=ZGdeefd>ZHdLd?ZIeJjrNeLJdZMdZNdZOdLd@ZPdAe5d.e6fd/e7d0e7ddfdBZQdLdCZRdLdDZSdLdEZTdeLfdFZUdGe5d.e6fd/e7d0e7ddfdHZVdIe)ddfdJZWxZXSdAe5d.e6fd/e7d0e7ddfdKZQxZXS)Qra Default base class for Reactors. @ivar _stopped: A flag which is true between paired calls to C{reactor.run} and C{reactor.stop}. This should be replaced with an explicit state machine. @ivar _justStopped: A flag which is true between the time C{reactor.stop} is called and the time the shutdown system event is fired. This is used to determine whether that event should be fired after each iteration through the mainloop. This should be replaced with an explicit state machine. @ivar _started: A flag which is true from the time C{reactor.run} is called until the time C{reactor.run} returns. This is used to prevent calls to C{reactor.run} on a running reactor. This should be replaced with an explicit state machine. @ivar running: See L{IReactorCore.running} @ivar _registerAsIOThread: A flag controlling whether the reactor will register the thread it is running in as the I/O thread when it starts. If C{True}, registration will be done, otherwise it will not be. @ivar _exitSignal: See L{_ISupportsExitSignalCapturing._exitSignal} @ivar _installSignalHandlers: A flag which indicates whether any signal handlers will be installed during startup. This includes handlers for SIGCHLD to monitor child processes, and SIGINT, SIGTERM, and SIGBREAK @ivar _signals: An object which knows how to install and uninstall the reactor's signal-handling behavior. TFN_signalstwisted.internet.reactorrIct|g|_i|_g|_g|_d|_d|_d|_d|_ d|_ t|_ d|_ |jdd|j|jdd|j |jdd|j"t%j&r|j)|j+y)NrFrstartupshutdown)superrUthreadCallQueue_eventTriggers_pendingTimedCalls_newTimedCalls_cancellationsrunning_started _justStopped_startedBeforeset_internalReaderswakeraddSystemEventTrigger_reallyStartRunningcrash disconnectAllr6supportsThreads _initThreads installWaker)rS __class__s rTrUzReactorBase.__init__ms 24;=5713  !#+.% ""8Y8P8PQ ""8ZD ""8Z9K9KL  # # %     rV_installSignalHandlersinstallSignalHandlersc:|r|jStS)z Get an appropriate signal handling object. @param installSignalHandlers: Indicate whether to even try to do any signal handling. If C{False} then the result will be a no-op implementation. )_signalsFactoryr:rSr$s rT_makeSignalHandlingzReactorBase._makeSignalHandlings !'') )%''rVcXt|j|j|jS)z Get a signal handling object that implements the basic behavior of stopping the reactor on SIGINT, SIGBREAK, and SIGTERM. )r;sigIntsigBreaksigTermrYs rTr&zReactorBase._signalsFactorys& # KK MM LL  rVreaderc\|jj||j|y)z Add a read descriptor which is part of the implementation of the reactor itself. The read descriptor will not be removed by L{IReactorFDSet.removeAll}. N)radd addReaderrSr-s rT_addInternalReaderzReactorBase._addInternalReaders$ !!&) vrVc\|jj||j|y)zm Remove a read descriptor which is part of the implementation of the reactor itself. N)rr removeReaderr1s rT_removeInternalReaderz!ReactorBase._removeInternalReaders& $$V, &!rVc|j| |j|jjy#|jjwxYw)N)r$) startRunningmainLoopr  uninstallr's rTrunzReactorBase.runsC 0EF & MMO MM # # %DMM # # %s ?Ac|jr~ |jrN|j|j}|jxr|}|j ||jrNt j d|jr}yy#t$r,t j dt jYCwxYw)NzMain loop terminated.zUnexpected error in main loop.) rrunUntilCurrentrr doIterationr3rrr)rSt2ts rTr8zReactorBase.mainLoopsmm 1mm((*B +A$$Q' mm/0mm! 89  sAB 2CCcXttj|jdz)Nz did not implement installWakerNotImplementedErrorr4qualr"rYs rTr!zReactorBase.installWaker%! LL (+L L  rVcR|jr|jjyy)z) Wake up the event loop. N)rwakeUprYs rTrFzReactorBase.wakeUps  :: JJ    rVrecXttj|jdz)zV Do one iteration over the readers and writers which have been added. z did not implement doIterationrArSres rTr=zReactorBase.doIterations'" LL (+K K  rVcXttj|jdz)Nz did not implement addReaderrAr1s rTr0zReactorBase.addReader%! LL (+I I  rVwritercXttj|jdz)Nz did not implement addWriterrArSrKs rT addWriterzReactorBase.addWriterrJrVcXttj|jdz)Nz did not implement removeReaderrAr1s rTr4zReactorBase.removeReaderrDrVcXttj|jdz)Nz did not implement removeWriterrArMs rT removeWriterzReactorBase.removeWriterrDrVcXttj|jdz)Nz did not implement removeAllrArYs rT removeAllzReactorBase.removeAllrJrVcXttj|jdz)Nz did not implement getReadersrArYs rT getReaderszReactorBase.getReaders%! LL (+J J  rVcXttj|jdz)Nz did not implement getWritersrArYs rT getWriterszReactorBase.getWritersrVrVrrc|stjdStj|rtj|S|jj ||S)z8 Return a Deferred that will resolve a hostname.z0.0.0.0)rrr isIPAddressrr)rSrrs rTresolvezReactorBase.resolve sJ ==+ +    %==& &}}**499rVcp|jrtjdd|_d|_d|_y)zD See twisted.internet.interfaces.IReactorCore.stop. z&Can't stop reactor that isn't running.TN)_stoppedrReactorNotRunningrrrYs rTstopzReactorBase.stops4 ==))*RS S  "rVcZd|_d|_|jdd|jy)z See twisted.internet.interfaces.IReactorCore.crash. Reset reactor state tracking attributes and re-initialize certain state-transition helpers which were set up in C{__init__} but later destroyed (through use). Frr N)rrrrrYs rTrzReactorBase.crashs*   ""8Y8P8PQrVnumberframecrtjd|j|j||_y)z Handle a SIGINT interrupt. @param number: See handler specification in L{signal.signal} @param frame: See handler specification in L{signal.signal} zReceived SIGINT, shutting down.Nr3rcallFromThreadr_ _exitSignalrSrarbs rTr*zReactorBase.sigInt+s+ 12 DII&!rVcrtjd|j|j||_y)z Handle a SIGBREAK interrupt. @param number: See handler specification in L{signal.signal} @param frame: See handler specification in L{signal.signal} z!Received SIGBREAK, shutting down.Nrdrgs rTr+zReactorBase.sigBreak6s+ 34 DII&!rVcrtjd|j|j||_y)z Handle a SIGTERM interrupt. @param number: See handler specification in L{signal.signal} @param frame: See handler specification in L{signal.signal} z Received SIGTERM, shutting down.Nrdrgs rTr,zReactorBase.sigTermAs+ 23 DII&!rVc|j}|D]:}tj||jt t j <y)z2Disconnect every reader, and writer in the system.N)rSr3callWithLoggerconnectionLostr5rCONNECTION_LOST)rS selectablesr-s rTrzReactorBase.disconnectAllLsCnn& ! F   --wt7K7K/L  rVcF|j|j|y)zG See twisted.internet.interfaces.IReactorCore.iterate. N)r<r=rHs rTiteratezReactorBase.iterateTs  rV eventTypec`|jj|}||jyy)zO See twisted.internet.interfaces.IReactorCore.fireSystemEvent. N)rgetr)rSrqevents rTfireSystemEventzReactorBase.fireSystemEvent[s/##'' 2   OO  rVrr.rErctj|s J|d||jvrt|j|<t ||j|j ||g|i|fS)zU See twisted.internet.interfaces.IReactorCore.addSystemEventTrigger.  is not callable)builtinsrrrrr)rSrrqrrErs rTrz!ReactorBase.addSystemEventTriggercs  *Ixj8H,II* D// /-=-?D   *9##I.998&*.4   rV triggerIDcJ|\}}|j|j|y)zX See twisted.internet.interfaces.IReactorCore.removeSystemEventTrigger. N)rr)rSryrqrs rTremoveSystemEventTriggerz$ReactorBase.removeSystemEventTriggerzs'& 6 I&44V $$VeV,##  ##%lln%%4+B+B1+E+J+Jc+Q4223D~~##q(#  3&##%00$7   49900%%4+B+B1+E+J+Jc+Q8   " $##c$*A*A&Ba&GG"#D 22'!++'D # D++ ,    %D    , e%GGI6!  <<+A:AJA.557??gNNAIAGGAJ $'s0H'/-I K K'II B KKcx|jttt||jd|_y)NT)r _GAIResolverrr,r usingThreadsrYs rTr zReactorBase._initThreadshs1  $ $T/48$:L:LM !%D rVrct|s J|d|jj|||f|jy)zl See L{twisted.internet.interfaces.IReactorFromThreads.callFromThread}. rwN)rrrrFrSrrErs rTrezReactorBase.callFromThreadqsCA; 61#%5 6 6;  ' 'D&(9 : KKMrVctddd|_|j|jj|_|j dd|j |_y)zO Create the threadpool accessible with callFromThread. r r rr N)r> threadpoolr}start_threadpoolStartupIDr_stopThreadPoolthreadpoolShutdownIDrYs rT_initThreadPoolzReactorBase._initThreadPoolsR)B0JKDO(,(<(rrrr rerrrrrr __classcell__)r"s@rTrr?sG:HILK 67Hn7)H8$)D( ( (. (    T"O""&&&1$ E   % T   D  0 T  ? t  #3   4o7G&G HI  D1  D!12 3A : :"*3- : # :# R "S "))< " " "s "8I+> "$ " "c "(9*= " " U T    38$        .=.=T=  c* 39 EK  . ! ($($(> $">*G&.sCx&8AGOU ( (!K!D! ,!7 !+%+8A-H x!%%% ## % c3h' 06 BH     & #& #: # J%c3h/ J8> JJP J  J Ac Ad A ;c3h' ;06 ;BH ;  ;rVrceZdZdZdZdZdedededdfdZ dd Z e dd Z dd Z dd Zdd ZdedeefdZdeddfdZdeddfdZdefdZdefdZy) BaseConnectorzm Basic implementation of L{IConnector}. State can be: "connecting", "connected", "disconnected" NrfactoryrrrIc<d|_||_||_||_y)N disconnected)rrrr)rSrrrs rTrUzBaseConnector.__init__s $    rVc|jdk(r|jy|jdk(r)|jJ|jjyy)z!Disconnect whatever our state is. connecting connectedN)rstopConnecting transportloseConnectionrYs rT disconnectzBaseConnector.disconnectsK :: %    ! ZZ; &>>- -- NN ) ) +'rVcyrrrYs rT_makeTransportzBaseConnector._makeTransports rVc|jdk7r tdd|_|js!|jj d|_|j |_|jR|jj|j|j jtj|_ |jj|y)z"Start connection to remote server.rzcan't connect in this staterr8N)r RuntimeErrorfactoryStartedrdoStartrrrrrfailIfNotConnectedr TimeoutError timeoutIDstartedConnectingrYs rTconnectzBaseConnector.connects :: '<= =! "" LL ""#D +/+>+>+@ << #!\\33 dnn??ASASAUDN &&t,rVc|jdk7rtjd|jJd|_|jj tj |`y)zStop attempting to connect.rzwe're not trying to connectNr)rrNotConnectingErrorrr UserErrorrYs rTrzBaseConnector.stopConnectingsU :: %**+HI I~~)))#  ))%//*;< NrVcv|j |jj|`yy#t$rYwxYwr)rrGrrYs rT cancelTimeoutzBaseConnector.cancelTimeoutsA >> % %%' &  s , 88addrcfd|_|j|jj|S)Nr)rrr buildProtocol)rSrs rTrzBaseConnector.buildProtocols*   ||))$//rVreasonc|jd|_d|_|jj |||jdk(r"|jj d|_yyNrr)rrrrclientConnectionFaileddoStoprrSrs rTconnectionFailedzBaseConnector.connectionFailed sY #  ++D&9 :: ' LL   !"#D  (rVcd|_|jj|||jdk(r"|jjd|_yyr)rrclientConnectionLostrrrs rTrlzBaseConnector.connectionLostsF#  ))$7 :: ' LL   !"#D  (rVcXttj|jdz)Nz! did not implement getDestinationrArYs rTgetDestinationzBaseConnector.getDestinations%! LL (+Q Q  rVcdjtj|jt ||j |j S)Nz<{} instance at 0x{:x} {} {}>)formatr4rCr"rrrrYs rTrzBaseConnector.__repr__$s?.55 LL ( tH JJ    !   rVr)rIr<)rtrrsrrrr2rrrUrrrrrrr#rr'rr5rrlrrrrrVrTrrs IN$/4?J ,  - 0(0x /B0 $w$4$$W$$   # rVrceZdZUdZdZej ed<dZejed<dej fdZ de e fdZ y)BasePortziBasic implementation of a ListeningPort. Note: This does not actually implement IListeningPort. N addressFamily socketTyperIctj|j|j}|jdt j |j |S)NF)rrr setblockingr_setCloseOnExecfileno)rSss rTcreateInternetSocketzBasePort.createInternetSocket6sA MM$,,doo > e ahhj)rVcXtdtj|jz)zRaises a RuntimeErrorzdoWrite called on a %s)rr4rCr"rYs rTdoWritezBasePort.doWrite<s 3gll4>>6RRSSrV)rtrrsrrr AddressFamilyrr SocketKindrrr5rrrVrTrr-sL +/M6''.$(J!!(fmm T'*TrVr__all__)grrxrrabcrrheapqrrr tracebackrtypesr typingr r r r rrrrrrrrzope.interfacerrtwisted.internetrrrrrrtwisted.internet._resolverrrrrr rtwisted.internet.deferr!r"twisted.internet.interfacesr#r$r%r&r'r(r)r*r+r,r-r.r/r0r1twisted.internet.protocolr2twisted.pythonr3r4twisted.python.failurer5twisted.python.runtimer6r7rr r9r:r;twisted.internet.tcpr<r=rtwisted.python.threadpoolr>r@rrrrr_ThreePhaseEventTriggerrrrr _ThreadCallrrFileDescriptorrrrrrVrTrsr   #,,"    8II :"4'*FQQ+&84J \FFFR _GGGT _ * * *#+38"4#U63;%7c6k9JJ!(# #.fck0BDfDU UV! KK\ *,EF."."G."b)56S1S+TUHS#X&fck(:Df