
    Bd.                     .   d Z dZdZddlZddlZddlZddlZddlZddlZddl	m
Z
 ddlZddlmZmZmZ ddlmZ ej        d	k    rddlZnddlZ ee          Zd
diZ ed ej                                        D                       Z G d d          ZdS )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   r      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              #   N   K   | ] \  }}|                     d           ||fV  !dS )SIGN)
startswith).0namenums      7/usr/lib/python3/dist-packages/fail2ban/server/utils.py	<genexpr>r   7   sW       E ET3T__U-C-CET{ E E E E E E    c                       e Zd ZdZdZdZdZedz  Z G d de          Z	e
d             Ze
d	             Ze
	 	 dd            Ze
dd            Zej        dk    re
d             Zne
d             Ze
d             ZdS )UtilszPUtilities provide diverse static methods like executes OS shell commands, etc.
	r   g?gMbP?d   c                   @    e Zd ZdZd ZddZd ZddZd	 Zd
 Z	d Z
dS )Utils.Cachez.A simple cache with a TTL and limit on size
		c                 l     | j         |i | t                      | _        t                      | _        d S N)
setOptionsr	   _cacher   _Cache__lock)selfargskwargss      r   __init__zUtils.Cache.__init__H   s3    4?D#F###4;4;;;r     <   c                 "    || _         || _        d S r   )maxCountmaxTime)r    r'   r(   s      r   r   zUtils.Cache.setOptionsM   s    4=4<<<r   c                 *    t          | j                  S r   )lenr   r    s    r   __len__zUtils.Cache.__len__Q   s    
dk

r   Nc                     | j                             |          }|r:|d         t          j                    k    r|d         S |                     |           |S )N   r   )r   gettimeunset)r    kdefvvs       r   r/   zUtils.Cache.getT   sO    {q1 tdikkaD[JJqMMM
;r   c                 L   t          j                     }| j        }| j        5  t          |          | j        k    rB|r@|                    d          \  }}|d         |k    rt          |          | j        k     rn|@||| j        z   f||<   d d d            d S # 1 swxY w Y   d S )NF)lastr.   )r0   r   r   r*   r'   popitemr(   )r    r2   r4   tcacheckcvs          r   setzUtils.Cache.set\   s    y{{1;5 
% 
%
5zzT]"" E**hr2	As5zzDM11	   1t|#$E!H
% 
% 
% 
% 
% 
% 
% 
% 
% 
% 
% 
% 
% 
% 
% 
% 
% 
%s   A*BB Bc                 |    | j         5  | j                            |d            d d d            d S # 1 swxY w Y   d S r   )r   r   pop)r    r2   s     r   r1   zUtils.Cache.unsetl   s      KOOAt                 s   155c                 x    | j         5  | j                                         d d d            d S # 1 swxY w Y   d S r   )r   r   clearr+   s    r   r@   zUtils.Cache.clearp   s      K                 s   /33)r$   r%   r   )__name__
__module____qualname____doc__r#   r   r,   r/   r<   r1   r@    r   r   Cacher   D   s           
        % % %       r   rF   c                     t          j         | t           j                  }|s|t          j        z  }n|t          j         z  }t          j         | t           j        |           |S r   )fcntlF_GETFLos
O_NONBLOCKF_SETFL)fhandlevalueflagss      r   setFBlockModezUtils.setFBlockModeu   sT    
+gu}
-
-%	 BM55R]N5+gu}e,,,	,r   c                     d}t          | t                    s| g} t          |           dz
  }|                                D ]*\  }}||d|dz  }|                     |           |dz  }+|dz   | d         z   | d<   | S )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ir2   r4   s         r   buildShellCmdzUtils.buildShellCmd   s     (	GT	"	" Y7	'll1n!nn 
 
daAAAqqq!!8
>>!611$+'!*	.r   r%   TFr   Nc           	      *    dx}}d}	dx}
|r8|rt                                |           nt          t          j        |          }
t                      fd}	 t          j         t          j        t          j        ||
t          j	                  
                                }	|	5fd}t                               ||t           j                  }	|	r|	d         }	|	!|r |t          j                   d}t                              d|fz             t          j        j                  }t          j        |t(          j                   t-          j        t           j                   
                                }	|	|rSt          j        |t(          j                   t-          j        t           j                   |	
                                }	|	&t                               |          st(          j        }	nb# t6          $ rU}|r |t          j                   d} d|}t                              |           s|sdnd|||	fcY d}~S Y d}~nd}~ww xY w|	|v rt          j        nt          j        }|t                                          k    r.|r, ||t          j        k    r|dz
  nt          j                   d}|s|t                                          k    rĉj        r	 |	|	d	k     r t                               j        d           j                                         }n2# tB          $ r%}t                              d
|           Y d}~nd}~ww xY w|d|dk    r^|t                                          k    rA|"                                D ],}t          #                    |dtI          |                     -j%        r	 |	|	d	k     r t                               j%        d           j%                                         }n2# tB          $ r%}t                              d|           Y d}~nd}~ww xY w|d|dk    r^|t                                          k    rA|"                                D ],}t          #                    |dtI          |                     -j        rj        &                                 j%        rj%        &                                 d}|	|v rt          '                    d|	           d}n|	"t                              dj                   n|	d	k     s|	dk    rH|	d	k     r|	 n|	dz
  }t                              dtP          )                    |d|z            |	           ndtT          )                    |	d          }t                              d|	           |r+t          +                    d|	|tY                      z             |r||||	fS t[          |          dk    r|n||	fS )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                 >    t                               | d          S )Nz%x -- exec: %s)logSyslog)levelrY   	realCmdIds    r   <lambda>z"Utils.executeCmd.<locals>.<lambda>   s    E+;YPP r   )stdoutstderrshellenv
