ϪfzSdZddlZddlmZmZddlmZmZddlm Z m Z ddl m Z ddl mZmZmZddlmZd ZGd d eZGd d eZGddeZGddeZGddeZGddeZGddeZGddeZGddeZGddeZGddeZGd d!eZGd"d#Z y)$z] Resource limiting policies. @seealso: See also L{twisted.protocols.htb} for rate limiting. N)OptionalType)directlyProvides providedBy)error interfaces)ILoggingContext) ClientFactoryProtocol ServerFactory)logctj|r|j}n|jj}|d|jjdS)zY Compute a log prefix for a wrapper and the object it wraps. @rtype: C{str} z ())r r logPrefix __class____name__)wrapperwrappedrs } provider to which L{IProtocol} method calls onto this L{ProtocolWrapper} will be proxied. @ivar factory: The L{WrappingFactory} which created this L{ProtocolWrapper}. rfactoryWrappingFactorywrappedProtocolc ||_||_yN)rr)selfrrs r__init__zProtocolWrapper.__init__5s / rc.t||jS)zo Use a customized log prefix mentioning both the wrapped protocol and the current one. )rrrs rrzProtocolWrapper.logPrefix;s !t';';<} for test purpose. r)reactortwisted.internetr callLaterrperiodfuncrs rrzThrottlingFactory.callLater -  ..rc.|xj|z c_y)zH Called by protocol to tell us more bytes were written. N)rrlengths rrpz!ThrottlingFactory.registerWrittens &(rc.|xj|z c_y)zE Called by protocol to tell us more bytes were read. N)rrs rrxzThrottlingFactory.registerReads v%rc2|j|jkDrV|jt|j|jz dz }|j ||j |_d|_|j d|j|_y)z: Checks if we've passed bandwidth limits. ?rr/N) rrr}floatrrrcheckReadBandwidthrr throttleTimes rrz$ThrottlingFactory.checkReadBandwidthsz    /    !$"5"56G3NL%)^^L$BVBV%WD "$(NN1d6M6M$N!rc2|j|jkDrV|jt|j|jz dz }|j ||j |_d|_|j d|j|_y)Nrrr/) rrrrrrrcheckWriteBandwidthrrs rrz%ThrottlingFactory.checkWriteBandwidths}  ! !DOO 3    !!$"8"89DOOKsRL&*nnd33'D #"#%)^^At7O7O%P"rctjd|z|jjD]}|j y)z2 Throttle reads on all protocols. zThrottling reads on %sN)r msgrUkeysr}ris rr}zThrottlingFactory.throttleReadss< (4/0$$& A OO  rcd|_tjd|z|jj D]}|j y)z9 Stop throttling reads on all protocols. NzStopped throttling reads on %s)rr rrUrrris rrz!ThrottlingFactory.unthrottleReads%sF"& 0478$$& A    rctjd|z|jjD]}|j y)z3 Throttle writes on all protocols. zThrottling writes on %sN)r rrUrrris rrz ThrottlingFactory.throttleWrites.s> )D01$$& A    rcd|_tjd|z|jj D]}|j y)z: Stop throttling writes on all protocols. NzStopped throttling writes on %s)rr rrUrrris rrz"ThrottlingFactory.unthrottleWrites6sF#' 1D89$$& !A    !rcD|jdk(r8|j|j|j|j |j|j kr+|xjdz c_t j||Stjdy)Nrr/zMax connection count reached!) rrrrrrrrdr rres rrdzThrottlingFactory.buildProtocol?s   1 $~~)'')*((*   $"9"9 9  A % "00t< < GG3 4rctj|||xjdzc_|jdk(r|j|jj |j |j j |j |j j |j|jj yyyNr/r)rrHrrcancelrrrris rrHz$ThrottlingFactory.unregisterProtocolMs**43 !   1 $%%1&&--/((4))002&&2''..0))5**1136 %r)rrLrMrNrnrRsysmaxsizer rrprxrrr}rrrrdrHrPrrrrs["H ;; *&/) & O Q !  4rrceZdZdZdZy)SpewingProtocolc`tjd|ztj||y)Nz Received: %r)r rrrFr)s rrFzSpewingProtocol.dataReceived\s# %&$$T40rc`tjd|ztj||y)Nz Sending: %r)r rrr(r)s rr(zSpewingProtocol.write`s#  $%dD)rN)rrLrMrFr(rPrrrr[s 1*rrceZdZeZy)SpewingFactoryN)rrLrMrrRrPrrrresHrrc"eZdZdZdZdZdZy)LimitConnectionsByPeerci|_yr)peerConnectionsr"s r startFactoryz#LimitConnectionsByPeer.startFactoryls !rc|d}|jj|d}||jk\ry|dz|j|<tj ||S)Nrr/)rgetmaxConnectionsPerPeerrrd)rrfpeerHostrs rrdz$LimitConnectionsByPeer.buildProtocolos\7..228Q? d88 8)81)<X&,,T488rc|jd}|j|xxdzcc<|j|dk(r|j|=yyr)r3r)rrjrs rrHz)LimitConnectionsByPeer.unregisterProtocolwsM99;q> X&!+&    )Q .$$X. /rN)rrLrMrrrdrHrPrrrris"9/rrcFeZdZUdZdZdZdZeee e d<dZ dZ dZ y)LimitTotalConnectionsFactorya Factory that limits the number of simultaneous connections. @type connectionCount: C{int} @ivar connectionCount: number of current connections. @type connectionLimit: C{int} or L{None} @cvar connectionLimit: maximum number of connections. @type overflowProtocol: L{Protocol} or L{None} @cvar overflowProtocol: Protocol to use for new connections when connectionLimit is exceeded. If L{None} (the default value), excess connections will be closed immediately. rNoverflowProtocolc|j|j|jkr|j}n|jy|j}||_t ||}|xjdz c_|Sr.)connectionLimitrrRrrr)rrfrrRs rrdz*LimitTotalConnectionsFactory.buildProtocolsu    '4+?+?$BVBV+V"mmoO  " " *#335O"&"49 !rcyrrPris rr%z-LimitTotalConnectionsFactory.registerProtocols rc.|xjdzc_yr.)rris rrHz/LimitTotalConnectionsFactory.unregisterProtocols !r)rrLrMrNrrrrrr rlrdr%rHrPrrrr~s6 OO15htH~.5  "rrcHeZdZdZdZd dZdZdZdZdZ d Z d Z d Z y) TimeoutProtocolzN Protocol that automatically disconnects when the connection is idle. cptj|||d|_d|_|j |y)z Constructor. @param factory: An L{TimeoutFactory}. @param wrappedProtocol: A L{Protocol} to wrapp. @param timeoutPeriod: Number of seconds to wait for activity before timing out. N)rr timeoutCall timeoutPeriod setTimeout)rrrrs rr zTimeoutProtocol.__init__s2   w@!  &rNc|j||_|6|jj|j|j|_yy)z Set a timeout. This will cancel any existing timeouts. @param timeoutPeriod: If not L{None}, change the timeout period. Otherwise, use the existing value. N) cancelTimeoutrrr timeoutFuncr)rrs rrzTimeoutProtocol.setTimeoutsK *  $#||55""D$4$4 D  %rcd|_|jr# |jjd|_yy#tjtj f$rY.wxYw)zg Cancel the timeout. If the timeout was already cancelled, this does nothing. N)rrrr AlreadyCalledAlreadyCancelledr"s rrzTimeoutProtocol.cancelTimeouts` "      '') $D  '')?)?@  s8#AAch|jr&|jj|jyy)zQ Reset the timeout, usually because some activity just happened. N)rresetrr"s r resetTimeoutzTimeoutProtocol.resetTimeouts,       " "4#5#5 6 rcP|jtj||yr)rrr(r)s rr(zTimeoutProtocol.writes dD)rcP|jtj||yr)rrr,rus rr,zTimeoutProtocol.writeSequences %%dC0rcP|jtj||yr)rrrFr)s rrFzTimeoutProtocol.dataReceiveds $$T40rcP|jtj||yr)rrrIrJs rrIzTimeoutProtocol.connectionLosts &&tV4rc$|jy)z This method is called when the timeout is triggered. By default it calls I{loseConnection}. Override this if you want something else to happen. N)r1r"s rrzTimeoutProtocol.timeoutFuncs rr) rrLrMrNr rrrr(r,rFrIrrPrrrrs4 ' $7*115rrc(eZdZdZeZddZdZdZy)TimeoutFactoryz% Factory for TimeoutWrapper. c>||_tj||yr)rrr )rrTrs rr zTimeoutFactory.__init__s*  ~6rcp|j||jj||jS)N)r)rRrTrdrres rrdzTimeoutFactory.buildProtocols8}}     - -d 3,,  rc2ddlm}|j||Srrrs rrzTimeoutFactory.callLater rrN)i) rrLrMrNrrRr rdrrPrrrrsH7 /rrcDeZdZd dZdZdZdZdZdZdZ d Z d Z y) TrafficLoggingProtocolNc\tj|||||_||_||_y)a @param factory: factory which created this protocol. @type factory: L{protocol.Factory}. @param wrappedProtocol: the underlying protocol. @type wrappedProtocol: C{protocol.Protocol}. @param logfile: file opened for writing used to write log messages. @type logfile: C{file} @param lengthLimit: maximum size of the datareceived logged. @type lengthLimit: C{int} @param number: identifier of the connection. @type number: C{int}. N)rr logfile lengthLimit_number)rrrrrnumbers rr zTrafficLoggingProtocol.__init__s,   w@ & rct|jj|dz|jjy)N )rr(flush)rlines r_logzTrafficLoggingProtocol._log)s( 4$;' rcx|jr-t||jkDr|d|jdz dz}|S)N z <... elided>)rrqr)s r _mungeDataz!TrafficLoggingProtocol._mungeData-s>   D D,<,< </$**R/0>AD rcN|jdtj|S)N*)rrconnectionMader"s rrz%TrafficLoggingProtocol.connectionMade3s #--d33rc|jd|j|j|fztj ||SNzC %d: %r)rrrrrFr)s rrFz#TrafficLoggingProtocol.dataReceived7s8 * dood.CDDE++D$77rcn|jd|j|fztj||Sr)rrrrIrJs rrIz%TrafficLoggingProtocol.connectionLost;s/ * f556--dF;;rc|jd|j|j|fztj ||S)NzS %d: %r)rrrrr(r)s rr(zTrafficLoggingProtocol.write@s8 * dood.CDDE$$T400rc |jd|j|Dcgc]}|j|c}fztj ||Scc}w)Nz SV %d: %r)rrrrr,)riovecds rr,z$TrafficLoggingProtocol.writeSequenceDsI +E/Rq0B/R SST,,T5990SsA cj|jd|jfztj|S)NzS %d: *)rrrr1r"s rr1z%TrafficLoggingProtocol.loseConnectionHs* )t||o-.--d33rr) rrLrMr rrrrFrIr(r,r1rPrrrrs/$ 48< 1:4rrc.eZdZeZdZddZdZdZdZ y)TrafficLoggingFactoryrNcL||_||_tj||yr) logfilePrefixrrr )rrTrrs rr zTrafficLoggingFactory.__init__Rs"*&  ~6rct|dS)Nw)openrBs rrzTrafficLoggingFactory.openWsD#rc|xjdz c_|j|jdzt|jz}|j ||j j |||j|jS)Nr/-)_counterrrstrrRrTrdr)rrfrs rrdz#TrafficLoggingFactory.buildProtocolZsr  ))D..4s4==7IIJ}}     - -d 3     MM   rcd|_y)zN Reset the value of the counter used to identify connections. rN)r r"s r resetCounterz"TrafficLoggingFactory.resetCounteres  rr) rrLrMrrRr r rrdrrPrrrrMs %HH7   rrcHeZdZUdZdZeeed<dZdZ dZ dZ dZ dZ y) TimeoutMixinaL Mixin for protocols which wish to timeout connections. Protocols that mix this in have a single timeout, set using L{setTimeout}. When the timeout is hit, L{timeoutConnection} is called, which, by default, closes the connection. @cvar timeOut: The number of seconds after which to timeout the connection. NtimeOutc2ddlm}|j||Srrrs rrzTimeoutMixin.callLater{rrc|j3|j&|jj|jyyy)a Reset the timeout count down. If the connection has already timed out, then do nothing. If the timeout has been cancelled (probably using C{setTimeout(None)}), also do nothing. It's often a good idea to call this when the protocol has received some meaningful input from the other end of the connection. "I've got some data, they're still there, reset the timeout". N)_TimeoutMixin__timeoutCallrrr"s rrzTimeoutMixin.resetTimeouts:    )dll.F    $ $T\\ 2/G )rcb|j}||_|jC|$ |jjd|_|S|jj ||S|!|j||j|_|S#tjtj f$rYpwxYw)z Change the timeout period @type period: C{int} or L{None} @param period: The period, in seconds, to change the timeout to, or L{None} to disable the timeout. N) rrrrrrrr_TimeoutMixin__timedOut)rrprevs rrzTimeoutMixin.setTimeouts||    )~&&--/&*"  ""((0  !%!HD  ..0C0CDsB#B.-B.c2d|_|jyr)rtimeoutConnectionr"s r __timedOutzTimeoutMixin.__timedOuts!  rc8|jjy)z Called when the connection times out. Override to define behavior other than dropping the connection. N)r&r1r"s rrzTimeoutMixin.timeoutConnections %%'r)rrLrMrNrrintrlrrrrrrrPrrrrls5"GXc]!M/ 34!(rr)!rNrtypingrrzope.interfacerrrrrtwisted.internet.interfacesr twisted.internet.protocolr r r twisted.pythonr rrrrnrrrrrrrrrrrPrrr"s  !7.7ML 9N$hN$b/m/d',',TD4D4N*o*_/_/*&"=&"ROoOd/_/:44_44nO>L(L(r