Debian Codegraph @

runtime/datetime.c

raw
1 /* The datetime object. It contains date and time related functions.
2 *
3 * Module begun 2008-03-05 by Rainer Gerhards, based on some code
4 * from syslogd.c. The main intension was to move code out of syslogd.c
5 * in a useful manner. It is still undecided if all functions will continue
6 * to stay here or some will be moved into parser modules (once we have them).
7 *
8 * Copyright 2008-2016 Rainer Gerhards and Adiscon GmbH.
9 *
10 * This file is part of the rsyslog runtime library.
11 *
12 * Licensed under the Apache License, Version 2.0 (the "License");
13 * you may not use this file except in compliance with the License.
14 * You may obtain a copy of the License at
15 *
16 * http://www.apache.org/licenses/LICENSE-2.0
17 * -or-
18 * see COPYING.ASL20 in the source distribution
19 *
20 * Unless required by applicable law or agreed to in writing, software
21 * distributed under the License is distributed on an "AS IS" BASIS,
22 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23 * See the License for the specific language governing permissions and
24 * limitations under the License.
25 */
26
27 #include "config.h"
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <stdarg.h>
31 #include <ctype.h>
32 #include <assert.h>
33 #include <string.h>
34 #ifdef HAVE_SYS_TIME_H
35 #include <sys/time.h>
36 #endif
37
38 #include "rsyslog.h"
39 #include "obj.h"
40 #include "modules.h"
41 #include "datetime.h"
42 #include "srUtils.h"
43 #include "stringbuf.h"
44 #include "errmsg.h"
45 #include "rsconf.h"
46 #include "timezones.h"
47
48 /* static data */
49 DEFobjStaticHelpers;
50
51 /* the following table of ten powers saves us some computation */
52 static const int tenPowers[6] = {1, 10, 100, 1000, 10000, 100000};
53
54 /* the following table saves us from computing an additional date to get
55 * the ordinal day of the year - at least from 1967-2099
56 * Note: non-2038+ compliant systems (Solaris) will generate compiler
57 * warnings on the post 2038-rollover years.
58 */
59 static const int yearInSec_startYear = 1967;
60 /* for x in $(seq 1967 2099) ; do
61 * printf %s', ' $(date --date="Dec 31 ${x} UTC 23:59:59" +%s)
62 * done |fold -w 70 -s */
63 static const long long yearInSecs[] = {
64 -63158401, -31536001, -1, 31535999, 63071999, 94694399, 126230399, 157766399, 189302399,
65 220924799, 252460799, 283996799, 315532799, 347155199, 378691199, 410227199, 441763199, 473385599,
66 504921599, 536457599, 567993599, 599615999, 631151999, 662687999, 694223999, 725846399, 757382399,
67 788918399, 820454399, 852076799, 883612799, 915148799, 946684799, 978307199, 1009843199, 1041379199,
68 1072915199, 1104537599, 1136073599, 1167609599, 1199145599, 1230767999, 1262303999, 1293839999, 1325375999,
69 1356998399, 1388534399, 1420070399, 1451606399, 1483228799, 1514764799, 1546300799, 1577836799, 1609459199,
70 1640995199, 1672531199, 1704067199, 1735689599, 1767225599, 1798761599, 1830297599, 1861919999, 1893455999,
71 1924991999, 1956527999, 1988150399, 2019686399, 2051222399, 2082758399, 2114380799, 2145916799, 2177452799,
72 2208988799, 2240611199, 2272147199, 2303683199, 2335219199, 2366841599, 2398377599, 2429913599, 2461449599,
73 2493071999, 2524607999, 2556143999, 2587679999, 2619302399, 2650838399, 2682374399, 2713910399, 2745532799,
74 2777068799, 2808604799, 2840140799, 2871763199, 2903299199, 2934835199, 2966371199, 2997993599, 3029529599,
75 3061065599, 3092601599, 3124223999, 3155759999, 3187295999, 3218831999, 3250454399, 3281990399, 3313526399,
76 3345062399, 3376684799, 3408220799, 3439756799, 3471292799, 3502915199, 3534451199, 3565987199, 3597523199,
77 3629145599, 3660681599, 3692217599, 3723753599, 3755375999, 3786911999, 3818447999, 3849983999, 3881606399,
78 3913142399, 3944678399, 3976214399, 4007836799, 4039372799, 4070908799, 4102444799};
79
80 /* note ramge is 1969 -> 2100 because it needs to access previous/next year */
81 /* for x in $(seq 1969 2100) ; do
82 * printf %s', ' $(date --date="Dec 28 ${x} UTC 12:00:00" +%V)
83 * done | fold -w 70 -s */
84 static const int weeksInYear[] = {
85 52, 53, 52, 52, 52, 52, 52, 53, 52, 52, 52, 52, 53, 52, 52, 52, 52, 52, 53, 52, 52, 52, 52, 53, 52, 52, 52,
86 52, 52, 53, 52, 52, 52, 52, 52, 53, 52, 52, 52, 52, 53, 52, 52, 52, 52, 52, 53, 52, 52, 52, 52, 53, 52, 52,
87 52, 52, 52, 53, 52, 52, 52, 52, 52, 53, 52, 52, 52, 52, 53, 52, 52, 52, 52, 52, 53, 52, 52, 52, 52, 53, 52,
88 52, 52, 52, 52, 53, 52, 52, 52, 52, 52, 53, 52, 52, 52, 52, 53, 52, 52, 52, 52, 52, 53, 52, 52, 52, 52, 53,
89 52, 52, 52, 52, 52, 53, 52, 52, 52, 52, 52, 53, 52, 52, 52, 52, 53, 52, 52, 52, 52, 52, 53, 52,
90 };
91
92 static const char *monthNames[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
93 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
94
95 /* ------------------------------ methods ------------------------------ */
96
97
98 /**
99 * Convert struct timeval to syslog_time
100 */
101 static void timeval2syslogTime(struct timeval *tp, struct syslogTime *t, const int inUTC) {
102 struct tm *tm;
103 struct tm tmBuf;
104 long lBias;
105 time_t secs;
106
107 #if defined(__hpux)
108 struct timezone tz;
109 #endif
110 secs = tp->tv_sec;
111 if (inUTC)
112 tm = gmtime_r(&secs, &tmBuf);
113 else
114 tm = localtime_r(&secs, &tmBuf);
115
116 t->year = tm->tm_year + 1900;
117 t->month = tm->tm_mon + 1;
118 t->day = tm->tm_mday;
119 t->wday = tm->tm_wday;
120 t->hour = tm->tm_hour;
121 t->minute = tm->tm_min;
122 t->second = tm->tm_sec;
123 t->secfrac = tp->tv_usec;
124 t->secfracPrecision = 6;
125
126 if (inUTC) {
127 t->OffsetMode = '+';
128 lBias = 0;
129 } else {
130 #if defined(__sun)
131 /* Solaris uses a different method of exporting the time zone.
132 * It is UTC - localtime, which is the opposite sign of mins east of GMT.
133 */
134 lBias = -(tm->tm_isdst ? altzone : timezone);
135 #elif defined(__hpux)
136 lBias = tz.tz_dsttime ? -tz.tz_minuteswest : 0;
137 #elif defined(_AIX)
138 /* AIXPORT : IBM documentation notice that 'extern long timezone'
139 * is setted after calling tzset.
140 * Recent version of AIX, localtime_r call inside tzset.
141 */
142 if (tm->tm_isdst) tzset();
143 lBias = -timezone;
144 #else
145 lBias = tm->tm_gmtoff;
146 #endif
147 if (lBias < 0) {
148 t->OffsetMode = '-';
149 lBias *= -1;
150 } else
151 t->OffsetMode = '+';
152 }
153 t->OffsetHour = lBias / 3600;
154 t->OffsetMinute = (lBias % 3600) / 60;
155 t->timeType = TIME_TYPE_RFC5424; /* we have a high precision timestamp */
156 t->inUTC = inUTC;
157 }
158
159 /**
160 * Get the current date/time in the best resolution the operating
161 * system has to offer (well, actually at most down to the milli-
162 * second level.
163 *
164 * The date and time is returned in separate fields as this is
165 * most portable and removes the need for additional structures
166 * (but I have to admit it is somewhat "bulky";)).
167 *
168 * Obviously, *t must not be NULL...
169 *
170 * rgerhards, 2008-10-07: added ttSeconds to provide a way to
171 * obtain the second-resolution UNIX timestamp. This is needed
172 * in some situations to minimize time() calls (namely when doing
173 * output processing). This can be left NULL if not needed.
174 */
175 static void getCurrTime(struct syslogTime *t, time_t *ttSeconds, const int inUTC) {
176 struct timeval tp;
177 /* AIXPORT : fix build error : "tm_gmtoff" is not a member of "struct tm"
178 * Choose the HPUX code path, only for this function.
179 * This is achieved by adding a check to _AIX wherever _hpux is checked
180 */
181
182
183 #if defined(__hpux) || defined(_AIX)
184 struct timezone tz;
185 #endif
186
187 assert(t != NULL);
188 #if defined(__hpux) || defined(_AIX)
189 /* NOTE: under HP UX, the tz information might actually be
190 * valid data. So we need to obtain and process it there.
191 * As HP UX is not a supported platform, this is left to
192 * explore by someone with interest in this platform.
193 */
194 gettimeofday(&tp, &tz);
195 #else
196 gettimeofday(&tp, NULL);
197 #endif
198 if (ttSeconds != NULL) *ttSeconds = tp.tv_sec;
199
200 timeval2syslogTime(&tp, t, inUTC);
201 }
202
203
204 /* A fast alternative to getCurrTime() and time() that only obtains
205 * a timestamp like time() does. I was told that gettimeofday(), at
206 * least under Linux, is much faster than time() and I could confirm
207 * this testing. So I created that function as a replacement.
208 * rgerhards, 2009-11-12
209 */
210 time_t getTime(time_t *ttSeconds) {
211 struct timeval tp;
212
213 if (gettimeofday(&tp, NULL) == -1) return -1;
214
215 if (ttSeconds != NULL) *ttSeconds = tp.tv_sec;
216 return tp.tv_sec;
217 }
218
219 dateTimeFormat_t getDateTimeFormatFromStr(const char *const __restrict__ s) {
220 assert(s != NULL);
221
222 if (strcmp(s, "date-rfc3164") == 0) return DATE_RFC3164;
223 if (strcmp(s, "date-rfc3339") == 0) return DATE_RFC3339;
224 if (strcmp(s, "date-unix") == 0) return DATE_UNIX;
225
226 return DATE_INVALID;
227 }
228
229 /*******************************************************************
230 * BEGIN CODE-LIBLOGGING *
231 *******************************************************************
232 * Code in this section is borrowed from liblogging. This is an
233 * interim solution. Once liblogging is fully integrated, this is
234 * to be removed (see http://www.monitorware.com/liblogging for
235 * more details. 2004-11-16 rgerhards
236 *
237 * Please note that the orginal liblogging code is modified so that
238 * it fits into the context of the current version of syslogd.c.
239 *
240 * DO NOT PUT ANY OTHER CODE IN THIS BEGIN ... END BLOCK!!!!
241 */
242
243
244 /**
245 * Parse a 32 bit integer number from a string. We do not permit
246 * integer overruns, this the guard against INT_MAX.
247 *
248 * \param ppsz Pointer to the Pointer to the string being parsed. It
249 * must be positioned at the first digit. Will be updated
250 * so that on return it points to the first character AFTER
251 * the integer parsed.
252 * \param pLenStr pointer to string length, decremented on exit by
253 * characters processed
254 * Note that if an empty string (len < 1) is passed in,
255 * the method always returns zero.
256 * \retval The number parsed.
257 */
258 static int srSLMGParseInt32(uchar **ppsz, int *pLenStr) {
259 register int i;
260
261 i = 0;
262 while (*pLenStr > 0 && **ppsz >= '0' && **ppsz <= '9' && i < INT_MAX / 10 - 1) {
263 i = i * 10 + **ppsz - '0';
264 ++(*ppsz);
265 --(*pLenStr);
266 }
267
268 return i;
269 }
270
271
272 /**
273 * Parse a TIMESTAMP-3339.
274 * updates the parse pointer position. The pTime parameter
275 * is guranteed to be updated only if a new valid timestamp
276 * could be obtained (restriction added 2008-09-16 by rgerhards).
277 * This method now also checks the maximum string length it is passed.
278 * If a *valid* timestamp is found, the string length is decremented
279 * by the number of characters processed. If it is not a valid timestamp,
280 * the length is kept unmodified. -- rgerhards, 2009-09-23
281 */
282 static rsRetVal ParseTIMESTAMP3339(struct syslogTime *pTime, uchar **ppszTS, int *pLenStr) {
283 uchar *pszTS = *ppszTS;
284 /* variables to temporarily hold time information while we parse */
285 int year;
286 int month;
287 int day;
288 int hour; /* 24 hour clock */
289 int minute;
290 int second;
291 int secfrac; /* fractional seconds (must be 32 bit!) */
292 int secfracPrecision;
293 char OffsetMode; /* UTC offset + or - */
294 int OffsetHour; /* UTC offset in hours */
295 int OffsetMinute; /* UTC offset in minutes */
296 int lenStr;
297 /* end variables to temporarily hold time information while we parse */
298 DEFiRet;
299
300 assert(pTime != NULL);
301 assert(ppszTS != NULL);
302 assert(pszTS != NULL);
303
304 lenStr = *pLenStr;
305 year = srSLMGParseInt32(&pszTS, &lenStr);
306
307 /* We take the liberty to accept slightly malformed timestamps e.g. in
308 * the format of 2003-9-1T1:0:0. This doesn't hurt on receiving. Of course,
309 * with the current state of affairs, we would never run into this code
310 * here because at postion 11, there is no "T" in such cases ;)
311 */
312 if (lenStr == 0 || *pszTS++ != '-' || year < 0 || year >= 2100) {
313 DBGPRINTF("ParseTIMESTAMP3339: invalid year: %d, pszTS: '%c'\n", year, *pszTS);
314 ABORT_FINALIZE(RS_RET_INVLD_TIME);
315 }
316 --lenStr;
317 month = srSLMGParseInt32(&pszTS, &lenStr);
318 if (month < 1 || month > 12) ABORT_FINALIZE(RS_RET_INVLD_TIME);
319
320 if (lenStr == 0 || *pszTS++ != '-') ABORT_FINALIZE(RS_RET_INVLD_TIME);
321 --lenStr;
322 day = srSLMGParseInt32(&pszTS, &lenStr);
323 if (day < 1 || day > 31) ABORT_FINALIZE(RS_RET_INVLD_TIME);
324
325 if (lenStr == 0 || *pszTS++ != 'T') ABORT_FINALIZE(RS_RET_INVLD_TIME);
326 --lenStr;
327
328 hour = srSLMGParseInt32(&pszTS, &lenStr);
329 if (hour < 0 || hour > 23) ABORT_FINALIZE(RS_RET_INVLD_TIME);
330
331 if (lenStr == 0 || *pszTS++ != ':') ABORT_FINALIZE(RS_RET_INVLD_TIME);
332 --lenStr;
333 minute = srSLMGParseInt32(&pszTS, &lenStr);
334 if (minute < 0 || minute > 59) ABORT_FINALIZE(RS_RET_INVLD_TIME);
335
336 if (lenStr == 0 || *pszTS++ != ':') ABORT_FINALIZE(RS_RET_INVLD_TIME);
337 --lenStr;
338 second = srSLMGParseInt32(&pszTS, &lenStr);
339 if (second < 0 || second > 60) ABORT_FINALIZE(RS_RET_INVLD_TIME);
340
341 /* Now let's see if we have secfrac */
342 if (lenStr > 0 && *pszTS == '.') {
343 --lenStr;
344 uchar *pszStart = ++pszTS;
345 secfrac = srSLMGParseInt32(&pszTS, &lenStr);
346 secfracPrecision = (int)(pszTS - pszStart);
347 } else {
348 secfracPrecision = 0;
349 secfrac = 0;
350 }
351
352 /* check the timezone */
353 if (lenStr == 0) ABORT_FINALIZE(RS_RET_INVLD_TIME);
354
355 if (*pszTS == 'Z') {
356 --lenStr;
357 pszTS++; /* eat Z */
358 OffsetMode = 'Z';
359 OffsetHour = 0;
360 OffsetMinute = 0;
361 } else if ((*pszTS == '+') || (*pszTS == '-')) {
362 OffsetMode = *pszTS;
363 --lenStr;
364 pszTS++;
365
366 OffsetHour = srSLMGParseInt32(&pszTS, &lenStr);
367 if (OffsetHour < 0 || OffsetHour > 23) ABORT_FINALIZE(RS_RET_INVLD_TIME);
368
369 if (lenStr == 0 || *pszTS != ':') ABORT_FINALIZE(RS_RET_INVLD_TIME);
370 --lenStr;
371 pszTS++;
372 OffsetMinute = srSLMGParseInt32(&pszTS, &lenStr);
373 if (OffsetMinute < 0 || OffsetMinute > 59) ABORT_FINALIZE(RS_RET_INVLD_TIME);
374 } else {
375 /* there MUST be TZ information */
376 ABORT_FINALIZE(RS_RET_INVLD_TIME);
377 }
378
379 /* OK, we actually have a 3339 timestamp, so let's indicated this */
380 if (lenStr > 0) {
381 if (*pszTS != ' ') /* if it is not a space, it can not be a "good" time - 2010-02-22 rgerhards */
382 ABORT_FINALIZE(RS_RET_INVLD_TIME);
383 ++pszTS; /* just skip past it */
384 --lenStr;
385 }
386
387 /* we had success, so update parse pointer and caller-provided timestamp */
388 *ppszTS = pszTS;
389 pTime->timeType = 2;
390 pTime->year = year;
391 pTime->month = month;
392 pTime->day = day;
393 pTime->hour = hour;
394 pTime->minute = minute;
395 pTime->second = second;
396 pTime->secfrac = secfrac;
397 pTime->secfracPrecision = secfracPrecision;
398 pTime->OffsetMode = OffsetMode;
399 pTime->OffsetHour = OffsetHour;
400 pTime->OffsetMinute = OffsetMinute;
401 *pLenStr = lenStr;
402
403 finalize_it:
404 RETiRet;
405 }
406
407
408 /**
409 * Parse a TIMESTAMP-3164. The pTime parameter
410 * is guranteed to be updated only if a new valid timestamp
411 * could be obtained (restriction added 2008-09-16 by rgerhards). This
412 * also means the caller *must* provide a valid (probably current)
413 * timstamp in pTime when calling this function. a 3164 timestamp contains
414 * only partial information and only that partial information is updated.
415 * So the "output timestamp" is a valid timestamp only if the "input
416 * timestamp" was valid, too. The is actually an optimization, as it
417 * permits us to use a pre-acquired timestamp and thus avoids to do
418 * a (costly) time() call. Thanks to David Lang for insisting on
419 * time() call reduction ;).
420 * This method now also checks the maximum string length it is passed.
421 * If a *valid* timestamp is found, the string length is decremented
422 * by the number of characters processed. If it is not a valid timestamp,
423 * the length is kept unmodified. -- rgerhards, 2009-09-23
424 *
425 * We support this format:
426 * [yyyy] Mon mm [yyyy] hh:mm:ss[.subsec][ [yyyy ]/[TZSTRING:]]
427 * Note that [yyyy] and [.subsec] are non-standard but frequently occur.
428 * Also [yyyy] can only occur once -- if it occurs twice, we flag the
429 * timestamp as invalid. if bParseTZ is true, we try to obtain a
430 * TZSTRING. Note that in this case it MUST be terminated by a colon
431 * (Cisco format). This option is a bit dangerous, as it could already
432 * by the tag. So it MUST only be enabled in specialised parsers.
433 * subsec, [yyyy] in front, TZSTRING was added in 2014-07-08 rgerhards
434 * Similarly, we try to detect a year after the timestamp if
435 * bDetectYearAfterTime is set. This is mutally exclusive with bParseTZ.
436 * Note: bDetectYearAfterTime will misdetect hostnames in the range
437 * 2000..2100 as years, so this option should explicitly be turned on
438 * and is not meant for general consumption.
439 */
440 static rsRetVal ParseTIMESTAMP3164(
441 struct syslogTime *pTime, uchar **ppszTS, int *pLenStr, const int bParseTZ, const int bDetectYearAfterTime) {
442 /* variables to temporarily hold time information while we parse */
443 int month;
444 int day;
445 int year = 0; /* 0 means no year provided */
446 int hour; /* 24 hour clock */
447 int minute;
448 int second;
449 int secfrac; /* fractional seconds (must be 32 bit!) */
450 int secfracPrecision;
451 char tzstring[16];
452 char OffsetMode = '\0'; /* UTC offset: \0 -> indicate no update */
453 char OffsetHour = '\0'; /* UTC offset in hours */
454 int OffsetMinute = 0; /* UTC offset in minutes */
455 /* end variables to temporarily hold time information while we parse */
456 int lenStr;
457 uchar *pszTS;
458 DEFiRet;
459
460 assert(ppszTS != NULL);
461 pszTS = *ppszTS;
462 assert(pszTS != NULL);
463 assert(pTime != NULL);
464 assert(pLenStr != NULL);
465 lenStr = *pLenStr;
466
467 if (lenStr < 3) ABORT_FINALIZE(RS_RET_INVLD_TIME);
468
469 /* first check if we have a year in front of the timestamp. some devices (e.g. Brocade)
470 * do this. As it is pretty straightforward to detect and chance of misinterpretation
471 * is low, we try to parse it.
472 */
473 if (*pszTS >= '0' && *pszTS <= '9') {
474 /* OK, either we have a prepended year or an invalid format! */
475 year = srSLMGParseInt32(&pszTS, &lenStr);
476 if (year < 1970 || year > 2100 || *pszTS != ' ') ABORT_FINALIZE(RS_RET_INVLD_TIME);
477 ++pszTS; /* skip SP */
478 }
479
480 /* If we look at the month (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec),
481 * we may see the following character sequences occur:
482 *
483 * J(an/u(n/l)), Feb, Ma(r/y), A(pr/ug), Sep, Oct, Nov, Dec
484 *
485 * We will use this for parsing, as it probably is the
486 * fastest way to parse it.
487 *
488 * 2009-08-17: we now do case-insensitive comparisons, as some devices obviously do not
489 * obey to the RFC-specified case. As we need to guess in any case, we can ignore case
490 * in the first place -- rgerhards
491 *
492 * 2005-07-18, well sometimes it pays to be a bit more verbose, even in C...
493 * Fixed a bug that lead to invalid detection of the data. The issue was that
494 * we had an if(++pszTS == 'x') inside of some of the consturcts below. However,
495 * there were also some elseifs (doing the same ++), which than obviously did not
496 * check the orginal character but the next one. Now removed the ++ and put it
497 * into the statements below. Was a really nasty bug... I didn't detect it before
498 * june, when it first manifested. This also lead to invalid parsing of the rest
499 * of the message, as the time stamp was not detected to be correct. - rgerhards
500 */
501 switch (*pszTS++) {
502 case 'j':
503 case 'J':
504 if (*pszTS == 'a' || *pszTS == 'A') {
505 ++pszTS;
506 if (*pszTS == 'n' || *pszTS == 'N') {
507 ++pszTS;
508 month = 1;
509 } else
510 ABORT_FINALIZE(RS_RET_INVLD_TIME);
511 } else if (*pszTS == 'u' || *pszTS == 'U') {
512 ++pszTS;
513 if (*pszTS == 'n' || *pszTS == 'N') {
514 ++pszTS;
515 month = 6;
516 } else if (*pszTS == 'l' || *pszTS == 'L') {
517 ++pszTS;
518 month = 7;
519 } else
520 ABORT_FINALIZE(RS_RET_INVLD_TIME);
521 } else
522 ABORT_FINALIZE(RS_RET_INVLD_TIME);
523 break;
524 case 'f':
525 case 'F':
526 if (*pszTS == 'e' || *pszTS == 'E') {
527 ++pszTS;
528 if (*pszTS == 'b' || *pszTS == 'B') {
529 ++pszTS;
530 month = 2;
531 } else
532 ABORT_FINALIZE(RS_RET_INVLD_TIME);
533 } else
534 ABORT_FINALIZE(RS_RET_INVLD_TIME);
535 break;
536 case 'm':
537 case 'M':
538 if (*pszTS == 'a' || *pszTS == 'A') {
539 ++pszTS;
540 if (*pszTS == 'r' || *pszTS == 'R') {
541 ++pszTS;
542 month = 3;
543 } else if (*pszTS == 'y' || *pszTS == 'Y') {
544 ++pszTS;
545 month = 5;
546 } else
547 ABORT_FINALIZE(RS_RET_INVLD_TIME);
548 } else
549 ABORT_FINALIZE(RS_RET_INVLD_TIME);
550 break;
551 case 'a':
552 case 'A':
553 if (*pszTS == 'p' || *pszTS == 'P') {
554 ++pszTS;
555 if (*pszTS == 'r' || *pszTS == 'R') {
556 ++pszTS;
557 month = 4;
558 } else
559 ABORT_FINALIZE(RS_RET_INVLD_TIME);
560 } else if (*pszTS == 'u' || *pszTS == 'U') {
561 ++pszTS;
562 if (*pszTS == 'g' || *pszTS == 'G') {
563 ++pszTS;
564 month = 8;
565 } else
566 ABORT_FINALIZE(RS_RET_INVLD_TIME);
567 } else
568 ABORT_FINALIZE(RS_RET_INVLD_TIME);
569 break;
570 case 's':
571 case 'S':
572 if (*pszTS == 'e' || *pszTS == 'E') {
573 ++pszTS;
574 if (*pszTS == 'p' || *pszTS == 'P') {
575 ++pszTS;
576 month = 9;
577 } else
578 ABORT_FINALIZE(RS_RET_INVLD_TIME);
579 } else
580 ABORT_FINALIZE(RS_RET_INVLD_TIME);
581 break;
582 case 'o':
583 case 'O':
584 if (*pszTS == 'c' || *pszTS == 'C') {
585 ++pszTS;
586 if (*pszTS == 't' || *pszTS == 'T') {
587 ++pszTS;
588 month = 10;
589 } else
590 ABORT_FINALIZE(RS_RET_INVLD_TIME);
591 } else
592 ABORT_FINALIZE(RS_RET_INVLD_TIME);
593 break;
594 case 'n':
595 case 'N':
596 if (*pszTS == 'o' || *pszTS == 'O') {
597 ++pszTS;
598 if (*pszTS == 'v' || *pszTS == 'V') {
599 ++pszTS;
600 month = 11;
601 } else
602 ABORT_FINALIZE(RS_RET_INVLD_TIME);
603 } else
604 ABORT_FINALIZE(RS_RET_INVLD_TIME);
605 break;
606 case 'd':
607 case 'D':
608 if (*pszTS == 'e' || *pszTS == 'E') {
609 ++pszTS;
610 if (*pszTS == 'c' || *pszTS == 'C') {
611 ++pszTS;
612 month = 12;
613 } else
614 ABORT_FINALIZE(RS_RET_INVLD_TIME);
615 } else
616 ABORT_FINALIZE(RS_RET_INVLD_TIME);
617 break;
618 default:
619 ABORT_FINALIZE(RS_RET_INVLD_TIME);
620 }
621
622 lenStr -= 3;
623
624 /* done month */
625
626 if (lenStr == 0 || *pszTS++ != ' ') ABORT_FINALIZE(RS_RET_INVLD_TIME);
627 --lenStr;
628
629 /* we accept a slightly malformed timestamp when receiving. This is
630 * we accept one-digit days
631 */
632 if (*pszTS == ' ') {
633 --lenStr;
634 ++pszTS;
635 }
636
637 day = srSLMGParseInt32(&pszTS, &lenStr);
638 if (day < 1 || day > 31) ABORT_FINALIZE(RS_RET_INVLD_TIME);
639
640 if (lenStr == 0 || *pszTS++ != ' ') ABORT_FINALIZE(RS_RET_INVLD_TIME);
641 --lenStr;
642
643 /* time part */
644 hour = srSLMGParseInt32(&pszTS, &lenStr);
645 if (year == 0 && hour > 1970 && hour < 2100) {
646 /* if so, we assume this actually is a year. This is a format found
647 * e.g. in Cisco devices.
648 * (if you read this 2100+ trying to fix a bug, congratulate me
649 * to how long the code survived - me no longer ;)) -- rgerhards, 2008-11-18
650 */
651 year = hour;
652
653 /* re-query the hour, this time it must be valid */
654 if (lenStr == 0 || *pszTS++ != ' ') ABORT_FINALIZE(RS_RET_INVLD_TIME);
655 --lenStr;
656 hour = srSLMGParseInt32(&pszTS, &lenStr);
657 }
658
659 if (hour < 0 || hour > 23) ABORT_FINALIZE(RS_RET_INVLD_TIME);
660
661 if (lenStr == 0 || *pszTS++ != ':') ABORT_FINALIZE(RS_RET_INVLD_TIME);
662 --lenStr;
663 minute = srSLMGParseInt32(&pszTS, &lenStr);
664 if (minute < 0 || minute > 59) ABORT_FINALIZE(RS_RET_INVLD_TIME);
665
666 if (lenStr == 0 || *pszTS++ != ':') ABORT_FINALIZE(RS_RET_INVLD_TIME);
667 --lenStr;
668 second = srSLMGParseInt32(&pszTS, &lenStr);
669 if (second < 0 || second > 60) ABORT_FINALIZE(RS_RET_INVLD_TIME);
670
671 /* as an extension e.g. found in CISCO IOS, we support sub-second resultion.
672 * It's presence is indicated by a dot immediately following the second.
673 */
674 if (lenStr > 0 && *pszTS == '.') {
675 --lenStr;
676 uchar *pszStart = ++pszTS;
677 secfrac = srSLMGParseInt32(&pszTS, &lenStr);
678 secfracPrecision = (int)(pszTS - pszStart);
679 } else {
680 secfracPrecision = 0;
681 secfrac = 0;
682 }
683
684 /* try to parse the TZSTRING if we are instructed to do so */
685 if (bParseTZ && lenStr > 2 && *pszTS == ' ') {
686 int i;
687 for (++pszTS, --lenStr, i = 0; lenStr > 0 && i < (int)sizeof(tzstring) - 1 && *pszTS != ':' && *pszTS != ' ';
688 --lenStr)
689 tzstring[i++] = *pszTS++;
690 if (i > 0) {
691 /* found TZ, apply it */
692 tzinfo_t *tzinfo;
693 tzstring[i] = '\0';
694 if ((tzinfo = glblFindTimezone(runConf, (char *)tzstring)) == NULL) {
695 DBGPRINTF("ParseTIMESTAMP3164: invalid TZ string '%s' -- ignored\n", tzstring);
696 } else {
697 OffsetMode = tzinfo->offsMode;
698 OffsetHour = tzinfo->offsHour;
699 OffsetMinute = tzinfo->offsMin;
700 }
701 }
702 }
703 if (bDetectYearAfterTime && year == 0 && lenStr > 5 && *pszTS == ' ') {
704 int j;
705 int y = 0;
706 for (j = 1; j < 5; ++j) {
707 if (pszTS[j] < '0' || pszTS[j] > '9') break;
708 y = 10 * y + pszTS[j] - '0';
709 }
710 if (lenStr > 6 && pszTS[5] != ' ') y = 0; /* no year! */
711 if (2000 <= y && y < 2100) {
712 year = y;
713 pszTS += 5; /* we need to preserve the SP, checked below */
714 lenStr -= 5;
715 }
716 }
717
718 /* we provide support for an extra ":" after the date. While this is an
719 * invalid format, it occurs frequently enough (e.g. with Cisco devices)
720 * to permit it as a valid case. -- rgerhards, 2008-09-12
721 */
722 if (lenStr > 0 && *pszTS == ':') {
723 ++pszTS; /* just skip past it */
724 --lenStr;
725 }
726 if (lenStr > 0) {
727 if (*pszTS != ' ') /* if it is not a space, it can not be a "good" time - 2010-02-22 rgerhards */
728 ABORT_FINALIZE(RS_RET_INVLD_TIME);
729 ++pszTS; /* just skip past it */
730 --lenStr;
731 }
732
733 /* we had success, so update parse pointer and caller-provided timestamp
734 * fields we do not have are not updated in the caller's timestamp. This
735 * is the reason why the caller must pass in a correct timestamp.
736 */
737 *ppszTS = pszTS; /* provide updated parse position back to caller */
738 pTime->timeType = 1;
739 pTime->month = month;
740 if (year > 0) pTime->year = year; /* persist year if detected */
741 pTime->day = day;
742 pTime->hour = hour;
743 pTime->minute = minute;
744 pTime->second = second;
745 pTime->secfrac = secfrac;
746 pTime->secfracPrecision = secfracPrecision;
747 if (OffsetMode != '\0') { /* need to update TZ info? */
748 pTime->OffsetMode = OffsetMode;
749 pTime->OffsetHour = OffsetHour;
750 pTime->OffsetMinute = OffsetMinute;
751 }
752 *pLenStr = lenStr;
753
754 finalize_it:
755 RETiRet;
756 }
757
758 void applyDfltTZ(struct syslogTime *pTime, char *tz) {
759 pTime->OffsetMode = tz[0];
760 pTime->OffsetHour = (tz[1] - '0') * 10 + (tz[2] - '0');
761 pTime->OffsetMinute = (tz[4] - '0') * 10 + (tz[5] - '0');
762 }
763
764 /*******************************************************************
765 * END CODE-LIBLOGGING *
766 *******************************************************************/
767
768 /**
769 * Format a syslogTimestamp into format required by MySQL.
770 * We are using the 14 digits format. For example 20041111122600
771 * is interpreted as '2004-11-11 12:26:00'.
772 * The caller must provide the timestamp as well as a character
773 * buffer that will receive the resulting string. The function
774 * returns the size of the timestamp written in bytes (without
775 * the string terminator). If 0 is returend, an error occurred.
776 */
777 static int formatTimestampToMySQL(struct syslogTime *ts, char *pBuf) {
778 /* currently we do not consider localtime/utc. This may later be
779 * added. If so, I recommend using a property replacer option
780 * and/or a global configuration option. However, we should wait
781 * on user requests for this feature before doing anything.
782 * rgerhards, 2007-06-26
783 */
784 assert(ts != NULL);
785 assert(pBuf != NULL);
786
787 pBuf[0] = (ts->year / 1000) % 10 + '0';
788 pBuf[1] = (ts->year / 100) % 10 + '0';
789 pBuf[2] = (ts->year / 10) % 10 + '0';
790 pBuf[3] = ts->year % 10 + '0';
791 pBuf[4] = (ts->month / 10) % 10 + '0';
792 pBuf[5] = ts->month % 10 + '0';
793 pBuf[6] = (ts->day / 10) % 10 + '0';
794 pBuf[7] = ts->day % 10 + '0';
795 pBuf[8] = (ts->hour / 10) % 10 + '0';
796 pBuf[9] = ts->hour % 10 + '0';
797 pBuf[10] = (ts->minute / 10) % 10 + '0';
798 pBuf[11] = ts->minute % 10 + '0';
799 pBuf[12] = (ts->second / 10) % 10 + '0';
800 pBuf[13] = ts->second % 10 + '0';
801 pBuf[14] = '\0';
802 return 15;
803 }
804
805 static int formatTimestampToPgSQL(struct syslogTime *ts, char *pBuf) {
806 /* see note in formatTimestampToMySQL, applies here as well */
807 assert(ts != NULL);
808 assert(pBuf != NULL);
809
810 pBuf[0] = (ts->year / 1000) % 10 + '0';
811 pBuf[1] = (ts->year / 100) % 10 + '0';
812 pBuf[2] = (ts->year / 10) % 10 + '0';
813 pBuf[3] = ts->year % 10 + '0';
814 pBuf[4] = '-';
815 pBuf[5] = (ts->month / 10) % 10 + '0';
816 pBuf[6] = ts->month % 10 + '0';
817 pBuf[7] = '-';
818 pBuf[8] = (ts->day / 10) % 10 + '0';
819 pBuf[9] = ts->day % 10 + '0';
820 pBuf[10] = ' ';
821 pBuf[11] = (ts->hour / 10) % 10 + '0';
822 pBuf[12] = ts->hour % 10 + '0';
823 pBuf[13] = ':';
824 pBuf[14] = (ts->minute / 10) % 10 + '0';
825 pBuf[15] = ts->minute % 10 + '0';
826 pBuf[16] = ':';
827 pBuf[17] = (ts->second / 10) % 10 + '0';
828 pBuf[18] = ts->second % 10 + '0';
829 pBuf[19] = '\0';
830 return 19;
831 }
832
833
834 /**
835 * Format a syslogTimestamp to just the fractional seconds.
836 * The caller must provide the timestamp as well as a character
837 * buffer that will receive the resulting string. The function
838 * returns the size of the timestamp written in bytes (without
839 * the string terminator). If 0 is returend, an error occurred.
840 * The buffer must be at least 7 bytes large.
841 * rgerhards, 2008-06-06
842 */
843 static int formatTimestampSecFrac(struct syslogTime *ts, char *pBuf) {
844 int iBuf;
845 int power;
846 int secfrac;
847 short digit;
848
849 assert(ts != NULL);
850 assert(pBuf != NULL);
851
852 iBuf = 0;
853 if (ts->secfracPrecision > 0) {
854 power = tenPowers[(ts->secfracPrecision - 1) % 6];
855 secfrac = ts->secfrac;
856 while (power > 0) {
857 digit = secfrac / power;
858 secfrac -= digit * power;
859 power /= 10;
860 pBuf[iBuf++] = digit + '0';
861 }
862 } else {
863 pBuf[iBuf++] = '0';
864 }
865 pBuf[iBuf] = '\0';
866
867 return iBuf;
868 }
869
870
871 /**
872 * Format a syslogTimestamp to a RFC3339 timestamp string (as
873 * specified in syslog-protocol).
874 * The caller must provide the timestamp as well as a character
875 * buffer that will receive the resulting string. The function
876 * returns the size of the timestamp written in bytes (without
877 * the string terminator). If 0 is returend, an error occurred.
878 */
879 static int formatTimestamp3339(struct syslogTime *ts, char *pBuf) {
880 int iBuf;
881 int power;
882 int secfrac;
883 short digit;
884
885 assert(ts != NULL);
886 assert(pBuf != NULL);
887
888 /* start with fixed parts */
889 /* year yyyy */
890 pBuf[0] = (ts->year / 1000) % 10 + '0';
891 pBuf[1] = (ts->year / 100) % 10 + '0';
892 pBuf[2] = (ts->year / 10) % 10 + '0';
893 pBuf[3] = ts->year % 10 + '0';
894 pBuf[4] = '-';
895 /* month */
896 pBuf[5] = (ts->month / 10) % 10 + '0';
897 pBuf[6] = ts->month % 10 + '0';
898 pBuf[7] = '-';
899 /* day */
900 pBuf[8] = (ts->day / 10) % 10 + '0';
901 pBuf[9] = ts->day % 10 + '0';
902 pBuf[10] = 'T';
903 /* hour */
904 pBuf[11] = (ts->hour / 10) % 10 + '0';
905 pBuf[12] = ts->hour % 10 + '0';
906 pBuf[13] = ':';
907 /* minute */
908 pBuf[14] = (ts->minute / 10) % 10 + '0';
909 pBuf[15] = ts->minute % 10 + '0';
910 pBuf[16] = ':';
911 /* second */
912 pBuf[17] = (ts->second / 10) % 10 + '0';
913 pBuf[18] = ts->second % 10 + '0';
914
915 iBuf = 19; /* points to next free entry, now it becomes dynamic! */
916
917 if (ts->secfracPrecision > 0) {
918 pBuf[iBuf++] = '.';
919 power = tenPowers[(ts->secfracPrecision - 1) % 6];
920 secfrac = ts->secfrac;
921 while (power > 0) {
922 digit = secfrac / power;
923 secfrac -= digit * power;
924 power /= 10;
925 pBuf[iBuf++] = digit + '0';
926 }
927 }
928
929 if (ts->OffsetMode == 'Z') {
930 pBuf[iBuf++] = 'Z';
931 } else {
932 pBuf[iBuf++] = ts->OffsetMode;
933 pBuf[iBuf++] = (ts->OffsetHour / 10) % 10 + '0';
934 pBuf[iBuf++] = ts->OffsetHour % 10 + '0';
935 pBuf[iBuf++] = ':';
936 pBuf[iBuf++] = (ts->OffsetMinute / 10) % 10 + '0';
937 pBuf[iBuf++] = ts->OffsetMinute % 10 + '0';
938 }
939
940 pBuf[iBuf] = '\0';
941
942 return iBuf;
943 }
944
945 /**
946 * Format a syslogTimestamp to a RFC3164 timestamp sring.
947 * The caller must provide the timestamp as well as a character
948 * buffer that will receive the resulting string. The function
949 * returns the size of the timestamp written in bytes (without
950 * the string termnator). If 0 is returend, an error occurred.
951 * rgerhards, 2010-03-05: Added support to for buggy 3164 dates,
952 * where a zero-digit is written instead of a space for the first
953 * day character if day < 10. syslog-ng seems to do that, and some
954 * parsing scripts (in migration cases) rely on that.
955 */
956 static int formatTimestamp3164(struct syslogTime *ts, char *pBuf, int bBuggyDay) {
957 int iDay;
958 assert(ts != NULL);
959 assert(pBuf != NULL);
960
961 pBuf[0] = monthNames[(ts->month - 1) % 12][0];
962 pBuf[1] = monthNames[(ts->month - 1) % 12][1];
963 pBuf[2] = monthNames[(ts->month - 1) % 12][2];
964 pBuf[3] = ' ';
965 iDay = (ts->day / 10) % 10; /* we need to write a space if the first digit is 0 */
966 pBuf[4] = (bBuggyDay || iDay > 0) ? iDay + '0' : ' ';
967 pBuf[5] = ts->day % 10 + '0';
968 pBuf[6] = ' ';
969 pBuf[7] = (ts->hour / 10) % 10 + '0';
970 pBuf[8] = ts->hour % 10 + '0';
971 pBuf[9] = ':';
972 pBuf[10] = (ts->minute / 10) % 10 + '0';
973 pBuf[11] = ts->minute % 10 + '0';
974 pBuf[12] = ':';
975 pBuf[13] = (ts->second / 10) % 10 + '0';
976 pBuf[14] = ts->second % 10 + '0';
977 pBuf[15] = '\0';
978 return 16; /* traditional: number of bytes written */
979 }
980
981
982 /**
983 * convert syslog timestamp to time_t
984 * Note: it would be better to use something similar to mktime() here.
985 * Unfortunately, mktime() semantics are problematic: first of all, it
986 * works on local time, on the machine's time zone. In syslog, we have
987 * to deal with multiple time zones at once, so we cannot plainly rely
988 * on the local zone, and so we cannot rely on mktime(). One solution would
989 * be to refactor all time-related functions so that they are all guarded
990 * by a mutex to ensure TZ consistency (which would also enable us to
991 * change the TZ at will for specific function calls). But that would
992 * potentially mean a lot of overhead.
993 * Also, mktime() has some side effects, at least setting of tzname. With
994 * a refactoring as described above that should probably not be a problem,
995 * but would also need more work. For some more thoughts on this topic,
996 * have a look here:
997 * http://stackoverflow.com/questions/18355101/is-standard-c-mktime-thread-safe-on-linux
998 * In conclusion, we keep our own code for generating the unix timestamp.
999 * rgerhards, 2016-03-02
1000 */
1001 static time_t syslogTime2time_t(const struct syslogTime *ts) {
1002 long MonthInDays, NumberOfYears, NumberOfDays;
1003 int utcOffset;
1004 time_t TimeInUnixFormat;
1005
1006 if (ts->year < 1970 || ts->year > 2100) {
1007 TimeInUnixFormat = 0;
1008 LogError(0, RS_RET_ERR,
1009 "syslogTime2time_t: invalid year %d "
1010 "in timestamp - returning 1970-01-01 instead",
1011 ts->year);
1012 goto done;
1013 }
1014
1015 /* Counting how many Days have passed since the 01.01 of the
1016 * selected Year (Month level), according to the selected Month*/
1017
1018 switch (ts->month) {
1019 case 1:
1020 MonthInDays = 0; // until 01 of January
1021 break;
1022 case 2:
1023 MonthInDays = 31; // until 01 of February - leap year handling down below!
1024 break;
1025 case 3:
1026 MonthInDays = 59; // until 01 of March
1027 break;
1028 case 4:
1029 MonthInDays = 90; // until 01 of April
1030 break;
1031 case 5:
1032 MonthInDays = 120; // until 01 of Mai
1033 break;
1034 case 6:
1035 MonthInDays = 151; // until 01 of June
1036 break;
1037 case 7:
1038 MonthInDays = 181; // until 01 of July
1039 break;
1040 case 8:
1041 MonthInDays = 212; // until 01 of August
1042 break;
1043 case 9:
1044 MonthInDays = 243; // until 01 of September
1045 break;
1046 case 10:
1047 MonthInDays = 273; // until 01 of Oktober
1048 break;
1049 case 11:
1050 MonthInDays = 304; // until 01 of November
1051 break;
1052 case 12:
1053 MonthInDays = 334; // until 01 of December
1054 break;
1055 default: /* this cannot happen (and would be a program error)
1056 * but we need the code to keep the compiler silent.
1057 */
1058 MonthInDays = 0; /* any value fits ;) */
1059 break;
1060 }
1061 /* adjust for leap years */
1062 if ((ts->year % 100 != 0 && ts->year % 4 == 0) || (ts->year == 2000)) {
1063 if (ts->month > 2) MonthInDays++;
1064 }
1065
1066
1067 /* 1) Counting how many Years have passed since 1970
1068 2) Counting how many Days have passed since the 01.01 of the selected Year
1069 (Day level) according to the Selected Month and Day. Last day doesn't count,
1070 it should be until last day
1071 3) Calculating this period (NumberOfDays) in seconds*/
1072
1073 NumberOfYears = ts->year - yearInSec_startYear - 1;
1074 NumberOfDays = MonthInDays + ts->day - 1;
1075 TimeInUnixFormat = (time_t)(yearInSecs[NumberOfYears] + 1) + NumberOfDays * 86400;
1076
1077 /*Add Hours, minutes and seconds */
1078 TimeInUnixFormat += ts->hour * 60 * 60;
1079 TimeInUnixFormat += ts->minute * 60;
1080 TimeInUnixFormat += ts->second;
1081 /* do UTC offset */
1082 utcOffset = ts->OffsetHour * 3600 + ts->OffsetMinute * 60;
1083 if (ts->OffsetMode == '+') utcOffset *= -1; /* if timestamp is ahead, we need to "go back" to UTC */
1084 TimeInUnixFormat += utcOffset;
1085 done:
1086 return TimeInUnixFormat;
1087 }
1088
1089
1090 /**
1091 * format a timestamp as a UNIX timestamp; subsecond resolution is
1092 * discarded.
1093 * Note that this code can use some refactoring. I decided to use it
1094 * because mktime() requires an upfront TZ update as it works on local
1095 * time. In any case, it is worth reconsidering to move to mktime() or
1096 * some other method.
1097 * Important: pBuf must point to a buffer of at least 11 bytes.
1098 * rgerhards, 2012-03-29
1099 */
1100 static int formatTimestampUnix(struct syslogTime *ts, char *pBuf) {
1101 snprintf(pBuf, 11, "%u", (unsigned)syslogTime2time_t(ts));
1102 return 11;
1103 }
1104
1105 /* 0 - Sunday, 1, Monday, ...
1106 * Note that we cannot use strftime() and helpers as they rely on the TZ
1107 * variable (again, arghhhh). So we need to do it ourselves...
1108 * Note: in the year 2100, this algorithm does not work correctly (due to
1109 * leap time rules. To fix it then (*IF* this code really still exists then),
1110 * just use 2100 as new anchor year and adapt the initial day number.
1111 */
1112 int getWeekdayNbr(struct syslogTime *ts) {
1113 int wday;
1114 int g, f;
1115
1116 g = ts->year;
1117 if (ts->month < 3) {
1118 g--;
1119 f = ts->month + 13;
1120 } else {
1121 f = ts->month + 1;
1122 }
1123 wday = ((36525 * g) / 100) + ((306 * f) / 10) + ts->day - 621049;
1124 wday %= 7;
1125 return wday;
1126 }
1127
1128 /* getOrdinal - 1-366 day of the year
1129 * I've given little thought to leap seconds here.
1130 */
1131 int getOrdinal(struct syslogTime *ts) {
1132 int yday;
1133 time_t thistime;
1134 time_t previousyears;
1135 int utcOffset;
1136 time_t seconds_into_year;
1137
1138 if (ts->year < 1970 || ts->year > 2100) {
1139 yday = 0;
1140 LogError(0, RS_RET_ERR,
1141 "getOrdinal: invalid year %d "
1142 "in timestamp - returning 1970-01-01 instead",
1143 ts->year);
1144 goto done;
1145 }
1146
1147 thistime = syslogTime2time_t(ts);
1148
1149 previousyears = (time_t)yearInSecs[ts->year - yearInSec_startYear - 1];
1150
1151 /* adjust previous years to match UTC offset */
1152 utcOffset = ts->OffsetHour * 3600 + ts->OffsetMinute * 60;
1153 if (ts->OffsetMode == '+') utcOffset += -1; /* if timestamp is ahead, we need to "go back" to UTC */
1154 previousyears += utcOffset;
1155
1156 /* subtract seconds from previous years */
1157 seconds_into_year = thistime - previousyears;
1158
1159 /* divide by seconds in a day and truncate to int */
1160 yday = seconds_into_year / 86400;
1161 done:
1162 return yday;
1163 }
1164
1165 /* getWeek - 1-52 week of the year */
1166 int getWeek(struct syslogTime *ts) {
1167 int weekNum;
1168 struct syslogTime yt;
1169 int curDow;
1170 int jan1Dow;
1171 int curYearDay;
1172
1173 /* initialize a timestamp for january 1st of the current year */
1174 yt.year = ts->year;
1175 yt.month = 1;
1176 yt.day = 1;
1177 yt.hour = 0;
1178 yt.minute = 0;
1179 yt.second = 0;
1180 yt.secfracPrecision = 0;
1181 yt.secfrac = 0;
1182 yt.OffsetMinute = ts->OffsetMinute;
1183 yt.OffsetHour = ts->OffsetHour;
1184 yt.OffsetMode = ts->OffsetMode;
1185 yt.timeType = TIME_TYPE_RFC3164; /* low-res time */
1186
1187 /* get current day in year, current day of week
1188 * and the day of week of 1/1 */
1189 curYearDay = getOrdinal(ts);
1190 curDow = getWeekdayNbr(ts);
1191 jan1Dow = getWeekdayNbr(&yt);
1192
1193 /* calculate week of year for given date by pinning 1/1 as start
1194 * of year, then going back and adjusting for the actual week day. */
1195 weekNum = ((curYearDay + 6) / 7);
1196 if (curDow < jan1Dow) {
1197 ++weekNum;
1198 }
1199 return weekNum;
1200 }
1201
1202 /* getISOWeek - 1-53 week of the year */
1203 int getISOWeek(struct syslogTime *ts, int *year) {
1204 int weekNum;
1205 int curDow;
1206 int curYearDay;
1207
1208 /* get current day in year, current day of week
1209 * and the day of week of 1/1 */
1210 curYearDay = getOrdinal(ts);
1211 curDow = getWeekdayNbr(ts);
1212
1213 /* map from 0 - Sunday, 1, Monday to 1, Monday, 7 - Sunday */
1214 if (curDow == 0) {
1215 curDow = 7;
1216 }
1217 /* make ordinal in range 1-366 */
1218 curYearDay++;
1219
1220 weekNum = (10 + curYearDay - curDow) / 7;
1221 *year = ts->year;
1222 if (weekNum == 0) {
1223 /* this is actually W52 or W53 of previous year */
1224 weekNum = weeksInYear[ts->year - 1 - 1969];
1225 *year = ts->year - 1;
1226 } else if (weekNum > weeksInYear[ts->year - 1969]) {
1227 /* this is actually W01 of next year */
1228 weekNum = 1;
1229 *year = ts->year + 1;
1230 }
1231
1232 return weekNum;
1233 }
1234
1235 void timeConvertToUTC(const struct syslogTime *const __restrict__ local, struct syslogTime *const __restrict__ utc) {
1236 struct timeval tp;
1237 tp.tv_sec = syslogTime2time_t(local);
1238 tp.tv_usec = local->secfrac;
1239 timeval2syslogTime(&tp, utc, 1);
1240 }
1241
1242 /**
1243 * Format a UNIX timestamp.
1244 */
1245 static int formatUnixTimeFromTime_t(time_t unixtime,
1246 const char *format,
1247 char *pBuf,
1248 __attribute__((unused)) uint pBufMax) {
1249 struct tm lt;
1250
1251 assert(format != NULL);
1252 assert(pBuf != NULL);
1253
1254 // Convert to struct tm
1255 if (gmtime_r(&unixtime, &lt) == NULL) {
1256 DBGPRINTF("Unexpected error calling gmtime_r().\n");
1257 return -1;
1258 }
1259
1260 // Do our conversions
1261 if (strcmp(format, "date-rfc3164") == 0) {
1262 assert(pBufMax >= 16);
1263
1264 // Unlikely to run into this situation, but you never know...
1265 if (lt.tm_mon < 0 || lt.tm_mon > 11) {
1266 DBGPRINTF("lt.tm_mon is out of range. Value: %d\n", lt.tm_mon);
1267 return -1;
1268 }
1269
1270 // MMM dd HH:mm:ss
1271 snprintf(pBuf, pBufMax, "%s %2d %.2d:%.2d:%.2d", monthNames[lt.tm_mon], lt.tm_mday, lt.tm_hour, lt.tm_min,
1272 lt.tm_sec);
1273 } else if (strcmp(format, "date-rfc3339") == 0) {
1274 assert(pBufMax >= 26);
1275
1276 // YYYY-MM-DDTHH:mm:ss+00:00
1277 snprintf(pBuf, pBufMax, "%d-%.2d-%.2dT%.2d:%.2d:%.2dZ", lt.tm_year + 1900, lt.tm_mon + 1, lt.tm_mday,
1278 lt.tm_hour, lt.tm_min, lt.tm_sec);
1279 }
1280
1281 return strlen(pBuf);
1282 }
1283
1284 /* queryInterface function
1285 * rgerhards, 2008-03-05
1286 */
1287 BEGINobjQueryInterface(datetime)
1288 CODESTARTobjQueryInterface(datetime);
1289 if (pIf->ifVersion != datetimeCURR_IF_VERSION) { /* check for current version, increment on each change */
1290 ABORT_FINALIZE(RS_RET_INTERFACE_NOT_SUPPORTED);
1291 }
1292
1293 /* ok, we have the right interface, so let's fill it
1294 * Please note that we may also do some backwards-compatibility
1295 * work here (if we can support an older interface version - that,
1296 * of course, also affects the "if" above).
1297 */
1298 pIf->getCurrTime = getCurrTime;
1299 pIf->GetTime = getTime;
1300 pIf->timeval2syslogTime = timeval2syslogTime;
1301 pIf->ParseTIMESTAMP3339 = ParseTIMESTAMP3339;
1302 pIf->ParseTIMESTAMP3164 = ParseTIMESTAMP3164;
1303 pIf->formatTimestampToMySQL = formatTimestampToMySQL;
1304 pIf->formatTimestampToPgSQL = formatTimestampToPgSQL;
1305 pIf->formatTimestampSecFrac = formatTimestampSecFrac;
1306 pIf->formatTimestamp3339 = formatTimestamp3339;
1307 pIf->formatTimestamp3164 = formatTimestamp3164;
1308 pIf->formatTimestampUnix = formatTimestampUnix;
1309 pIf->syslogTime2time_t = syslogTime2time_t;
1310 pIf->formatUnixTimeFromTime_t = formatUnixTimeFromTime_t;
1311 finalize_it:
1312 ENDobjQueryInterface(datetime)
1313
1314
1315 /* Initialize the datetime class. Must be called as the very first method
1316 * before anything else is called inside this class.
1317 * rgerhards, 2008-02-19
1318 */
1319 BEGINAbstractObjClassInit(datetime, 1, OBJ_IS_CORE_MODULE) /* class, version */
1320 /* request objects we use */
1321 ENDObjClassInit(datetime)
1322
1323 /* vi:set ai:
1324 */