
    =*f=.                         S r SrSrSSKrSSKrSSKrSSKrSSKrSSKrSSK	J
r
  SSKrSSKJrJrJr  SSKJr  SSKr\" \5      rS	S
0r\" S \R0                  R3                  5        5       5      r " S S5      rg)z2Serg G. Brester (sebres) and Fail2Ban ContributorszYCopyright (c) 2004 Cyril Jaquier, 2011-2012 Yaroslav Halchenko, 2012-2015 Serg G. BresterGPL    N)Lock   )	getLogger_merge_dicts
uni_decode)OrderedDict   am  "Command not found".  Make sure that all commands in %(realCmd)r are in the PATH of fail2ban-server process (grep -a PATH= /proc/`pidof -x fail2ban-server`/environ). You may want to start "fail2ban-server -f" separately, initiate it with "fail2ban-client reload" in another shell session and observe if additional informative error messages appear in the terminals.c              #   \   #    U  H"  u  pUR                  S 5      (       d  M  X!4v   M$     g7f)SIGN)
startswith).0namenums      7/usr/lib/python3/dist-packages/fail2ban/server/utils.py	<genexpr>r   4   s)      E)YTT__U-C {)s   ,
,c                       \ rS rSrSrSrSrSr\S-  r " S S\	5      r
\S	 5       r\S
 5       r\  SS j5       r\SS j5       r\R"                  S:X  a	  \S 5       rO\S 5       r\S 5       rSrg)Utils7   zWUtilities provide diverse static methods like executes OS shell commands, etc.
        r   g?gMbP?d   c                   J    \ rS rSrSrS rSS jrS rSS jrS r	S	 r
S
 rSrg)Utils.CacheA   z<A simple cache with a TTL and limit on size
                c                 d    U R                   " U0 UD6  [        5       U l        [        5       U l        g N)
