o b(k@s^ddlZddlZddlZddlZz ddlZddlZWn ey'dZdZYnweZeZz ddlm Z m Z Wn eyCdZ dZ Ynwe Z e Z ddl mZddlmZmZmZmZmZmZmZmZddlmZddlmZeeddd dd d d Gd ddeZddZdOddZddZddZ ddZ!ddZ"   dPddZ#d d!Z$d"d#Z%dQd'd(Z&d)d*Z'ggfd+d,Z(Gd-d.d.Z)d/d0Z*Gd1d2d2Z+Gd3d4d4Z,Gd5d6d6Z-Gd7d8d8Z.zdd9lm/Z0Wn eydZ1Ynwe0Z1e1durd:d;Z/ndd?Z2d@dAZ3dBdCZ4dDdEZ5dFdGZ6dHdIZ7dJdKZ8dLdMZ9gdNZ:dS)SN) getgroups setgroups) OrderedDict)CallableClassVarMappingMutableMappingSequenceTupleUnioncast)Version)deprecatedModuleAttributeTwistedz$Use collections.OrderedDict instead.ztwisted.python.utilrcseZdZdZ d4fdd ZddZdd Zd d Zd d ZddZ e Z ddZ ddZ ddZ ddZd5ddZddZddZdefdd Zd!d"ZeZd#d$Zd%d&ZeZefd'd(Zd)d*Zd+d,Zd-d.Zd/d0Zd1edefd2d3Z Z!S)6InsensitiveDicta Dictionary, that has case-insensitive keys. Normally keys are retained in their original form when queried with .keys() or .items(). If initialized with preserveCase=0, keys are both looked up in lowercase and returned in lowercase by .keys() and .items(). Ncs,ti|_||_|r||dSdS)zD Create an empty dictionary, or update from 'dict'. N)super__init__datapreserveupdate)selfdictr __class__5/usr/lib/python3/dist-packages/twisted/python/util.pyrEs zInsensitiveDict.__init__cCs||}|j|=dSN_lowerOrReturnrrkeykrrr __delitem__Os  zInsensitiveDict.__delitem__cCs t|ts t|tr|S|Sr) isinstancebytesstrlowerrr#rrrr!SszInsensitiveDict._lowerOrReturncCs||}|j|dS)zI Retrieve the value associated with 'key' (in any case). rr r"rrr __getitem__Ys zInsensitiveDict.__getitem__cCs||}||f|j|<dS)z| Associate 'value' with 'key'. If 'key' already exists, but in different case, it will be replaced. Nr )rr#valuer$rrr __setitem__`s zInsensitiveDict.__setitem__cCs||}||jvS)z= Case insensitive test whether 'key' exists. r r"rrrhas_keyhs  zInsensitiveDict.has_keycCs&|jst|ts t|tr|S|Sr)rr&r'r(r)r*rrr _doPreserveqszInsensitiveDict._doPreservecC t|S)z6 List of keys in their original case. )listiterkeysrrrrkeysw zInsensitiveDict.keyscCr0)z! List of values. )r1 itervaluesr3rrrvalues}r5zInsensitiveDict.valuescCr0)z, List of (key,value) pairs. )r1 iteritemsr3rrritemsr5zInsensitiveDict.itemscCs"z||WSty|YSw)zn Retrieve value associated with 'key' or return default value if 'key' doesn't exist. )KeyErrorrr#defaultrrrgets   zInsensitiveDict.getcCs||s |||<||S)z| If 'key' doesn't exist, associate it with the 'default' value. Return value associated with 'key'. )r.r;rrr setdefaults zInsensitiveDict.setdefaultcCs|D]\}}|||<qdS)z5 Copy (key,value) pairs from 'dict'. Nr9)rrr$vrrrrs zInsensitiveDict.updatereturncCs ddd|D}d|S)z: String representation of the dictionary. z, cSsg|] \}}|d|qS)z: r).0r$r@rrr sz,InsensitiveDict.__repr__..zInsensitiveDict({%s}))joinr9)rr9rrr__repr__szInsensitiveDict.__repr__ccs&|jD] }||dVqdSNrrr7r/rr@rrrr2szInsensitiveDict.iterkeysccs |jD]}|dVqdSNr)rr7rHrrrr6s zInsensitiveDict.itervaluesccs*|jD] \}}|||fVqdSrrG)rr$r@rrrr8szInsensitiveDict.iteritemscCs<z |j||dWSty||jur|YSw)zB @see: L{dict.pop} @since: Twisted 21.2.0 r)rpopr!r: _notFoundr;rrrrJs  zInsensitiveDict.popcCs|d}||d=|SrFr?)rirrrpopitems  zInsensitiveDict.popitemcCs|D]}||=qdSr)r4)rr$rrrclears zInsensitiveDict.clearcCs t||jSr)rrr3rrrcopys zInsensitiveDict.copycCs t|jSr)lenrr3rrr__len__s zInsensitiveDict.__len__othercCsJt|tr#|D]\}}||vs|||krdSq t|t|kStS)NF)r&rr9rPNotImplemented)rrRr$r@rrr__eq__s zInsensitiveDict.__eq__rIr)"__name__ __module__ __qualname____doc__rr%r!r+r-r. __contains__r/r4r7r9r=r>rr(rEr2__iter__r6r8objectrKrJrMrNrOrQboolrT __classcell__rrrrr7s:      rcCs4t}g}|D]}||vr||||q|S)z Make the elements of a list unique by inserting them into a dictionary. This must not change the order of the input lst. )setappendadd)lstseenresultr$rrruniquifys  rdcCsBt||krtdt||f|g|}t||dt|<|S)aT Pads a sequence out to n elements, filling in with a default value if it is not long enough. If the input sequence is longer than n, raises ValueError. Details, details: This returns a new list; it does not extend the original sequence. The new list contains the values of the original sequence, not copies. z%d elements is more than %d.N)rP ValueErrorr1)nseqr<blankrrrpadTos  ric Csptjdtddddl}tjtjtjtj|j d}tj d}tj d}t tjj |||g}|S)NzCtwisted.python.util.getPluginDirs is deprecated since Twisted 12.2. stacklevelrpluginsz~/TwistedPluginsz ~/.twisted) warningswarnDeprecationWarningtwistedospathrDdirnameabspath__file__ expanduserfilterisdir)rq systemPlugins userPlugins confPlugins allPluginsrrr getPluginDirss  r~cCs"tjdtddtjtdS)NzBtwisted.python.util.addPluginDir is deprecated since Twisted 12.2.rjrk)rnrorpsysrsextendr~rrrr addPluginDirs rcCstjtjtj||S)z Return the path to a sibling of a file in the filesystem. This is useful in conjunction with the special C{__file__} attribute that Python provides for modules, so modules can load associated resource files. )rrrsrDrtru)rssiblingrrrsibpathsrc CsPddl}z||WSty}z |jtjkrtd}~wty'tw)z: Helper to turn IOErrors into KeyboardInterrupts. rN)getpassOSErrorerrnoEINTRKeyboardInterruptEOFError)promptrerrr_getpass)s   r Password: Confirm password: Passwords don't match.c Cs2ttjdo tj}d}z}|sQ|r/ztjtjf}tddt_t_Wn-ty.tdwtj}|ddkr@|dd}|W|rPtj |\t_t_SS t |}|si|W|rhtj |\t_t_SSt |} || kr|W|rtj |\t_t_SStj |dqR|rtj |\t_t_w)a+ Obtain a password by prompting or from stdin. If stdin is a terminal, prompt for a new password, and confirm (if C{confirm} is true) by asking again to make sure the user typed the same thing, as keystrokes will not be echoed. If stdin is not a terminal, and C{forceTTY} is not true, read in a line and use it as the password, less the trailing newline, if any. If C{forceTTY} is true, attempt to open a tty and prompt for the password using it. Raise a RuntimeError if this is not possible. @returns: C{str} isattyNz/dev/ttyzr+zCannot obtain a TTY ) hasattrrstdinrstdoutopen BaseException RuntimeErrorreadlinecloserstderrwrite) rconfirmforceTTY confirmPromptmismatchMessageisaTTYoldpasswordtry1try2rrr getPassword9sN         rcGs tjdtt|ddS)N r)rrrrDmapr()arrrprintlnns rcsdfdd|DS)Ncsg|] }tt|AqSr)chrord)rBcbrrrCxszstr_xor..)rD)srrrrstr_xorwsr=->csJt|ddgffdd }ddd|f|_|S)zS Creates a function that will return a string representing a progress bar. rrcstt|dks Jdt|}|d}d||d}|r,||d<|S||dkr4dS||d<|S)Nrz#Don't mess with the last parameter.rj[]rr)rPint)positionforcelastdonetoDorcaValue currentChardoneChar undoneCharwidthrrstatBars   zmakeStatBar..statBaraRstatBar(position, force = 0) -> '[%s%s%s]'-style progress bar returned string is %d characters long, and the range goes from 0..%d. The 'position' argument is where the '%s' will be drawn. If force is false, '' will be returned instead if the resulting progress bar is identical to the previously returned progress bar. )floatrX)r maxPositionrrrrrrr makeStatBar{s  rcCsddlm}d|jvr6|jd}t|dr||j}n|t|}td|jj d|dt |d Std|jj |jj |j fd S) zV A trace function for sys.settrace that prints every function or method call. r)reflectrrzmethod z of z at zfunction %s in %s, line %sN) twisted.pythonrf_localsrqualrtypeprintf_codeco_nameid co_filenamef_lineno)framerignoredrser$rrrspewers    &rc Cstj|}|tj}tjj}tjj}tjj}t|rV||tj}d}|D]} ||| s5d}nq'|rI|D]} ||| sHd}nq:|rM|S| dt|sdS)z Walk upwards from start, looking for a directory containing all files and directories given as arguments:: >>> searchupwards('.', ['foo.txt'], ['bar', 'bam']) If not found, return None rrrN) rrrsrusplitsepexistsrDryrPrJ) startfilesdirsparentsrrDry candidate allpresentfdrrr searchupwardss0   rc@sBeZdZdZdddZddZddZd d Zd d Zd dZ dS)LineLogz A limited-size line-based log, useful for logging line-based protocols such as SMTP. When the log fills up, old entries drop off the end. cCs"|dkrd}dg||_||_dS)z Create a new log, with size lines of storage (default 10). A log size of 0 (or less) means an infinite log. rN)logsize)rrrrrrs  zLineLog.__init__cCs<|jr|jdd|jdd<||jd<dS|j|dS)Nrr)rrr_)rlinerrrr_szLineLog.appendcCst|Sr)r'r3rrrr(sz LineLog.strcCsdtd|jS)N )rDrxrr3rrr __bytes__szLineLog.__bytes__cCstd|j|Sr)rxr)ritemrrrr+szLineLog.__getitem__cCsdg|j|_dS)z Empty the log. N)rrr3rrrrNsz LineLog.clearN)r) rUrVrWrXrr_r(rr+rNrrrrrs   rcOs*z ||i|WdS|yYdSw)zF Determine whether the given call raises the given exception. rrr) exceptionrargskwargsrrrraisess  rc@s"eZdZdZdddZddZdS) IntervalDifferentiala Given a list of intervals, generate the amount of time to sleep between "instants". For example, given 7, 11 and 13, the three (infinite) sequences:: 7 14 21 28 35 ... 11 22 33 44 ... 13 26 39 52 ... will be generated, merged, and used to produce:: (7, 0) (4, 1) (2, 2) (1, 0) (7, 0) (1, 1) (4, 2) (2, 0) (5, 1) (2, 0) New intervals may be added or removed as iteration proceeds using the proper methods. <cCs|dd|_||_dS)a @type intervals: C{list} of C{int}, C{long}, or C{float} param @param intervals: The intervals between instants. @type default: C{int}, C{long}, or C{float} @param default: The duration to generate if the intervals list becomes empty. N) intervalsr<)rrr<rrrrs zIntervalDifferential.__init__cCst|j|jSr)_IntervalDifferentialIteratorrr<r3rrrrZ%szIntervalDifferential.__iter__N)r)rUrVrWrXrrZrrrrrs  rc@s0eZdZddZddZeZddZddZd S) rcCs.ddt|tt|D|_||_d|_dS)NcSsg|] \}}|||gqSrr)rBrrfrrrrC,sz:_IntervalDifferentialIterator.__init__..r)ziprangerPrr<r)rrLrrrrr*s z&_IntervalDifferentialIterator.__init__cCsp|js|jdfS|jdd|jdd}}|jdd|jdd7<|j||j}||_||fS)Nrrjr)rr<sortr)rrindexrcrrr__next__0s    z&_IntervalDifferentialIterator.__next__cCsb|jr&|jdd|jdd}|j|||t|jg|jdS|j||dgdS)Nrr)rr_rPr)rrLdelayrrr addInterval=s z)_IntervalDifferentialIterator.addIntervalcCsrtt|jD]-}|j|d|kr4|j|d}|j|=|jD]}|d|kr0|dd8<q dSqtd)Nrrjz.Specified interval not in IntervalDifferential)rrPrre)rintervalrLrrrrremoveIntervalEs  z,_IntervalDifferentialIterator.removeIntervalN)rUrVrWrrnextrrrrrrr)s   rc@sPeZdZUdZdZeeeeeeefeee ffe d<defddZ e Z dS) FancyStrMixinaO Mixin providing a flexible implementation of C{__str__}. C{__str__} output will begin with the name of the class, or the contents of the attribute C{fancybasename} if it is set. The body of C{__str__} can be controlled by overriding C{showAttributes} in a subclass. Set C{showAttributes} to a sequence of strings naming attributes, or sequences of C{(attributeName, callable)}, or sequences of C{(attributeName, displayName, formatCharacter)}. In the second case, the callable is passed the value of the attribute and its return value used in the output of C{__str__}. In the final case, the attribute is looked up using C{attributeName}, but the output uses C{displayName} instead, and renders the value of the attribute using C{formatCharacter}, e.g. C{"%.3f"} might be used for a float. rshowAttributesrAc Csdt|d|jjg}|jD]Z}t|tr#|d|dt||q t|dkrItt tt f|}|d|dd|dt||dq tt tttf|}|d|d|dt||dfq |d d |S) N< fancybasenamerrrjrrz %s=rr) getattrrrUrr&r(r_rPr r rrD)rrattrrrr__str__hs   .*  zFancyStrMixin.__str__N) rUrVrWrXrr r r(r r__annotations__rrErrrrrQs rc@sJeZdZUdZdZeeeed<de de fddZ de de fdd Z d S) FancyEqMixinz Mixin that implements C{__eq__} and C{__ne__}. Comparison is done using the list of attributes defined in C{compareAttributes}. rcompareAttributesrRrAcs8jsuStjrtfddjDStS)Nc3s$|] }t|t|kVqdSr)r)rBnamerRrrr s  z&FancyEqMixin.__eq__..)rr&rallrS)rrRrr rrTs zFancyEqMixin.__eq__cCs||}|tur |S| Sr)rTrS)rrRrcrrr__ne__s zFancyEqMixin.__ne__N) rUrVrWrXrrr r(rr[r\rTr rrrrr|s  r) initgroupscCsdS)zk Do nothing. Underlying platform support require to manipulate groups is missing. Nruid primaryGidrrrrsrcCstt|j|S)a Initializes the group access list. This uses the stdlib support which calls initgroups(3) under the hood. If the given user is a member of more than C{NGROUPS}, arbitrary groups will be silently discarded to bring the number below that limit. @type uid: C{int} @param uid: The UID for which to look up group information. @type primaryGid: C{int} @param primaryGid: The GID to include when setting the groups. ) _initgroupspwdgetpwuidpw_namerrrrrsFc Cs|r tj}tj}tj}n tj}tj}tj}|dur|||durR||krG|r*dp+d}d|d|}|d|}td ||dSt ||||dSdS)a Attempts to switch the uid/euid and gid/egid for the current process. If C{uid} is the same value as L{os.getuid} (or L{os.geteuid}), this function will issue a L{UserWarning} and not raise an exception. @type uid: C{int} or L{None} @param uid: the UID (or EUID) to switch the current process to. This parameter will be ignored if the value is L{None}. @type gid: C{int} or L{None} @param gid: the GID (or EGID) to switch the current process to. This parameter will be ignored if the value is L{None}. @type euid: C{bool} @param euid: if True, set only effective user-id rather than real user-id. (This option has no effect unless the process is running as root, in which case it means not to shed all privileges, retaining the option to regain privileges in cases such as spawning processes. Use with caution.) Neuidrz tried to drop privileges and setrz is already z){} but {}; should we be root? Continuing.) rrseteuidsetegidgeteuidsetuidsetgidgetuidrnroformatr) rgidrrrruidText actionText problemTextrrr switchUIDs,    r"c OsJ z||i|WSty$}z|jdtjkrWYd}~qd}~ww)af Call C{f} with the given arguments, handling C{EINTR} by retrying. @param f: A function to call. @param a: Positional arguments to pass to C{f}. @param kw: Keyword arguments to pass to C{f}. @return: Whatever C{f} returns. @raise Exception: Whatever C{f} raises, except for C{OSError} with C{errno} set to C{EINTR}. TrN)rrrr)rrkwrrrruntilConcludess r$c Csz|j|_Wn tyYnwz|j|_Wn ttfy!Ynwz |j|jWn ttfy6Ynwz|j|_W|StyHY|Sw)z Overwrite C{g}'s name and docstring with values from C{f}. Update C{g}'s instance dictionary with C{f}'s. @return: A function that has C{g}'s behavior and metadata merged from C{f}. )rU TypeErrorrXAttributeError__dict__rrV)rgrrrmergeFunctionMetadatas,     r)cCsg}d}d}|D]9}||kr||7}n(|r6t|dkr"||7}n|dd}|d}||||}n|||}|}q|rM|d|d<n|S||d|S)ay Convert a string like a variable name into a slightly more human-friendly string with spaces and capitalized letters. @type mname: C{str} @param mname: The name to convert to a label. This must be a string which could be used as a Python identifier. Strings which do not take this form will result in unpredictable behavior. @rtype: C{str} rFrNrrr)isupperrPr_ capitalizerD)mname labelListword lastWasUpperletterlastWord firstLetterrrr nameToLabel!s*            r3cC6zt|WStytdurt|dYSw)a Convert a user identifier, as a string, into an integer UID. @type uidString: C{str} @param uidString: A string giving the base-ten representation of a UID or the name of a user which can be converted to a UID via L{pwd.getpwnam}. @rtype: C{int} @return: The integer UID corresponding to the given string. @raise ValueError: If the user name is supplied and L{pwd} is not available. Nrj)rrergetpwnam) uidStringrrr uidFromStringO  r7cCr4)a Convert a group identifier, as a string, into an integer GID. @type gidString: C{str} @param gidString: A string giving the base-ten representation of a GID or the name of a group which can be converted to a GID via L{grp.getgrnam}. @rtype: C{int} @return: The integer GID corresponding to the given string. @raise ValueError: If the group name is supplied and L{grp} is not available. Nrj)rregrpgetgrnam) gidStringrrr gidFromStringer8r<c OsNtt}}||kr||kr||i|S|dkr)||ks$||kr)td||kr2t||dkrC||ks>||krCt|z5||i|W|dkr\||ksW||kr\td||kret||dkrw||ksq||krxt|SSS|dkr||ks||krtd||krt||dkr||ks||krt|www)a, Run the given function wrapped with seteuid/setegid calls. This will try to minimize the number of seteuid/setegid calls, comparing current and wanted permissions @param euid: effective UID used to call the function. @type euid: C{int} @type egid: effective GID used to call the function. @param egid: C{int} @param function: the function run with the specific permission. @type function: any callable @param args: arguments passed to C{function} @param kwargs: keyword arguments passed to C{function} r)rrrgetegidrr)regidfunctionrrrrrrrrunAsEffectiveUser{s2         r@cOsXt|D] \}}tj|i|q||i|WdS1s%wYdS)a  Run C{f(*args, **kwargs)}, but with some warnings suppressed. Unlike L{twisted.internet.utils.runWithWarningsSuppressed}, it has no special support for L{twisted.internet.defer.Deferred}. @param suppressedWarnings: A list of arguments to pass to L{warnings.filterwarnings}. Must be a sequence of 2-tuples (args, kwargs). @param f: A callable. @param args: Arguments for C{f}. @param kwargs: Keyword arguments for C{f} @return: The result of C{f(*args, **kwargs)}. N)rncatch_warningsfilterwarnings)suppressedWarningsrrrrr#rrrrunWithWarningsSuppresseds   $rD)rdrir~rrrrrrrrrrrrrrr"r)r3r7r<r@r$rDr)rrrrr)rrr)F);rrrrrnr9_grpr_pwd ImportErrorr _getgroupsr _setgroups collectionsrtypingrrrrr r r r incrementalr twisted.python.deprecaterrrdrir~rrrrrrrrrrrrrrrr __initgroupsrr"r$r)r3r7r<r@rD__all__rrrrs    (  )    5 $) #(+    /.(