
    GkcL                     <   d Z dZdZddlZddlZddlmZ ddlmZm	Z	m
Z
mZmZmZ ddlmZ dd	lmZ d
dlmZ  ee      ZdZ ej.                  dej0                        Z ej4                  dd      ZddZd fdZ G d de      Z G d de      Z  G d de      Z!y)z'Cyril Jaquier and Fail2Ban Contributorsz Copyright (c) 2004 Cyril JaquierGPL    N)Lock   )reDateTemplateDatePatternRegex
DateTai64n	DateEpochRE_EPOCH_PATTERN)validateTimeZone)Utils   )	getLogger   z(?<!\\)\{DATE\}i  i  )maxCountmaxTimec                 |   || }d| vr| j                         }t        j                  |      }|svd|v rMt        j                  |       rt        | d|v       }n(|dv rt        |dk7        }n|dv rt        |dk7  d	      }|#|d
v rt        |dk7  rdnd      }nt        |       }t        j                  ||       |S )N%EPOCHLEPOCH)patternlongFrm)r   z{^LN-BEG}EPOCHz^EPOCH)lineBeginOnly)r   z{^LN-BEG}LEPOCHz^LEPOCHT)r   r   )TAI64Nz{^LN-BEG}TAI64Nz^TAI64Nr   startF)	wordBegin)	upperDD_patternCachegetr   searchr
   r	   r   set)r   keytemplates      >/usr/lib/python3/dist-packages/fail2ban/server/datedetector.py_getPatternTemplater%   ,   s    K#	3$^g&(c/BH44w8H77x$GH	55xWULH(HS(#    c                     d| z   S N	{^LN-BEG} )ss    r$   <lambda>r,   D   s
    +/ r&   c                      || j                         }t        j                  |      }|sd |t        | d| j                              }t        | d      rt        j                  |      }|s$t        | d      st        |      }|S t        |      }|S )Nr   )namer   r   getattrregexhasattrr%   )r#   wrapr.   	template2r0   s        r$   _getAnchoredTemplater4   D   s    X]]  &