setOptionsr	   _cacher   _Cache__lock)selfargskwargss      r   __init__Utils.Cache.__init__E   s%    ??D#F#4;4;    c                     Xl         X l        g r   )maxCountmaxTime)r   r&   r'   s      r   r   Utils.Cache.setOptionsJ   s    =<r$   c                 ,    [        U R                  5      $ r   )lenr   r   s    r   __len__Utils.Cache.__len__N   s    
dkk
r$   Nc                     U R                   R                  U5      nU(       a2  US   [        R                  " 5       :  a  US   $ U R                  U5        U$ )N   r   )r   gettimeunset)r   kdefvvs       r   r0   Utils.Cache.getQ   sB    {{q1tdiikaD[JJqM
;r$   c                 p   [         R                   " 5       nU R                  nU R                     [        U5      U R                  :  aD  U(       a=  UR                  SS9u  pVUS   U:  a  [        U5      U R                  :  a  O	U(       a  M=  X#U R                  -   4XA'   S S S 5        g ! , (       d  f       g = f)NF)lastr/   )r1   r   r   r*   r&   popitemr'   )r   r3   r5   tcacheckcvs          r   setUtils.Cache.setY   s    yy{1;;5
5zT]]"E*hr	As5zDMM1	 5 t||#$EH 	s   AB'B''
B5c                     U R                      U R                  R                  US 5        S S S 5        g ! , (       d  f       g = fr   )r   r   pop)r   r3   s     r   r2   Utils.Cache.unseti   s%    KKOOAt 	s	   3
Ac                     U R                      U R                  R                  5         S S S 5        g ! , (       d  f       g = fr   )r   r   clearr+   s    r   rD   Utils.Cache.clearm   s#    KK 	s   1
?)__lockr   r&   r'   )i  <   r   )__name__
__module____qualname____firstlineno____doc__r"   r   r,   r0   r>   r2   rD   __static_attributes__ r$   r   Cacher   A   s*    
% r$   rO   c                     [         R                   " U [         R                  5      nU(       d  U[        R                  -  nOU[        R                  ) -  n[         R                   " U [         R                  U5        U$ r   )fcntlF_GETFLos
O_NONBLOCKF_SETFL)fhandlevalueflagss      r   setFBlockModeUtils.setFBlockModer   sP    
++gu}}
-%	BMM5R]]N5++gu}}e,	,r$   c                     Sn[        U [        5      (       d  U /n [        U 5      S-
  nUR                  5        H'  u  pEX$< SU< S3-  nU R	                  U5        US-  nM)     US-   U S   -   U S'   U $ )a
  Generates new shell command as array, contains map as variables to
                arguments statement (varsStat), the command (realCmd) used this variables and
                the list of the arguments, mapped from varsDict

                Example:
                        buildShellCmd('echo "V2: $v2, V1: $v1"', {"v1": "val 1", "v2": "val 2", "vUnused": "unused var"})
                returns:
                        ['v1=$0 v2=$1 vUnused=$2 
echo "V2: $v2, V1: $v1"', 'val 1', 'val 2', 'unused var']
                 r/   z=$ 
r   )
isinstancelistr*   itemsappend)realCmdvarsDictvarsStatir3   r5   s         r   buildShellCmdUtils.buildShellCmd|   s~     (	GT	"	"Y7	'l1n!nndaAq!!8
>>!61  $+'!*	.r$   Nc           	        ^ ^^ S=pxSn	S=mn
U(       a8  U(       a  [         R                  T U5      m O[        [        R                  U5      n
[        T 5      mU U4S jn [        R                  " T [        R                  [        R                  X*[        R                  S9mTR                  5       n	U	c6  U4S jn[         R                  X[         R                  5      n	U	(       a  U	S   n	U	GcE  U(       a  U" [        R                  5        Sn[        R!                  STU4-  5        [        R"                  " TR$                  5      n[        R&                  " U[(        R*                  5        [,        R.                  " [         R0                  5        TR                  5       n	U	b  U(       a\  [        R&                  " U[(        R2                  5        [,        R.                  " [         R0                  5        U	c  TR                  5       n	U	c*  [         R5                  U5      (       d  [(        R2                  n	X;   a  [        R8                  O[        R                  nU[        R;                  5       :  a8  U(       a1  U" U[        R8                  :X  a  US-
  O[        R                  5        SnU(       d  U[        R;                  5       :  Ga\  TR<                  (       a   U	b  U	S	:  a   [         R?                  TR<                  S5        TR<                  RA                  5       nUbV  US:w  aP  U[        R;                  5       :  a8  URE                  5        H$  n[        RG                  UST[I        U5      5        M&     TRJ                  (       a   U	b  U	S	:  a   [         R?                  TRJ                  S5        TRJ                  RA                  5       nUbV  US:w  aP  U[        R;                  5       :  a8  URE                  5        H$  n[        RG                  UST[I        U5      5        M&     TR<                  (       a  TR<                  RM                  5         TRJ                  (       a  TRJ                  RM                  5         SnX;   a  [        RO                  STU	5        SnOU	c"  [        R!                  STTR$                  5        OU	S	:  d  U	S:  a>  U	S	:  a  U	* OU	S-
  n[        R!                  ST[P        RS                  USU-  5      U	5        OV[T        RS                  U	S5      n[        R!                  STU	5        U(       a"  [        RW                  SU	U[Y        5       -  5        U(       a  UXxU	4$ [[        U5      S:X  a  U$ UU	4$ ! [6         ab  nU(       a  U" [        R                  5        SnT < SU< 3n[        R!                  U5        T(       d  U(       d  SOSXxU	4s SnA$  SnAGNSnAff = f! [B         a!  n[        R!                  S
U5         SnAGNSnAff = f! [B         a!  n[        R!                  SU5         SnAGNySnAff = f)a$  Executes a command.

Parameters
----------
realCmd : str
        The command to execute.
timeout : int
        The time out in seconds for the command.
shell : bool
        If shell is True (default), the specified command (may be a string) will be 
        executed through the shell.
output : bool
        If output is True, the function returns tuple (success, stdoutdata, stderrdata, returncode).
        If False, just indication of success is returned
varsDict: dict
        variables supplied to the command (or to the shell script)

Returns
-------
bool or (bool, str, str, int)
        True if the command succeeded and with stdout, stderr, returncode if output was set to True

Raises
------
OSError
        If command fails to be executed.
RuntimeError
        If command execution times out.
Nc                 4   > [         R                  U STT5      $ )Nz%x -- exec: %s)logSyslog)levelrc   	realCmdIds    r   <lambda>"Utils.executeCmd.<locals>.<lambda>   s    E+;YPr$   )stdoutstderrshellenv
preexec_fnc                  6   > TR                  5       n U b  SU 4$ S $ )NT)poll)retcodepopens    r   _popen_wait_end)Utils.executeCmd.<locals>._popen_wait_end   s"    zz|W&2T7O<<r$   r/   z!%x -- timed out after %s seconds.z -- failed with Fr   z  ... -- failed to read stdout %sr\   z%x -- stdout: %rz  ... -- failed to read stderr %sz%x -- stderr: %rz%x -- returned successfully %iTz%x -- unable to kill PID %i   z&%x -- killed with %s (return code: %s)z	signal %iz%x -- returned %izHINT on %i: %s).r   rg   r   rS   environid
subprocessPopenPIPEsetsidrw   wait_forDEFAULT_SHORTEST_INTERVALloggingERRORrk   errorgetpgidpidkillpgsignalSIGTERMr1   sleepDEFAULT_SLEEP_INTERVALSIGKILL
pid_existsOSErrorDEBUGgetEffectiveLevelrq   rY   readIOError
splitlinesrl   r   rr   closedebugsignamer0   _RETCODE_HINTSinfolocalsr*   )rc   timeoutrs   outputtout_kill_treesuccess_codesrd   rq   rr   rx   rt   logCmdrz   pgide	std_levellsuccesssigcodemsgry   rn   s   `                   @@r   
executeCmdUtils.executeCmd   s   @ &'%#!!'84G
rzz8
,Ck)P&'EJOOJOO5yy5
 ZZ\7o= nn_u7V7VWGqzWovgmm$tf
LL4 ::eii DIIdFNN#JJu++,jjlG.YYtV^^$	ZZ,,-

gu//55~~W  '7gmmW]])&**,,fI$>Yq[GMMR]aTZyF4466 ll97Q;%,,.ll!V flyF<T<T<V/V!jj.	:a=I "ll97Q;%,,.ll!V flyF<T<T<V/V!jj.	:a=I " \\5<<%%'
\\5<<%%''	<<0)WE7	<<-y%))D{gm 1gX'C-7	<<8w{{7K'$9:GE 
		GT	*3	<<#Y8	
KK '3>:
67
**&!+C'71CCq 
 EfW]]#dV&-q16	<<
5UFG$DD 	E&  9\\4a889  9\\4a889sR   GV AW0 AX 
W-AW(W-(W-0
X:XX
Y	(YY	c                 V  ^ Sn U " 5       nU(       a  U$ U(       a4  S=p5[        U5      (       d  [        R                  " 5       U-   mU4S jnOUnW" 5       (       a   U$ [        WU=(       d    [        R                  -   [        R
                  5      n[        R                  " U5        M  )aF  Wait until condition expression `cond` is True, up to `timeout` sec

Parameters
----------
cond : callable
        The expression to check condition 
        (should return equivalent to bool True if wait successful).
timeout : float or callable
        The time out for end of wait
        (in seconds or callable that returns True if timeout occurred).
interval : float (optional)
        Polling start interval for wait cycle in seconds.

Returns
-------
variable
        The return value of the last call of `cond`, 
        logical False (or None, 0, etc) if timeout occurred.
r/   r   c                  4   > [         R                   " 5       T :  $ r   )r1   )time0s   r   ro    Utils.wait_for.<locals>.<lambda>9  s    DIIK%/r$   )callabler1   minr   r   DEFAULT_SLEEP_TIMEr   )condr   intervaliniretstmtimeout_exprr   s          @r   r   Utils.wait_for  s    , 	
#	3	J	MCGYY[7"U/\\nn	 
* 
SH< < <=u?W?W	X3::c? 	r$   posixc                     SSK nU S:  a  g [        R                  " U S5        g! [         a#  nUR                   UR                  :H  s SnA$ SnAff = f)z6Check whether pid exists in the current process table.r   NFT)errnorS   killr   EPERM)r   r   r   s      r   r   Utils.pid_existsE  sM     	AgGGCO   "77ekk!!"s   % 
AAAAc                     SS K nUR                  R                  nSnUR                  USU 5      nUS:w  a  UR	                  U5        gg)Nr   i   TF)ctypeswindllkernel32OpenProcessCloseHandle)r   r   r   SYNCHRONIZEprocesss        r   r   r   R  sH    mm$$8;!!+q#67l!r$   c                     [         R                  R                  [         R                  R                  U 5      5      S   n[        R
                  R                  X5      R                  5       nU$ )Nr   )rS   pathsplitextbasename	importlib	machinerySourceFileLoaderload_module)pythonModulepythonModuleNamemods      r   load_python_moduleUtils.load_python_module_  sY    WW%%77L!##$&,,	##.;= 	*r$   rN   )rG   TFT)r   Nr   )rH   rI   rJ   rK   rL   r   r   DEFAULT_SHORT_INTERVALr   objectrO   staticmethodrY   rg   r   r   rS   r   r   r   rM   rN   r$   r   r   r   7   s     3c9.V .b    , NR#DD DDL % %R GGw
 
 
 
  r$   r   )
__author____copyright____license__rQ   r   rS   r   r   sys	threadingr   r1   helpersr   r   r   collectionsr	   importlib.machineryr   rH   rk   r   dict__dict__ra   r   r   rN   r$   r   <module>r      s   ( B
k   	   
   9 9 #  
8	  D  E//'')E En nr$   