timetemplate.py

Go to the documentation of this file.
00001 # -*- coding: utf8 -*-
00002 # This file is part of Fail2Ban.
00003 #
00004 # Fail2Ban is free software; you can redistribute it and/or modify
00005 # it under the terms of the GNU General Public License as published by
00006 # the Free Software Foundation; either version 2 of the License, or
00007 # (at your option) any later version.
00008 #
00009 # Fail2Ban is distributed in the hope that it will be useful,
00010 # but WITHOUT ANY WARRANTY; without even the implied warranty of
00011 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00012 # GNU General Public License for more details.
00013 #
00014 # You should have received a copy of the GNU General Public License
00015 # along with Fail2Ban; if not, write to the Free Software
00016 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
00017 
00018 # Author: Cyril Jaquier
00019 # 
00020 # $Revision: 645 $
00021 
00022 __author__ = "Cyril Jaquier"
00023 __version__ = "$Revision: 645 $"
00024 __date__ = "$Date: 2008-01-16 23:55:04 +0100 (Wed, 16 Jan 2008) $"
00025 __copyright__ = "Copyright (c) 2004 Cyril Jaquier"
00026 __license__ = "GPL"
00027 
00028 import time, logging
00029 
00030 from template import Template, Templates
00031 from mytime import MyTime
00032 
00033 # Import ISO 8601 support.
00034 import iso8601
00035 
00036 # Gets the instance of the logger.
00037 logSys = logging.getLogger("fail2ban.timetemplate")
00038 
00039 class TimeTemplate(Template):
00040     
00041     def __init__(self):
00042         Template.__init__(self, Template.TEMPLATE_TIME, "<TIME>")
00043     
00044     def setRegex(self, regex):
00045         Template.setRegex(self, "(?P<%s>%s)" % (self.getName(), regex))
00046     
00047     def getTime(self, line):
00048         raise Exception("getTime() is abstract")
00049 
00050 
00051 class TimeISO8601(TimeTemplate):
00052 
00053     def __init__(self):
00054         TimeTemplate.__init__(self)
00055         date_re = "[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}" \
00056         ".[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+)?" \
00057         "(Z|(([-+])([0-9]{2}):([0-9]{2})))?"
00058         self.setRegex(date_re)
00059     
00060     def getTime(self, line):
00061         # Parses the date.
00062         return list(iso8601.parse_date(line).utctimetuple())
00063 
00064 
00065 class TimeEpoch(TimeTemplate):
00066     
00067     def __init__(self):
00068         TimeTemplate.__init__(self)
00069         # We already know the format for TAI64N
00070         self.setRegex("\d{10}(\.\d{6})?")
00071     
00072     def getTime(self, line):
00073         # extract part of format which represents seconds since epoch
00074         return list(time.localtime(float(line)))
00075 
00076 
00077 ##
00078 # Use strptime() to parse a date. Our current locale is the 'C'
00079 # one because we do not set the locale explicitly. This is POSIX
00080 # standard.
00081 
00082 class TimeStrptime(TimeTemplate):
00083     
00084     TABLE = dict()
00085     TABLE["Jan"] = []
00086     TABLE["Feb"] = [u"Fév"]
00087     TABLE["Mar"] = [u"Mär"]
00088     TABLE["Apr"] = ["Avr"]
00089     TABLE["May"] = ["Mai"]
00090     TABLE["Jun"] = []
00091     TABLE["Jul"] = []
00092     TABLE["Aug"] = ["Aou"]
00093     TABLE["Sep"] = []
00094     TABLE["Oct"] = ["Okt"]
00095     TABLE["Nov"] = []
00096     TABLE["Dec"] = [u"Déc", "Dez"]
00097     
00098     def __init__(self):
00099         TimeTemplate.__init__(self)
00100         self.__pattern = ""
00101     
00102     def setPattern(self, pattern):
00103         self.__pattern = pattern.strip()
00104         
00105     def getPattern(self):
00106         return self.__pattern
00107     
00108     #@staticmethod
00109     def convertLocale(date):
00110         for t in TimeStrptime.TABLE:
00111             for m in TimeStrptime.TABLE[t]:
00112                 if date.find(m) >= 0:
00113                     return date.replace(m, t)
00114         return date
00115     convertLocale = staticmethod(convertLocale)
00116     
00117     def getTime(self, line):
00118         try:
00119             # Try first with 'C' locale
00120             date = list(time.strptime(line, self.getPattern()))
00121         except ValueError:
00122             # Try to convert date string to 'C' locale
00123             conv = self.convertLocale(line)
00124             try:
00125                 date = list(time.strptime(conv, self.getPattern()))
00126             except ValueError:
00127                 # Try to add the current year to the pattern. Should fix
00128                 # the "Feb 29" issue.
00129                 conv += " %s" % MyTime.gmtime()[0]
00130                 pattern = "%s %%Y" % self.getPattern()
00131                 date = list(time.strptime(conv, pattern))
00132         if date[0] < 2000:
00133             # There is probably no year field in the logs
00134             date[0] = MyTime.gmtime()[0]
00135             # Bug fix for #1241756
00136             # If the date is greater than the current time, we suppose
00137             # that the log is not from this year but from the year before
00138             if time.mktime(date) > MyTime.time():
00139                 date[0] -= 1
00140         return date
00141 
00142 
00143 class TimeTai64n(TimeTemplate):
00144     
00145     def __init__(self):
00146         TimeTemplate.__init__(self)
00147         # We already know the format for TAI64N
00148         self.setRegex("@[0-9a-f]{24}")
00149     
00150     def getTime(self, line):
00151         # extract part of format which represents seconds since epoch
00152         seconds_since_epoch = line[2:17]
00153         return list(time.gmtime(int(seconds_since_epoch, 16)))
00154 
00155 
00156 class TimeTemplates(Templates):
00157     
00158     def __init__(self):
00159         Templates.__init__(self)
00160         # standard
00161         template = TimeStrptime()
00162         template.setDescription("Month Day Hour:Minute:Second")
00163         template.setRegex("\S{3}\s{1,2}\d{1,2} \d{2}:\d{2}:\d{2}")
00164         template.setPattern("%b %d %H:%M:%S")
00165         self.templates.append(template)
00166         # asctime
00167         template = TimeStrptime()
00168         template.setDescription("Weekday Month Day Hour:Minute:Second Year")
00169         template.setRegex("\S{3} \S{3}\s{1,2}\d{1,2} \d{2}:\d{2}:\d{2} \d{4}")
00170         template.setPattern("%a %b %d %H:%M:%S %Y")
00171         self.templates.append(template)
00172         # asctime without year
00173         template = TimeStrptime()
00174         template.setDescription("Weekday Month Day Hour:Minute:Second")
00175         template.setRegex("\S{3} \S{3}\s{1,2}\d{1,2} \d{2}:\d{2}:\d{2}")
00176         template.setPattern("%a %b %d %H:%M:%S")
00177         self.templates.append(template)
00178         # simple date
00179         template = TimeStrptime()
00180         template.setDescription("Year/Month/Day Hour:Minute:Second")
00181         template.setRegex("\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}")
00182         template.setPattern("%Y/%m/%d %H:%M:%S")
00183         self.templates.append(template)
00184         # simple date too (from x11vnc)
00185         template = TimeStrptime()
00186         template.setDescription("Day/Month/Year Hour:Minute:Second")
00187         template.setRegex("\d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2}")
00188         template.setPattern("%d/%m/%Y %H:%M:%S")
00189         self.templates.append(template)
00190         # Apache format [31/Oct/2006:09:22:55 -0000]
00191         template = TimeStrptime()
00192         template.setDescription("Day/Month/Year:Hour:Minute:Second")
00193         template.setRegex("\d{2}/\S{3}/\d{4}:\d{2}:\d{2}:\d{2}")
00194         template.setPattern("%d/%b/%Y:%H:%M:%S")
00195         self.templates.append(template)
00196         # Exim 2006-12-21 06:43:20
00197         template = TimeStrptime()
00198         template.setDescription("Year-Month-Day Hour:Minute:Second")
00199         template.setRegex("\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}")
00200         template.setPattern("%Y-%m-%d %H:%M:%S")
00201         self.templates.append(template)
00202         # named 26-Jul-2007 15:20:52.252 
00203         template = TimeStrptime()
00204         template.setDescription("Day-Month-Year Hour:Minute:Second[.Millisecond]")
00205         template.setRegex("\d{2}-\S{3}-\d{4} \d{2}:\d{2}:\d{2}")
00206         template.setPattern("%d-%b-%Y %H:%M:%S")
00207         self.templates.append(template)
00208         # TAI64N
00209         template = TimeTai64n()
00210         template.setDescription("TAI64N")
00211         self.templates.append(template)
00212         # Epoch
00213         template = TimeEpoch()
00214         template.setDescription("Epoch")
00215         self.templates.append(template)
00216         # ISO 8601
00217         template = TimeISO8601()
00218         template.setDescription("ISO 8601")
00219         self.templates.append(template)
Generated on Wed May 22 03:05:07 2013 for Fail2Ban by  doxygen 1.6.3