preexec_fnc                  <                                     } | d| fnd S )NT)poll)retcodepopens    r   _popen_wait_endz)Utils.executeCmd.<locals>._popen_wait_end   s#    zz||W&2T7OO<r   r.   z!%x -- timed out after %s seconds.z -- failed with Fr   z  ... -- failed to read stdout %srR   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   r]   r   rJ   environid
subprocessPopenPIPEsetsidrl   wait_forDEFAULT_SHORTEST_INTERVALloggingERRORra   errorgetpgidpidkillpgsignalSIGTERMr0   sleepDEFAULT_SLEEP_INTERVALSIGKILL
pid_existsOSErrorDEBUGgetEffectiveLevelrf   rP   readIOError
splitlinesrb   r   rg   closedebugsignamer/   _RETCODE_HINTSinfolocalsr*   )rY   timeoutrh   outputtout_kill_treesuccess_codesrZ   rf   rg   rm   ri   logCmdro   pgide	std_levellsuccesssigcodemsgrn   rd   s   `                   @@r   
executeCmdzUtils.executeCmd   sp   @ &6'%# - -!!'844GG
rz8
,
,Ckk)PPPPP&'EJOJO5cy  5
 ZZ\\7o= = = = = nn_gu7VWWG qzWo3vvgm$$$tf
LL4   :ei  DIdFN###Ju+,,,jjllG.YtV^$$$	Z,---

gu//55~W	 E E E2ffW]###dV&-ggqq16	<<
 ED55UFFG$DDDDDDDE E E E E	E  '-77gmmW])&**,,,,affI$>$>Yq[[GMRRR]aTZ JyF446666 l 	J97Q;;%,...l!!VV 9 9 9\\4a888888889fllyF<T<T<V<V/V/V!! J Jjj.	:a==IIIIl 	J97Q;;%,...l!!VV 9 9 9\\4a888888889fllyF<T<T<V<V/V/V!! J Jjj.	:a==IIII
\'5<%%'''
\'5<%%''''	<<0)WEEE77	<<-y%)DDDD{{gmm 1gXX'C-7	<<8w{{7K'$9::GE E E E 
		GT	*	*3	<<#Y888	 ;
KK '3>::: +
667
**&&!++'71CCsR   F'H 
I%AI I% I%7AL9 9
M(M##M(AP 
Q
%QQ
c                 "   d}	  |             }|r|S |r1dx}}t          |          st          j                    |z   fd}n|} |            rn>t          ||pt          j        z   t          j                  }t          j        |           |S )a5  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.   Tr   c                  2    t          j                      k    S r   )r0   )time0s   r   re   z Utils.wait_for.<locals>.<lambda><  s    DIKK%/ r   )callabler0   minr   r   DEFAULT_SLEEP_TIMEr   )condr   intervaliniretstmtimeout_exprr   s          @r   rw   zUtils.wait_for  s    , 	
#	3	 J	 MC#G Y[[7"U////\\\lnn 
		SH< <=u?W	X	X3:c??? 
*r   posixc                     ddl }| dk     rdS 	 t          j        | d           dS # t          $ r}|j         |j        k    cY d}~S d}~ww xY w)z6Check whether pid exists in the current process table.r   NFT)errnorJ   killr   EPERM)r}   r   r   s      r   r   zUtils.pid_existsH  su     <<<	Agg5GCOOO 4  " " "7ek!!!!!!!"s   % 
A	AA	A	c                     dd l }|j        j        }d}|                    |d|           }|dk    r|                    |           dS dS )Nr   i   TF)ctypeswindllkernel32OpenProcessCloseHandle)r}   r   r   SYNCHRONIZEprocesss        r   r   zUtils.pid_existsU  sX    ===m$8;!!+q#667ll!!!45r   c                 :   t           j                            t           j                            |                     d         }t          j        dk    r3t          j                            ||           	                                }nt          j        ||           }|S )Nr   r
   )rJ   pathsplitextbasenamesysversion_info	importlib	machinerySourceFileLoaderload_moduleimpload_source)pythonModulepythonModuleNamemods      r   load_python_modulezUtils.load_python_moduleb  s    W%%7L!!# ##$&			-	-l
$ 
$$/KMM 3 
l
$ 
$3	*r   )r%   TFTr^   Nr   )rA   rB   rC   rD   r   r   DEFAULT_SHORT_INTERVALrx   objectrF   staticmethodrP   r]   r   rw   rJ   r   r   r   rE   r   r   r   r   :   sQ         3c9. . . . .V . . .b   ,   ,, NR#DD DD DD ,DDL % % % ,%R Gw
 
 <
 
 
 
 <
 	 	 ,	 	 	r   r   )
__author____copyright____license__rH   ry   rJ   r   rs   r   	threadingr   r0   helpersr   r   r   collectionsr	   r   importlib.machineryr   r   rA   ra   r   dict__dict__rW   r   r   rE   r   r   <module>r      sd  ( B
k   				      



        9 9 9 9 9 9 9 9 9 9 # # # # # #v 
8		  D $ E E/''))E E E E Er r r r r r r r r rr   