wxHNN;
<%Xy!""5)9	
(I
&#D)I 	 $E*Ir&   c                   J    e Zd ZdZd Zed        Zd Zg dZed        Z	d Z
y)	DateDetectorCachez7Implements the caching of the default templates list.
	c                 @    t               | _        t               | _        y N)r   _DateDetectorCache__locklist_DateDetectorCache__templatesselfs    r$   __init__zDateDetectorCache.__init__\   s    $+V$r&   c                     | j                   r| j                   S | j                  5  | j                   r| j                   cddd       S | j                          | j                   cddd       S # 1 sw Y   yxY w)6List of template instances managed by the detector.
		N)r;   r9   _addDefaultTemplater<   s    r$   	templateszDateDetectorCache.templates`   sh     



{{ 
  


	  s   A,A,,A5c                 2   |j                   }|j                  d      s\|j                  d      sKt        |d      r?t        |      }|j                   |k7  r%d|_        | j
                  d   j                  |       | j
                  d   j                  |       y)z&Cache Fail2Ban's default template.

		r)   ^r0   g      Y@r   r   N)r.   
startswithr1   r4   weight_DateDetectorCache__tmpcacheappend)r=   r#   r.   r3   s       r$   _cacheTemplatez DateDetectorCache._cacheTemplatel   s|     
$		%dooc.BwxY`Ga#H-9nn IOOAi(//!H%r&   )zF%ExY(?P<_sep>[-/.])%m(?P=_sep)%d(?:T|  ?)%H:%M:%S(?:[.,]%f)?(?:\s*%z)?z)(?:%a )?%b %d %k:%M:%S(?:\.%f)?(?: %ExY)?z$(?:%a )?%b %d %ExY %k:%M:%S(?:\.%f)?z1%d(?P<_sep>[-/])%m(?P=_sep)(?:%ExY|%Exy) %k:%M:%Sz=%d(?P<_sep>[-/])%b(?P=_sep)%ExY[ :]?%H:%M:%S(?:\.%f)?(?: %z)?z%m/%d/%ExY:%H:%M:%Sz%m-%d-%ExY %k:%M:%S(?:\.%f)?r   z{^LN-BEG}%H:%M:%Sz^<%m/%d/%Exy@%H:%M:%S>z%Exy%Exm%Exd  ?%H:%M:%Sz%b %d, %ExY %I:%M:%S %pz^%b-%d-%Exy %k:%M:%Sz6%ExY%Exm%Exd(?:T|  ?)%ExH%ExM%ExS(?:[.,]%f)?(?:\s*%z)?z1(?:%Z )?(?:%a )?%b %d %k:%M:%S(?:\.%f)?(?: %ExY)?z1(?:%z )?(?:%a )?%b %d %k:%M:%S(?:\.%f)?(?: %ExY)?r   c                     t        t        j                  d   t              r?t	        t        j                        D ]#  \  }}t        |      }|t        j                  |<   % t        j                  S )Nr   )
isinstancer6   DEFAULT_TEMPLATESstr	enumerater%   )r=   idts      r$   defaultTemplatesz"DateDetectorCache.defaultTemplates   s`    !33A6<+==> 0uq"	R	 B-/''*0 
	,	,,r&   c                     g g f| _         | j                  D ]  }| j                  |        | j                   d   | j                   d   z   | _        | ` y)z<Add resp. cache Fail2Ban's default set of date templates.
		r   r   N)rG   rQ   rI   r;   )r=   rP   s     r$   rA   z%DateDetectorCache._addDefaultTemplate   sX     F$/!! br __Q'$//!*<<$
or&   N)__name__
__module____qualname____doc__r>   propertyrB   rI   rL   rQ   rA   r*   r&   r$   r6   r6   Y   sG     	 	&$3j - -	r&   r6   c                   0    e Zd ZdZdZd Zed        Zd Zy)DateDetectorTemplateztUsed for "shallow copy" of the template object.

	Prevents collectively usage of hits/lastUsed in cached templates
	r#   hitslastUseddistancec                 <    || _         d| _        d| _        d| _        y )Nr   rZ   )r=   r#   s     r$   r>   zDateDetectorTemplate.__init__   s    $-$)$-$-r&   c                 v    | j                   | j                  j                  z  t        d| j                        z  S )Nr   )r[   r#   rF   maxr]   r<   s    r$   rF   zDateDetectorTemplate.weight   s+    	T]]))	)C4==,A	AAr&   c                 .    t        | j                  |      S )zF Returns attribute of template (called for parameters not in slots)
		)r/   r#   )r=   r.   s     r$   __getattr__z DateDetectorTemplate.__getattr__   s     
	%%r&   N)	rS   rT   rU   rV   	__slots__r>   rW   rF   rc   r*   r&   r$   rY   rY      s.     : B B&r&   rY   c                       e Zd ZdZ e       Zd ZddZd ZddZ	e
d        Zd Ze
d	        Zej                  d
        ZddZd Zy)DateDetectorzjManages one or more date templates to find a date within a log line.

	Attributes
	----------
	templates
	c                     t               | _        t               | _        d| _        d| _        d| _        d| _        d| _        d | _	        d | _
        y )Ni,  )r   N)r_   Nr_   r   )r:   _DateDetector__templatesr!   _DateDetector__known_names_DateDetector__unusedTime_DateDetector__lastPos_DateDetector__lastEndPos_DateDetector__lastTemplIdx_DateDetector__firstUnused_DateDetector__preMatch_DateDetector__default_tzr<   s    r$   r>   zDateDetector.__init__   sL    V$u$$$.&$"$$$/$r&   c                     |j                   }|| j                  v r|ry t        d|z        | j                  j                  |       | j                  j                  t        |             y )Nz(There is already a template with name %s)r.   ri   
ValueErroraddrh   rH   rY   )r=   r#   	ignoreDupr.   s       r$   _appendTemplatezDateDetector._appendTemplate   sa    	$	T	.5
7 7.x89r&   c                 $   t        |t              r|x}d|vr|j                         t        j	                        }|sQdv rfd}| j                  |       ydv r| j                  |d       ydk(  rt        d	      }nt        |      }t        j                  |       | j                  |       t        j                  d
t        |dd      |j                         t        j                  dt        |dd      |j                         y)a  Add a date template to manage and use in search of dates.

		Parameters
		----------
		template : DateTemplate or str
			Can be either a `DateTemplate` instance, or a string which will
			be used as the pattern for the `DatePatternRegex` template. The
			template will then be added to the detector.

		Raises
		------
		ValueError
			If a template already exists with the same name.
		r   )r)   z	{DEFAULT}c                 L    dk(  r| j                   t        j                  z  S d S r(   )flagsr   
LINE_BEGIN)r#   r"   s    r$   r,   z-DateDetector.appendTemplate.<locals>.<lambda>  s"    3+CUx~~(?(?? [_ r&   Nz{DATE}F)preMatchallDefaultsz{NONE}z{UNB}^z  date pattern `%r`: `%s`r    z  date pattern regex for %r: %s)rK   rM   r   r   r   addDefaultTemplater%   r!   ru   logSysinfor/   r.   debugr0   )r=   r#   r   fltr"   s       @r$   appendTemplatezDateDetector.appendTemplate   s     #3	
--/C!!#&8

((_ 		S!	S	g5A	#Hc2X#GS1XsH%x ++)
8Y#X]]4,,0
8Y#X^^5r&   Nc                    t        | j                        dkD  }|rt        j                  j                  nt        j                  j
                  D ]2  }|	 ||      st        |fd      }| j                  ||       4 y)z0Add Fail2Ban's default set of date templates.
		r   Nc                 8     t         j                   fd      S )Nc                 .    t        j                        S r8   )r   unboundPattern)mr+   s    r$   r,   zCDateDetector.addDefaultTemplate.<locals>.<lambda>.<locals>.<lambda>7  s    <3N3Nq3Q r&   )RE_DATE_PREMATCHsub)r+   rz   s   `r$   r,   z1DateDetector.addDefaultTemplate.<locals>.<lambda>7  s    $(()QS[\ r&   )r2   )rt   )lenrh   rf   	_defCacherB   rQ   r4   ru   )r=   filterTemplaterz   r{   rt   r#   s     `   r$   r}   zDateDetector.addDefaultTemplate*  s     $""#a')'2<##8N8N8_8_7h  )A8#H
\^H I67r&   c                     | j                   S )r@   )rh   r<   s    r$   rB   zDateDetector.templates;  s     
		r&   c                 8   t        | j                        s| j                          t        j	                         t
        k  rt        j                  nd } |t
        dz
  d|       d}d}d}| j                  }|t        | j                        k  rq| j                  |   }|j                  }|j                  t        j                  t        j                  z  z  r& |t
        dz
  d|       |j                  |      }|}nD| j                  d   | j                  d   }
}	 |t
        dz
  d	||	|
