2 * ------+---------+---------+---------+---------+---------+---------+---------*
3 * Initial version of parse8601 was originally added to newsyslog.c in
4 * FreeBSD on Jan 22, 1999 by Garrett Wollman <wollman@FreeBSD.org>.
5 * Initial version of parseDWM was originally added to newsyslog.c in
6 * FreeBSD on Apr 4, 2000 by Hellmuth Michaelis <hm@FreeBSD.org>.
8 * Copyright (c) 2003 - Garance Alistair Drosehn <gad@FreeBSD.org>.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * The views and conclusions contained in the software and documentation
33 * are those of the authors and should not be interpreted as representing
34 * official policies, either expressed or implied, of the FreeBSD Project.
36 * ------+---------+---------+---------+---------+---------+---------+---------*
37 * This is intended to be a set of general-purpose routines to process times.
38 * Right now it probably still has a number of assumptions in it, such that
39 * it works fine for newsyslog but might not work for other uses.
40 * ------+---------+---------+---------+---------+---------+---------+---------*
43 #include <sys/cdefs.h>
53 #define SECS_PER_HOUR 3600
56 * Bit-values which indicate which components of time were specified
57 * by the string given to parse8601 or parseDWM. These are needed to
58 * calculate what time-in-the-future will match that string.
60 #define TSPEC_YEAR 0x0001
61 #define TSPEC_MONTHOFYEAR 0x0002
62 #define TSPEC_LDAYOFMONTH 0x0004
63 #define TSPEC_DAYOFMONTH 0x0008
64 #define TSPEC_DAYOFWEEK 0x0010
65 #define TSPEC_HOUROFDAY 0x0020
67 #define TNYET_ADJ4DST -10 /* DST has "not yet" been adjusted */
70 time_t basesecs; /* Base point for relative times */
71 time_t tsecs; /* Time in seconds */
72 struct tm basetm; /* Base Time expanded into fields */
73 struct tm tm; /* Time expanded into fields */
74 int did_adj4dst; /* Track calls to ptime_adjust4dst */
75 int parseopts; /* Options given for parsing */
76 int tmspec; /* Indicates which time fields had
77 * been specified by the user */
80 static int days_pmonth(int month, int year);
81 static int parse8601(struct ptime_data *ptime, const char *str);
82 static int parseDWM(struct ptime_data *ptime, const char *str);
85 * Simple routine to calculate the number of days in a given month.
88 days_pmonth(int month, int year)
90 static const int mtab[] = {31, 28, 31, 30, 31, 30, 31, 31,
98 * We are usually called with a 'tm-year' value
99 * (ie, the value = the number of years past 1900).
105 * This is a leap year, as long as it is not a
106 * multiple of 100, or if it is a multiple of
110 ndays++; /* not multiple of 100 */
111 else if (year % 400 == 0)
112 ndays++; /* is multiple of 100 and 400 */
119 * Parse a limited subset of ISO 8601. The specific format is as follows:
121 * [CC[YY[MM[DD]]]][THH[MM[SS]]] (where `T' is the literal letter)
123 * We don't accept a timezone specification; missing fields (including timezone)
124 * are defaulted to the current date but time zero.
127 parse8601(struct ptime_data *ptime, const char *s)
133 l = strtol(s, &t, 10);
134 if (l < 0 || l >= INT_MAX || (*t != '\0' && *t != 'T'))
138 * Now t points either to the end of the string (if no time was
139 * provided) or to the letter `T' which separates date and time in
140 * ISO 8601. The pointer arithmetic is the same for either case.
143 ptime->tmspec = TSPEC_HOUROFDAY;
146 tm.tm_year = ((l / 1000000) - 19) * 100;
150 ptime->tmspec |= TSPEC_YEAR;
151 tm.tm_year -= tm.tm_year % 100;
152 tm.tm_year += l / 10000;
156 ptime->tmspec |= TSPEC_MONTHOFYEAR;
157 tm.tm_mon = (l / 100) - 1;
161 ptime->tmspec |= TSPEC_DAYOFMONTH;
171 if (tm.tm_year < 70 || tm.tm_mon < 0 || tm.tm_mon > 12
172 || tm.tm_mday < 1 || tm.tm_mday > 31)
177 l = strtol(s, &t, 10);
178 if (l < 0 || l >= INT_MAX || (*t != '\0' && !isspace(*t)))
191 ptime->tmspec |= TSPEC_HOUROFDAY;
201 if (tm.tm_sec < 0 || tm.tm_sec > 60 || tm.tm_min < 0
202 || tm.tm_min > 59 || tm.tm_hour < 0 || tm.tm_hour > 23)
211 * Parse a cyclic time specification, the format is as follows:
213 * [Dhh] or [Wd[Dhh]] or [Mdd[Dhh]]
215 * to rotate a logfile cyclic at
217 * - every day (D) within a specific hour (hh) (hh = 0...23)
218 * - once a week (W) at a specific day (d) OR (d = 0..6, 0 = Sunday)
219 * - once a month (M) at a specific day (d) (d = 1..31,l|L)
221 * We don't accept a timezone specification; missing fields
222 * are defaulted to the current date but time zero.
225 parseDWM(struct ptime_data *ptime, const char *s)
227 int daysmon, Dseen, WMseen;
233 /* Save away the number of days in this month */
235 daysmon = days_pmonth(tm.tm_mon, tm.tm_year);
238 ptime->tmspec = TSPEC_HOUROFDAY;
246 ptime->tmspec |= TSPEC_HOUROFDAY;
248 l = strtol(s, &tmp, 10);
259 ptime->tmspec |= TSPEC_DAYOFWEEK;
261 l = strtol(s, &tmp, 10);
265 if (l != tm.tm_wday) {
268 if (l < tm.tm_wday) {
269 save = 6 - tm.tm_wday;
272 save = l - tm.tm_wday;
277 if (tm.tm_mday > daysmon) {
279 tm.tm_mday = tm.tm_mday - daysmon;
280 if (tm.tm_mon >= 12) {
292 ptime->tmspec |= TSPEC_DAYOFMONTH;
294 if (tolower(*s) == 'l') {
295 /* User wants the last day of the month. */
296 ptime->tmspec |= TSPEC_LDAYOFMONTH;
297 tm.tm_mday = daysmon;
300 l = strtol(s, &tmp, 10);
318 else if (*endval == '\0' || isspace(*endval))
329 * Initialize a new ptime-related data area.
332 ptime_init(const struct ptime_data *optsrc)
334 struct ptime_data *newdata;
336 newdata = malloc(sizeof(struct ptime_data));
337 if (optsrc != NULL) {
338 memcpy(newdata, optsrc, sizeof(struct ptime_data));
340 memset(newdata, '\0', sizeof(struct ptime_data));
341 newdata->did_adj4dst = TNYET_ADJ4DST;
348 * Adjust a given time if that time is in a different timezone than
352 ptime_adjust4dst(struct ptime_data *ptime, const struct ptime_data *dstsrc)
354 struct ptime_data adjtime;
360 * Changes are not made to the given time until after all
361 * of the calculations have been successful.
365 /* Check to see if this adjustment was already made */
366 if ((adjtime.did_adj4dst != TNYET_ADJ4DST) &&
367 (adjtime.did_adj4dst == dstsrc->tm.tm_isdst))
368 return (0); /* yes, so don't make it twice */
370 /* See if daylight-saving has changed between the two times. */
371 if (dstsrc->tm.tm_isdst != adjtime.tm.tm_isdst) {
372 if (adjtime.tm.tm_isdst == 1)
373 adjtime.tsecs -= SECS_PER_HOUR;
374 else if (adjtime.tm.tm_isdst == 0)
375 adjtime.tsecs += SECS_PER_HOUR;
376 adjtime.tm = *(localtime(&adjtime.tsecs));
377 /* Remember that this adjustment has been made */
378 adjtime.did_adj4dst = dstsrc->tm.tm_isdst;
380 * XXX - Should probably check to see if changing the
381 * hour also changed the value of is_dst. What
382 * should we do in that case?
391 ptime_relparse(struct ptime_data *ptime, int parseopts, time_t basetime,
397 ptime->parseopts = parseopts;
398 ptime->basesecs = basetime;
399 ptime->basetm = *(localtime(&ptime->basesecs));
400 ptime->tm = ptime->basetm;
401 ptime->tm.tm_hour = ptime->tm.tm_min = ptime->tm.tm_sec = 0;
404 * Call a routine which sets ptime.tm and ptime.tspecs based
405 * on the given string and parsing-options. Note that the
406 * routine should not call mktime to set ptime.tsecs.
408 if (parseopts & PTM_PARSE_DWM)
409 pres = parseDWM(ptime, str);
411 pres = parse8601(ptime, str);
413 ptime->tsecs = (time_t)pres;
418 * Before calling mktime, check to see if we ended up with a
419 * "day-of-month" that does not exist in the selected month.
420 * If we did call mktime with that info, then mktime will
421 * make it look like the user specifically requested a day
422 * in the following month (eg: Feb 31 turns into Mar 3rd).
424 dpm = days_pmonth(ptime->tm.tm_mon, ptime->tm.tm_year);
425 if ((parseopts & PTM_PARSE_MATCHDOM) &&
426 (ptime->tmspec & TSPEC_DAYOFMONTH) &&
427 (ptime->tm.tm_mday> dpm)) {
429 * ptime_nxtime() will want a ptime->tsecs value,
430 * but we need to avoid mktime resetting all the
433 if (verbose && dbg_at_times > 1)
435 "\t-- dom fixed: %4d/%02d/%02d %02d:%02d (%02d)",
436 ptime->tm.tm_year, ptime->tm.tm_mon,
437 ptime->tm.tm_mday, ptime->tm.tm_hour,
438 ptime->tm.tm_min, dpm);
440 ptime->tsecs = mktime(&temp_tm);
441 if (ptime->tsecs > (time_t)-1)
442 ptimeset_nxtime(ptime);
443 if (verbose && dbg_at_times > 1)
445 " to: %4d/%02d/%02d %02d:%02d\n",
446 ptime->tm.tm_year, ptime->tm.tm_mon,
447 ptime->tm.tm_mday, ptime->tm.tm_hour,
452 * Convert the ptime.tm into standard time_t seconds. Check
453 * for invalid times, which includes things like the hour lost
454 * when switching from "standard time" to "daylight saving".
456 ptime->tsecs = mktime(&ptime->tm);
457 if (ptime->tsecs == (time_t)-1) {
458 ptime->tsecs = (time_t)-2;
466 ptime_free(struct ptime_data *ptime)
477 * Some trivial routines so ptime_data can remain a completely
481 ptimeget_ctime(const struct ptime_data *ptime)
485 return ("Null time in ptimeget_ctime()\n");
487 return (ctime(&ptime->tsecs));
491 * Generate a time of day string in an RFC5424 compatible format. Return a
492 * pointer to the buffer with the timestamp string or NULL if an error. If the
493 * time is not supplied, cannot be converted to local time, or the resulting
494 * string would overflow the buffer, the returned string will be the RFC5424
498 ptimeget_ctime_rfc5424(const struct ptime_data *ptime,
499 char *timebuf, size_t bufsize)
501 static const char NILVALUE[] = {"-"}; /* RFC5424 specified NILVALUE */
509 if (timebuf == NULL) {
513 if (bufsize < sizeof(NILVALUE)) {
518 * Convert to localtime. RFC5424 mandates the use of the NILVALUE if
519 * the time cannot be obtained, so use that if there is an error in the
522 if (ptime == NULL || localtime_r(&(ptime->tsecs), &tm) == NULL) {
523 strlcpy(timebuf, NILVALUE, bufsize);
528 * Convert the time to a string in RFC5424 format. The conversion
529 * cannot be done with strftime() because it cannot produce the correct
530 * timezone offset format.
532 if (tm.tm_gmtoff < 0) {
534 tz_offset = -tm.tm_gmtoff;
537 tz_offset = tm.tm_gmtoff;
540 tz_hours = tz_offset / 3600;
541 tz_mins = (tz_offset % 3600) / 60;
543 chars = snprintf(timebuf, bufsize,
544 "%04d-%02d-%02d" /* date */
545 "T%02d:%02d:%02d" /* time */
546 "%c%02d:%02d", /* time zone offset */
547 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
548 tm.tm_hour, tm.tm_min, tm.tm_sec,
549 tz_sign, tz_hours, tz_mins);
551 /* If the timestamp is too big for timebuf, return the NILVALUE. */
552 if (chars >= (int)bufsize) {
553 strlcpy(timebuf, NILVALUE, bufsize);
560 ptimeget_diff(const struct ptime_data *minuend, const struct
561 ptime_data *subtrahend)
564 /* Just like difftime(), we have no good error-return */
565 if (minuend == NULL || subtrahend == NULL)
568 return (difftime(minuend->tsecs, subtrahend->tsecs));
572 ptimeget_secs(const struct ptime_data *ptime)
578 return (ptime->tsecs);
582 * Generate an approximate timestamp for the next event, based on
583 * what parts of time were specified by the original parameter to
584 * ptime_relparse(). The result may be -1 if there is no obvious
585 * "next time" which will work.
588 ptimeset_nxtime(struct ptime_data *ptime)
590 int moredays, tdpm, tmon, tyear;
591 struct ptime_data nextmatch;
597 * Changes are not made to the given time until after all
598 * of the calculations have been successful.
602 * If the user specified a year and we're already past that
603 * time, then there will never be another one!
605 if (ptime->tmspec & TSPEC_YEAR)
609 * The caller gave us a time in the past. Calculate how much
610 * time is needed to go from that valid rotate time to the
611 * next valid rotate time. We only need to get to the nearest
612 * hour, because newsyslog is only run once per hour.
615 if (ptime->tmspec & TSPEC_MONTHOFYEAR) {
616 /* Special case: Feb 29th does not happen every year. */
617 if (ptime->tm.tm_mon == 1 && ptime->tm.tm_mday == 29) {
618 nextmatch.tm.tm_year += 4;
619 if (days_pmonth(1, nextmatch.tm.tm_year) < 29)
620 nextmatch.tm.tm_year += 4;
622 nextmatch.tm.tm_year += 1;
624 nextmatch.tm.tm_isdst = -1;
625 nextmatch.tsecs = mktime(&nextmatch.tm);
627 } else if (ptime->tmspec & TSPEC_LDAYOFMONTH) {
629 * Need to get to the last day of next month. Origtm is
630 * already at the last day of this month, so just add to
631 * it number of days in the next month.
633 if (ptime->tm.tm_mon < 11)
634 moredays = days_pmonth(ptime->tm.tm_mon + 1,
637 moredays = days_pmonth(0, ptime->tm.tm_year + 1);
639 } else if (ptime->tmspec & TSPEC_DAYOFMONTH) {
640 /* Jump to the same day in the next month */
641 moredays = days_pmonth(ptime->tm.tm_mon, ptime->tm.tm_year);
643 * In some cases, the next month may not *have* the
644 * desired day-of-the-month. If that happens, then
645 * move to the next month that does have enough days.
647 tmon = ptime->tm.tm_mon;
648 tyear = ptime->tm.tm_year;
656 tdpm = days_pmonth(tmon, tyear);
657 if (tdpm >= ptime->tm.tm_mday)
662 } else if (ptime->tmspec & TSPEC_DAYOFWEEK) {
664 } else if (ptime->tmspec & TSPEC_HOUROFDAY) {
669 nextmatch.tsecs += SECS_PER_HOUR * 24 * moredays;
670 nextmatch.tm = *(localtime(&nextmatch.tsecs));
674 * The new time will need to be adjusted if the setting of
675 * daylight-saving has changed between the two times.
677 ptime_adjust4dst(&nextmatch, ptime);
679 /* Everything worked. Update the given time and return. */
685 ptimeset_time(struct ptime_data *ptime, time_t secs)
692 ptime->tm = *(localtime(&ptime->tsecs));
693 ptime->parseopts = 0;
694 /* ptime->tmspec = ? */