a =*fL@sdZdZdZddlZddlZddlmZddlmZm Z m Z m Z m Z m Z ddlmZdd lmZd d lmZeeZd Zed ejZejdddZdddZddfddZGdddeZGdddeZ GdddeZ!dS)z'Cyril Jaquier and Fail2Ban Contributorsz Copyright (c) 2004 Cyril JaquierZGPLN)Lock)re DateTemplateDatePatternRegex DateTai64n DateEpochRE_EPOCH_PATTERN)validateTimeZone)Utils) getLoggerz(?Dr%cCsb||j}t|}|s^|t|d|j}t|dr>t|}|s^t|dsVt|}nt|}|S)Nr)namerrgetattrregexhasattrr )rwrapr' template2r)rrr_getAnchoredTemplateDs      r-c@sHeZdZdZddZeddZddZgdZed d Z d d Z d S)DateDetectorCachez7Implements the caching of the default templates list. cCst|_t|_dSN)r_DateDetectorCache__locklist_DateDetectorCache__templatesselfrrr__init__\szDateDetectorCache.__init__cCs^|jr |jS|j8|jr.|jWdS||jWdS1sP0YdS)6List of template instances managed by the detector. N)r2r0_addDefaultTemplater3rrr templates`szDateDetectorCache.templatescCs`|j}|dsL|dsLt|drLt|}|j|krLd|_|jd||jd|dS)z&Cache Fail2Ban's default template. r"^r)gY@rrN)r' startswithr*r-weight_DateDetectorCache__tmpcacheappend)r4rr'r,rrr_cacheTemplatels z DateDetectorCache._cacheTemplate)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)?rz{^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)?rcCs<ttjdtr6ttjD]\}}t|}|tj|<qtjS)Nr) isinstancer.DEFAULT_TEMPLATESstr enumerater )r4idtrrrdefaultTemplatess  z"DateDetectorCache.defaultTemplatescCs>ggf|_|jD]}||q|jd|jd|_|`dS)zr2)r4rDrrrr7s    z%DateDetectorCache._addDefaultTemplateN) __name__ __module__ __qualname____doc__r5propertyr8r>r@rEr7rrrrr.Ys 5 r.c@s0eZdZdZdZddZeddZddZd S) DateDetectorTemplateztUsed for "shallow copy" of the template object. Prevents collectively usage of hits/lastUsed in cached templates rhitslastUseddistancecCs||_d|_d|_d|_dS)NrrL)r4rrrrr5szDateDetectorTemplate.__init__cCs|j|jjtd|jS)Nr)rMrr;maxrOr3rrrr;szDateDetectorTemplate.weightcCs t|j|S)zF Returns attribute of template (called for parameters not in slots) )r(r)r4r'rrr __getattr__sz DateDetectorTemplate.__getattr__N) rFrGrHrI __slots__r5rJr;rRrrrrrKs  rKc@szeZdZdZeZddZdddZddZdd d Z e d dZ ddZ e ddZ e jddZ dddZddZd S) DateDetectorzjManages one or more date templates to find a date within a log line. Attributes ---------- templates cCs>t|_t|_d|_d|_d|_d|_d|_d|_ d|_ dS)Ni,)rN)rPNrPr) r1_DateDetector__templatesr_DateDetector__known_names_DateDetector__unusedTime_DateDetector__lastPos_DateDetector__lastEndPos_DateDetector__lastTemplIdx_DateDetector__firstUnusedZ_DateDetector__preMatch_DateDetector__default_tzr3rrrr5szDateDetector.__init__FcCsD|j}||jvr$|rdStd||j||jt|dS)Nz(There is already a template with name %s)r'rV ValueErroraddrUr=rK)r4r ignoreDupr'rrr_appendTemplates  zDateDetector._appendTemplatecst|tr|}d|vr"|t}|sdvrRfdd}||dSdvrl|j|dddSd krtd }n t|}t|||t d t |d d |j t dt |d d |jdS)aAdd 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}csdkr|jtj@SdSr!)flagsr LINE_BEGIN)rrrrr%r&z-DateDetector.appendTemplate..Nz{DATE}F)preMatch allDefaultsz{NONE}z{UNB}^z date pattern `%r`: `%s`rz date pattern regex for %r: %s)r?rArrraddDefaultTemplater rr`logSysinfor(r'debugr))r4rrZfltrrcrappendTemplates2        zDateDetector.appendTemplateNTcsht|jdk}|rtjjntjjD]@}|dur8||s8q"durTt|fddd}|j||dq"dS)z0Add Fail2Ban's default set of date templates. rNcstfddS)Ncs tSr/)rZunboundPattern)mr#rrr%7r&zCDateDetector.addDefaultTemplate....)RE_DATE_PREMATCHsubr#rdr#rr%7r&z1DateDetector.addDefaultTemplate..)r+)r_)lenrUrT _defCacher8rEr-r`)r4ZfilterTemplaterdrer_rrrorrg*s zDateDetector.addDefaultTemplatecCs|jS)r6)rUr3rrrr8;szDateDetector.templatesc Cst|js|ttkr$tjndd}|tdd|d}d}d}|j}|t|jkrd|j|}|j}|j t j t j B@r|tdd|| |}|}n4|jd |jd } } |tdd || | || d| |jd|| | || | d|jd  || d| |jdksJ|| | d|jd kr|jd s|| | d|jd ks|| d| |jdkr|jds|tdd || | | || | }n|tdd | |}|}|rZ|} |} t|jdks0|j t j t j B@s0| |jd kr>| |jd kr>|td|n|td|| | |f}d}n |td|s|tdt|jd }|jD]2}||kr|d7}q|tdd||j|j}| |}|r|} |} |td|| |j|jd |j|dt|jkrq|j t j t j B@r.q| d krZ|jrZ|j|djjsZq| |jksv| |jd kr|td| |dkr|| | |f}d}|d7}qq|d7}q|s|d r|\}} } }|td||j|}|j}|r|jd7_t|_| |_|j|kr2|jd7_| || d| || f|_| || d|| | df|_|r||jkr||}||_||fS|tddS)aAttempts 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. cWsdSr/r)argsrrrr%Vr&z(DateDetector.matchTime..rz"try to match time for line: %.120sN)NrPrPrPz/ try to match last anchored template #%02i ...rzJ 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)rprUrgrhgetEffectiveLevellogLevellogrZrrarrbZLINE_ENDZ matchDaterXrYisalnumrendr'rOrMtimerNr[_reorderTemplate) r4linervmatchfoundZignoreBySearchrCddtemplrrOendposrrr matchTimeAs                 &           zDateDetector.matchTimecCs|jSr/)r\r3rrr default_tzszDateDetector.default_tzcCst||_dSr/)r r\)r4valuerrrrscCs|dur||}|d}|durzV|j||d|jd}|durvttkrpttd|d|dd|j|WSWnt yYn0dS)aAttempts 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. Nrr)rz& got time %f for %r using template %s) rZgetDater\rhrtrurvgroupr'r])r4r{Z timeMatchrdaterrrgetTimes    zDateDetector.getTimecsr|jttkr0ttdjj|jj|j krR|j ndfdd}|sdkrSd|sS=gd<|j t krֈ|j jr|j d7_ qttkrttdSS)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 sLj}ttkr6ttd|jj|kpJjkS)NzE -> compare template #%02i & #%02i, weight %.3f > %.3f, hits %r > %r)r;rhrtrurvrMrN)Zpweightr~numposr8Zuntimer;rr _moveable s   z0DateDetector._reorderTemplate.._moveablerrz" -> moved template #%02i -> #%02i) rUrhrtrurvrMrNrWr;r[rp)r4rrrrrrzs.    zDateDetector._reorderTemplate)F)NNT)N)rFrGrHrIr.rqr5r`rkrgrJr8rrsetterrrzrrrrrTs  *      $rT)N)" __author__Z __copyright__Z __license__copyry threadingrZ datetemplaterrrrrr strptimer Zutilsr Zhelpersr rFrhrucompile IGNORECASErmZCacherr r-objectr.rKrTrrrrs$      n