||	dz
  |	 | j                  d   ||	|
 ||
|
dz    | j                  d
   
       ||	dz
  |	 | j                  d   k(  s5||	|	dz    | j                  d
   k(  r| j                  d
   j!                         su||
|
dz    | j                  d
   k(  s5||
dz
  |
 | j                  d   k(  rE| j                  d   j!                         s( |t
        dz
  d||	|
        |j                  ||	|
      }n# |t
        dz
  d       |j                  |      }|}|r|j#                         }	|j%                         }
t        | j                        dk(  sR|j                  t        j                  t        j                  z  z  s$|	| j                  d   k(  r!|
| j                  d   k(  r |t
        d|       n# |t
        d       ||	|
|f}d}n |t
        d       |s |t
        dt        | j                               d}| j                  D ]o  }||k(  r|dz  } |t
        dz
  d||j&                         |j                  }|j                  |      }|r |j#                         }	|j%                         }
 |t
        d||	|j(                  | j                  d   |j&                         |dz   t        | j                        k\  r n|j                  t        j                  t        j                  z  z  r n|	dk(  r4|j*                  r(| j                  |dz      j                  j*                  s nO|	|j(                  kD  s|	| j                  d   kD  r$ |t
        d       |	|d   k  r||	|
|f}d}|dz  }i n|dz  }r |s5|d   r0|\  }}	}
} |t
        d|       | j                  |   }|j                  }|rxj*                  dz  c_        t-        j,                         |_        	|_        | j0                  |k(  r| xj0                  dz  c_        |	||	dz
  |	 ||	   f| _        
||
dz
     ||
|
dz    f| _        |r || j                  k7  r| j3                  |      }|| _        |fS  |t
        d       y)a  Attempts to find date on a log line using templates.

		This uses the templates' `matchDate` method in an attempt to find
		a date. It also increments the match hit count for the winning
		template.

		Parameters
		----------
		line : str
			Line which is searched by the date templates.

		Returns
		-------
		re.MatchObject, DateTemplate
			The regex match returned from the first successfully matched
			template.
		c                       y r8   r*   )argss    r$   r,   z(DateDetector.matchTime.<locals>.<lambda>V  s    r&   r   z"try to match time for line: %.120sN)Nr_   r_   r_   z/  try to match last anchored template #%02i ...r   zJ  try to match last template #%02i (from %r to %r): ...%r==%r %s %r==%r...r   z+  boundaries are correct, search in part %rz,  boundaries show conflict, try whole searchz"  matched last time template #%02izB  ** last pattern collision - pattern change, reserve & search ...z8  ** last pattern not found - pattern change, search ...z search template (%i) ...z  try template #%02i: %sz2  matched time template #%02i (at %r <= %r, %r) %sz1  ** distance collision - pattern change, reservez  use best time template #%02iz no template.)NN)r   rh   r}   r~   getEffectiveLevellogLevellogrm   r#   rx   r   ry   LINE_END	matchDaterk   rl   isalnumr   endr.   r]   r[   timer\   rn   _reorderTemplate)r=   liner   matchfoundignoreBySearchrO   ddtemplr#   r]   endposs              r$   	matchTimezDateDetector.matchTimeA  sw   & 
T	..0H<

BT#hqj6= %
*%.
!T	a 78nn//0E0EEF
EqIt$EN~~a($*;*;A*>fH
`&	(1*Xq 1	(6	&D--a0	2 
(1*X$.."33HXaZ DNN1$55dnnQ>O>W>W>Y	&d//22F1HV 1 1! 44T=N=Nq=Q=Y=Y=[ 	!BDRXDYZh7U!CD%U^{{}HYY[F 			a^^|..|/D/DDE$..##$2C2CA2F(F7;WXHfa'UULM	x,c$2B2B.CD1"" "wN!VQ
.7<<@Ht$EXiikVG7##T^^A%6G 	
!s4##$$,11,2G2GGH	Q7<<1A1A!A#1F1O1O1T1T 	7###x$..2C'C	(GH	E!H	h)ue1fa
FAE"H E!H!&E8VQ2A6q!GH

<<1<iik77
A!d8A:h7hG4>tF1H~tF6!8/DD4A$$$a A4(
 h 	r&   c                     | j                   S r8   )rp   r<   s    r$   
default_tzzDateDetector.default_tz  s    			r&   c                 $    t        |      | _        y r8   )r   rp   )r=   values     r$   r   zDateDetector.default_tz  s    &u-$r&   c                 T   || j                  |      }|d   }|	 |j                  ||d   | j                        }|Yt        j	                         t
        k  r<t        j                  t
        d|d   |d   j                  d      |j                         |S 	 yy# t        $ r Y yw xY w)a  Attempts to return the date on a log line using templates.

		This uses the templates' `getDate` method in an attempt to find
		a date. 
		For the faster usage, always specify a parameter timeMatch (the previous tuple result
		of the matchTime), then this will work without locking and without cycle over templates.

		Parameters
		----------
		line : str
			Line which is searched by the date templates.

		Returns
		-------
		float
			The Unix timestamp returned from the first successfully matched
			template or None if not found.
		Nr   r   )r   z&  got time %f for %r using template %s)
r   getDaterp   r~   r   r   r   groupr.   rr   )r=   r   	timeMatchr#   dates        r$   getTimezDateDetector.getTime  s    ( ~~d#9q\(	D)A,4;L;LMD  "h.jjCAwQa (--1[	  
  			s   A;B 	B'&B'c                    rz| j                      t        j                         t        k  r&t        j	                  t        dj
                         j                  | j                  z
  j                  | j                  k  r| j                  ndz  fd} |       sdz
  k(  rS dz
   |       sS = gd | j                  t              k  r`| j                     j
                  rG| xj                  dz  c_	        | j                  t              k  r| j                     j
                  rGt        j                         t        k  rt        j	                  t        d       S S )zReorder template (bubble up) in template list if hits grows enough.

		Parameters
		----------
		num : int
			Index of template should be moved.
		z%  -> reorder template #%02i, hits: %rr   c                         j                   } t        j                         t        k  r7t        j	                  t        d| j
                     j
                         | kD  xs    j                  kD  S )NzE  -> compare template #%02i & #%02i, weight %.3f > %.3f, hits %r > %r)rF   r~   r   r   r   r[   r\   )pweightr   numposrB   untimerF   s    r$   	_moveablez0DateDetector._reorderTemplate.<locals>._moveable  so    n##G!X-ZZa	3y~/B/BDG?v	#(?(???r&   r   r   z"  -> moved template #%02i -> #%02i)rh   r~   r   r   r   r[   r\   rj   rF   rn   r   )r=   r   r   r   r   rB   r   rF   s    ` @@@@@r$   r   zDateDetector._reorderTemplate  sW    	9s^7 H,
JJx@#w||Tt0006NN6#11C7		SAX3@ @ +
c!e|Z
a%C;Z~i9S			c)n	,4;M;M1N1S1S! 
		c)n	,4;M;M1N1S1S H,
JJx=sCH
:	*r&   )F)NNTr8   )rS   rT   rU   rV   r6   r   r>   ru   r   r}   rW   rB   r   r   setterr   r   r*   r&   r$   rf   rf      sz       :(5T7"  
JX   . ."H-r&   rf   r8   )"
__author____copyright____license__copyr   	threadingr   datetemplater   r   r   r	   r
   r   strptimer   utilsr   helpersr   rS   r~   r   compile
IGNORECASEr   Cacher   r%   r4   objectr6   rY   rf   r*   r&   r$   <module>r      s   ( 7
2     &   
8	2::0"--@ %++tU;0 )B *k k\&6 &.H6 Hr&   