Debian Codegraph @

src/cronoutils.c

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 /* ====================================================================
2 * Copyright (c) 1995-1999 The Apache Group. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in
13 * the documentation and/or other materials provided with the
14 * distribution.
15 *
16 * 3. All advertising materials mentioning features or use of this
17 * software must display the following acknowledgment:
18 * "This product includes software developed by the Apache Group
19 * for use in the Apache HTTP server project (http://www.apache.org/)."
20 *
21 * 4. The names "Apache Server" and "Apache Group" must not be used to
22 * endorse or promote products derived from this software without
23 * prior written permission. For written permission, please contact
24 * [email protected].
25 *
26 * 5. Products derived from this software may not be called "Apache"
27 * nor may "Apache" appear in their names without prior written
28 * permission of the Apache Group.
29 *
30 * 6. Redistributions of any form whatsoever must retain the following
31 * acknowledgment:
32 * "This product includes software developed by the Apache Group
33 * for use in the Apache HTTP server project (http://www.apache.org/)."
34 *
35 * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY
36 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
38 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE GROUP OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
41 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
42 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
43 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
44 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
45 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
46 * OF THE POSSIBILITY OF SUCH DAMAGE.
47 * ====================================================================
48 *
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Group and was originally based
51 * on public domain software written at the National Center for
52 * Supercomputing Applications, University of Illinois, Urbana-Champaign.
53 * For more information on the Apache Group and the Apache HTTP server
54 * project, please see <http://www.apache.org/>.
55 *
56 */
57 /*
58 * cronoutils -- utilities for the cronolog program
59 *
60 * Copyright (c) 1996-1999 by Ford & Mason Ltd
61 *
62 * This software was submitted by Ford & Mason Ltd to the Apache
63 * Software Foundation in December 1999. Future revisions and
64 * derivatives of this source code must acknowledge Ford & Mason Ltd
65 * as the original contributor of this module. All other licensing
66 * and usage conditions are those of the Apache Software Foundation.
67 *
68 * Originally written by Andrew Ford <[email protected]>
69 *
70 */
71
•72 #include <strings.h>
73
74 #include "cronoutils.h"
75 extern char *tzname[2];
76
77
78 #ifdef _WIN32
79 #include "strptime.h"
80 #endif
81 /* debug_file is the file to output debug messages to. No debug
82 * messages are output if it is set to NULL.
83 */
84 FILE *debug_file = NULL;
85
86
87 /* America and Europe disagree on whether weeks start on Sunday or
88 * Monday - weeks_start_on_mondays is set if a %U specifier is encountered.
89 */
90 int weeks_start_on_mondays = 0;
91
92
93 /* periods[] is an array of the names of the periods.
94 */
95 char *periods[] =
96 {
97 "second",
98 "minute",
99 "hour",
100 "day",
101 "week",
102 "month",
103 "year",
104 "aeon" /* i.e. once only */
105 };
106
107 /* period_seconds[] is an array of the number of seconds in a period.
108 */
109 int period_seconds[] =
110 {
111 1,
112 60,
113 60 * 60,
114 60 * 60 * 24,
115 60 * 60 * 24 * 7,
116 60 * 60 * 24 * 31,
117 60 * 60 * 24 * 36
118 };
119
120 /* Try to create missing directories on the path of filename.
121 *
122 * Note that on a busy server there may theoretically be many cronolog
123 * processes trying simultaneously to create the same subdirectories
124 * so ignore any EEXIST errors on mkdir -- they probably just mean
125 * that another process got there first.
126 *
127 * Unless CHECK_ALL_PREFIX_DIRS is defined, we save the directory of
128 * the last file tested -- any common prefix should exist. This
129 * probably only saves a few stat system calls at the start of each
130 * log period, but it might as well be done.
131 */
132 void
133 create_subdirs(char *filename)
134 {
135 #ifndef CHECK_ALL_PREFIX_DIRS
136 static char lastpath[MAX_PATH] = "";
137 #endif
138 struct stat stat_buf;
139 char dirname[MAX_PATH];
140 char *p;
141
142 DEBUG(("Creating missing components of \"%s\"\n", filename));
143 for (p = filename; (p = strchr(p, '/')); p++)
144 {
145 if (p == filename)
146 {
147 continue; /* Don't bother with the root directory */
148 }
149
150 memcpy(dirname, filename, p - filename);
151 dirname[p-filename] = '\0';
152
153 #ifndef CHECK_ALL_PREFIX_DIRS
154 if (strncmp(dirname, lastpath, strlen(dirname)) == 0)
155 {
156 DEBUG(("Initial prefix \"%s\" known to exist\n", dirname));
157 continue;
158 }
159 #endif
160
161 DEBUG(("Testing directory \"%s\"\n", dirname));
162 if (stat(dirname, &stat_buf) < 0)
163 {
164 if (errno != ENOENT)
165 {
166 perror(dirname);
167 exit(2);
168 }
169 else
170 {
171 DEBUG(("Directory \"%s\" does not exist -- creating\n", dirname));
172 if ((mkdir(dirname, DIR_MODE) < 0) && (errno != EEXIST))
173 #ifndef _WIN32
174 {
175 #else
176 if ((mkdir(dirname) < 0) && (errno != EEXIST))
177 #endif
178 perror(dirname);
179 exit(2);
180 }
181 }
182 }
183 }
184 #ifndef CHECK_ALL_PREFIX_DIRS
185 strcpy(lastpath, dirname);
186 #endif
187 }
188
189 /* Create a hard or symbolic link to a filename according to the type specified.
190 *
191 * This function could do with more error checking!
192 */
193 void
194 create_link(char *pfilename,
195 const char *linkname, mode_t linktype,
196 const char *prevlinkname)
197 {
198 struct stat stat_buf;
199
200 if (stat(prevlinkname, &stat_buf) == 0)
201 {
202 unlink(prevlinkname);
203 }
204 if (stat(linkname, &stat_buf) == 0)
205 {
206 if (prevlinkname) {
207 rename(linkname, prevlinkname);
208 }
209 else {
210 unlink(linkname);
211 }
212 }
213 #ifndef _WIN32
214 if (linktype == S_IFLNK)
215 {
216 symlink(pfilename, linkname);
217 }
218 else
219 {
220 link(pfilename, linkname);
221 }
222 #else
223 fprintf(stderr, "Creating link from %s to %s not supported", pfilename, linkname);
224 #endif
225 }
226
227 /* Examine the log file name specifier for strftime conversion
228 * specifiers and determine the period between log files.
229 * Smallest period allowed is per minute.
230 */
231 PERIODICITY
232 determine_periodicity(char *spec)
233 {
234 PERIODICITY periodicity = ONCE_ONLY;
235 char ch;
236
237 DEBUG(("Determining periodicity of \"%s\"\n", spec));
238 while ((ch = *spec++) != 0)
239 {
240 if (ch == '%')
241 {
242 ch = *spec++;
243 if (!ch) break;
244
245 switch (ch)
246 {
247 case 'y': /* two digit year */
248 case 'Y': /* four digit year */
249 if (periodicity > YEARLY)
250 {
251 DEBUG(("%%%c -> yearly\n", ch));
252 periodicity = YEARLY;
253 }
254 break;
255
256 case 'b': /* abbreviated month name */
257 case 'h': /* abbreviated month name (non-standard) */
258 case 'B': /* full month name */
259 case 'm': /* month as two digit number (with
260 leading zero) */
261 if (periodicity > MONTHLY)
262 {
263 DEBUG(("%%%c -> monthly\n", ch));
264 periodicity = MONTHLY;
265 }
266 break;
267
268 case 'U': /* week number (weeks start on Sunday) */
269 case 'W': /* week number (weeks start on Monday) */
270 if (periodicity > WEEKLY)
271 {
272 DEBUG(("%%%c -> weeky\n", ch));
273 periodicity = WEEKLY;
274 weeks_start_on_mondays = (ch == 'W');
275 }
276 break;
277
278 case 'a': /* abbreviated weekday name */
279 case 'A': /* full weekday name */
280 case 'd': /* day of the month (with leading zero) */
281 case 'e': /* day of the month (with leading space -- non-standard) */
282 case 'j': /* day of the year (with leading zeroes) */
283 case 'w': /* day of the week (0-6) */
284 case 'D': /* full date spec (non-standard) */
285 case 'x': /* full date spec */
286 if (periodicity > DAILY)
287 {
288 DEBUG(("%%%c -> daily\n", ch));
289 periodicity = DAILY;
290 }
291 break;
292
293 case 'H': /* hour (24 hour clock) */
294 case 'I': /* hour (12 hour clock) */
295 case 'p': /* AM/PM indicator */
296 if (periodicity > HOURLY)
297 {
298 DEBUG(("%%%c -> hourly\n", ch));
299 periodicity = HOURLY;
300 }
301 break;
302
303 case 'M': /* minute */
304 if (periodicity > PER_MINUTE)
305 {
306 DEBUG(("%%%c -> per minute\n", ch));
307 periodicity = PER_MINUTE;
308 }
309 break;
310
311 case 'S': /* second */
312 case 's': /* seconds since the epoch (GNU non-standard) */
313 case 'c': /* full time and date spec */
314 case 'T': /* full time spec */
315 case 'r': /* full time spec (non-standard) */
316 case 'R': /* full time spec (non-standard) */
317 DEBUG(("%%%c -> per second", ch));
318 periodicity = PER_SECOND;
319
320 default: /* ignore anything else */
321 DEBUG(("ignoring %%%c\n", ch));
322 break;
323 }
324 }
325 }
326 return periodicity;
327 }
328
329 /*
330 */
331 PERIODICITY
332 parse_timespec(char *optarg, int *p_period_multiple)
333 {
334 PERIODICITY periodicity = INVALID_PERIOD;
335 int period_multiple = 1;
336 char *p = optarg;
337
338 /* Skip leading whitespace */
339
340 while (isspace(*p)) { p++; }
341
342
343 /* Parse a digit string */
344
345 if (isdigit(*p)) {
346 period_multiple = *p++ - '0';
347
348 while (isdigit(*p)) {
349 period_multiple *= 10;
350 period_multiple += (*p++ - '0');
351 }
352 }
353
354
355 /* Skip whitespace */
356
357 while (isspace(*p)) { p++; }
358
359 if (strncasecmp(p, "sec", 3) == 0) {
360 if (period_multiple < 60) {
361 periodicity = PER_SECOND;
362 }
363 }
364 else if (strncasecmp(p, "min", 3) == 0) {
365 if (period_multiple < 60) {
366 periodicity = PER_MINUTE;
367 }
368 }
369 else if (strncasecmp(p, "hour", 4) == 0) {
370 if (period_multiple < 24) {
371 periodicity = HOURLY;
372 }
373 }
374 else if (strncasecmp(p, "day", 3) == 0) {
375 if (period_multiple <= 31) {
376 periodicity = DAILY;
377 }
378 }
379 else if (strncasecmp(p, "week", 4) == 0) {
380 if (period_multiple < 53) {
381 periodicity = WEEKLY;
382 }
383 }
384 else if (strncasecmp(p, "mon", 3) == 0) {
385 if (period_multiple <= 12) {
386 periodicity = MONTHLY;
387 }
388 }
389 *p_period_multiple = period_multiple;
390 return periodicity;
391 }
392
393 /* To determine the time of the start of the next period add just
394 * enough to move beyond the start of the next period and then
395 * determine the time of the start of that period.
396 *
397 * There is a potential problem if the start or end of daylight saving
398 * time occurs during the current period.
399 */
400 time_t
401 start_of_next_period(time_t time_now, PERIODICITY periodicity, int period_multiple)
402 {
403 time_t start_time;
404
405 switch (periodicity)
406 {
407 case YEARLY:
408 start_time = (time_now + 366 * SECS_PER_DAY + DST_ALLOWANCE);
409 break;
410
411 case MONTHLY:
412 start_time = (time_now + 31 * SECS_PER_DAY + DST_ALLOWANCE);
413 break;
414
415 case WEEKLY:
416 start_time = (time_now + SECS_PER_WEEK + DST_ALLOWANCE);
417 break;
418
419 case DAILY:
420 start_time = (time_now + SECS_PER_DAY + DST_ALLOWANCE);
421 break;
422
423 case HOURLY:
424 start_time = time_now + period_multiple * SECS_PER_HOUR + LEAP_SECOND_ALLOWANCE;
425 break;
426
427 case PER_MINUTE:
428 start_time = time_now + period_multiple * SECS_PER_MIN + LEAP_SECOND_ALLOWANCE;
429 break;
430
431 case PER_SECOND:
432 start_time = time_now + 1;
433 break;
434
435 default:
436 start_time = FAR_DISTANT_FUTURE;
437 break;
438 }
439 return start_of_this_period(start_time, periodicity, period_multiple);
440 }
441
442 /* Determine the time of the start of the period containing a given time.
443 * Break down the time with localtime and subtract the number of
444 * seconds since the start of the period. If the length of period is
445 * equal or longer than a day then we have to check tht the
446 * calculation is not thrown out by the start or end of daylight
447 * saving time.
448 */
449 time_t
450 start_of_this_period(time_t start_time, PERIODICITY periodicity, int period_multiple)
451 {
452 struct tm tm_initial;
453 struct tm tm_adjusted;
454 int expected_mday;
455
456 #ifndef _WIN32
457 localtime_r(&start_time, &tm_initial);
458 #else
459 struct tm * tempTime;
460
461 tempTime = localtime(&start_time);
462 if (NULL != tempTime)
463 {
464 memcpy(&tm_initial, tempTime, sizeof(struct tm));
465
466 free(tempTime);
467 tempTime = NULL;
468 }
469 #endif
470 switch (periodicity)
471 {
472 case YEARLY:
473 case MONTHLY:
474 case WEEKLY:
475 case DAILY:
476 switch (periodicity)
477 {
478 case YEARLY:
479 start_time -= ( (tm_initial.tm_yday * SECS_PER_DAY)
480 + (tm_initial.tm_hour * SECS_PER_HOUR)
481 + (tm_initial.tm_min * SECS_PER_MIN)
482 + (tm_initial.tm_sec));
483 expected_mday = 1;
484 break;
485
486 case MONTHLY:
487 start_time -= ( ((tm_initial.tm_mday - 1) * SECS_PER_DAY)
488 + ( tm_initial.tm_hour * SECS_PER_HOUR)
489 + ( tm_initial.tm_min * SECS_PER_MIN)
490 + ( tm_initial.tm_sec));
491 expected_mday = 1;
492 break;
493
494 case WEEKLY:
495 if (weeks_start_on_mondays)
496 {
497 tm_initial.tm_wday = (6 + tm_initial.tm_wday) % 7;
498 }
499 start_time -= ( (tm_initial.tm_wday * SECS_PER_DAY)
500 + (tm_initial.tm_hour * SECS_PER_HOUR)
501 + (tm_initial.tm_min * SECS_PER_MIN)
502 + (tm_initial.tm_sec));
503 expected_mday = tm_initial.tm_mday;
504 break;
505
506 case DAILY:
507 start_time -= ( (tm_initial.tm_hour * SECS_PER_HOUR)
508 + (tm_initial.tm_min * SECS_PER_MIN )
509 + tm_initial.tm_sec);
510 expected_mday = tm_initial.tm_mday;
511 break;
512
513 default:
514 fprintf(stderr, "software fault in start_of_this_period()\n");
515 exit(1);
516 }
517
518 /* If the time of day is not equal to midnight then we need to
519 * adjust for daylight saving time. Adjust the time backwards
520 * by the value of the hour, minute and second fields. If the
521 * day of the month is not as expected one then we must have
522 * adjusted back to the previous day so add 24 hours worth of
523 * seconds.
524 */
525 #ifndef _WIN32
526 localtime_r(&start_time, &tm_adjusted);
527 #else
528 tempTime = localtime(&start_time);
529 if (NULL != tempTime)
530 {
531 memcpy(&tm_adjusted, tempTime, sizeof(struct tm));
532
533 free(tempTime);
534 tempTime = NULL;
535 }
536 #endif
537 if ( (tm_adjusted.tm_hour != 0)
538 || (tm_adjusted.tm_min != 0)
539 || (tm_adjusted.tm_sec != 0))
540 {
541 char sign = '-';
542 time_t adjust = - ( (tm_adjusted.tm_hour * SECS_PER_HOUR)
543 + (tm_adjusted.tm_min * SECS_PER_MIN)
544 + (tm_adjusted.tm_sec));
545
546 if (tm_adjusted.tm_mday != expected_mday)
547 {
548 adjust += SECS_PER_DAY;
549 sign = '+';
550 }
551 start_time += adjust;
552
553 if (adjust < 0)
554 {
555 adjust = -adjust;
556 }
557
558 DEBUG(("Adjust for dst: %02d/%02d/%04d %02d:%02d:%02d -- %c%0d:%02d:%02d\n",
559 tm_initial.tm_mday, tm_initial.tm_mon+1, tm_initial.tm_year+1900,
560 tm_initial.tm_hour, tm_initial.tm_min, tm_initial.tm_sec, sign,
561 adjust / SECS_PER_HOUR, (adjust / 60) % 60, adjust % SECS_PER_HOUR));
562 }
563 break;
564
565 case HOURLY:
566 start_time -= (tm_initial.tm_sec + tm_initial.tm_min * SECS_PER_MIN);
567 if (period_multiple > 1) {
568 start_time -= SECS_PER_HOUR * (tm_initial.tm_hour -
569 period_multiple * (tm_initial.tm_hour / period_multiple));
570 }
571 break;
572
573 case PER_MINUTE:
574 start_time -= tm_initial.tm_sec;
575 if (period_multiple > 1) {
576 start_time -= SECS_PER_MIN * (tm_initial.tm_min -
577 period_multiple * (tm_initial.tm_min / period_multiple));
578 }
579 break;
580
581 case PER_SECOND: /* No adjustment needed */
582 default:
583 break;
584 }
585 return start_time;
586 }
587
588 /* Converts struct tm to time_t, assuming the data in tm is UTC rather
589 * than local timezone (as mktime assumes).
590 *
591 * Contributed by Roger Beeman <[email protected]>.
592 */
593 time_t
594 mktime_from_utc(struct tm *t)
595 {
596 time_t tl, tb;
597
598 tl = mktime(t);
599 tb = mktime(gmtime(&tl));
600 return (tl <= tb ? (tl + (tl - tb)) : (tl - (tb - tl)));
601 }
602
603 /* Check whether the string is processed well. It is processed if the
604 * pointer is non-NULL, and it is either at the `GMT', or at the end
605 * of the string.
606 */
607 static int
608 check_end(const char *p)
609 {
610 if (!p)
611 return 0;
612 while (isspace(*p))
613 ++p;
614 if (!*p || (p[0] == 'G' && p[1] == 'M' && p[2] == 'T'))
615 return 1;
616 else
617 return 0;
618 }
619
620 /* NOTE: We don't use `%n' for white space, as OSF's strptime uses
621 it to eat all white space up to (and including) a newline, and
622 the function fails (!) if there is no newline.
623
624 Let's hope all strptime-s use ` ' to skipp *all* whitespace
625 instead of just one (it works that way on all the systems I've
626 tested it on). */
627
628 static char *european_date_formats[] =
629 {
630 "%d %b %Y %T", /* dd mmm yyyy HH:MM:SS */
631 "%d %b %Y %H:%M", /* dd mmm yyyy HH:MM */
632 "%d %b %Y", /* dd mmm yyyy */
633 "%d-%b-%Y %T", /* dd-mmm-yyyy HH:MM:SS */
634 "%d-%b-%Y %H:%M", /* dd-mmm-yyyy HH:MM */
635 "%d-%b-%y %T", /* dd-mmm-yy HH:MM:SS */
636 "%d-%b-%y %H:%M", /* dd-mmm-yy HH:MM */
637 "%d-%b-%Y",
638 "%b %d %T %Y",
639 "%b %d %Y",
640 NULL
641 };
642
643 static char *american_date_formats[] =
644 {
645 "%b %d %Y %T", /* dd mmm yyyy HH:MM:SS */
646 "%b %d %Y %H:%M", /* dd mmm yyyy HH:MM */
647 "%b %d %Y", /* dd mmm yyyy */
648 "%b-%d-%Y %T", /* dd-mmm-yyyy HH:MM:SS */
649 "%b-%d-%Y %H:%M", /* dd-mmm-yyyy HH:MM */
650 "%b-%d-%Y",
651 "%b/%d/%Y %T",
652 "%b/%d/%Y %H:%M",
653 "%b/%d/%Y",
654 NULL
655 };
656
657
658
659 time_t
660 parse_time(char *time_str, int use_american_date_formats)
661 {
662 struct tm tm;
663 char **date_formats;
664
665 memset(&tm, 0, sizeof (tm));
666 tm.tm_isdst = -1;
667
668
669 for (date_formats = (use_american_date_formats
670 ? american_date_formats
671 : european_date_formats);
672 *date_formats;
673 date_formats++)
674 {
675 if (check_end((const char *)strptime(time_str, *date_formats, &tm)))
676 return mktime_from_utc(&tm);
677 }
678
679 return -1;
680 }
681
682
683
684 /* Simple debugging print function.
685 */
686 void
687 print_debug_msg(char *msg, ...)
688 {
689 va_list ap;
690
691 va_start(ap, msg);
692 vfprintf(debug_file, msg, ap);
693 }
694
695
696 /* Build a timestamp and return a pointer to it.
697 * (has a number of static buffers that are rotated).
698 */
699 char *
700 timestamp(time_t thetime)
701 {
702 static int index = 0;
703 static char buffer[4][80];
704 struct tm *tm;
705 char *retval;
706
707 retval = buffer[index++];
708 index %= 4;
709
710 tm = localtime(&thetime);
711 strftime(retval, 80, "%Y/%m/%d-%H:%M:%S %Z", tm);
712 return retval;
713 }
714
715