newsyslog.c revision 1.34 1 /* $NetBSD: newsyslog.c,v 1.34 2000/07/19 10:52:35 ad Exp $ */
2
3 /*
4 * Copyright (c) 1999, 2000 Andrew Doran <ad (at) NetBSD.org>
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 *
28 */
29
30 /*
31 * This file contains changes from the Open Software Foundation.
32 */
33
34 /*
35 * Copyright 1988, 1989 by the Massachusetts Institute of Technology
36 *
37 * Permission to use, copy, modify, and distribute this software
38 * and its documentation for any purpose and without fee is
39 * hereby granted, provided that the above copyright notice
40 * appear in all copies and that both that copyright notice and
41 * this permission notice appear in supporting documentation,
42 * and that the names of M.I.T. and the M.I.T. S.I.P.B. not be
43 * used in advertising or publicity pertaining to distribution
44 * of the software without specific, written prior permission.
45 * M.I.T. and the M.I.T. S.I.P.B. make no representations about
46 * the suitability of this software for any purpose. It is
47 * provided "as is" without express or implied warranty.
48 *
49 */
50
51 /*
52 * newsyslog(8) - a program to roll over log files provided that specified
53 * critera are met, optionally preserving a number of historical log files.
54 */
55
56 #include <sys/cdefs.h>
57 #ifndef lint
58 __RCSID("$NetBSD: newsyslog.c,v 1.34 2000/07/19 10:52:35 ad Exp $");
59 #endif /* not lint */
60
61 #include <sys/types.h>
62 #include <sys/time.h>
63 #include <sys/stat.h>
64 #include <sys/param.h>
65
66 #include <ctype.h>
67 #include <fcntl.h>
68 #include <grp.h>
69 #include <pwd.h>
70 #include <signal.h>
71 #include <stdio.h>
72 #include <stdlib.h>
73 #include <stdarg.h>
74 #include <string.h>
75 #include <time.h>
76 #include <unistd.h>
77 #include <errno.h>
78 #include <err.h>
79 #include <util.h>
80 #include <paths.h>
81
82 #include "pathnames.h"
83
84 #define PRHDRINFO(x) ((void)(verbose ? printf x : 0))
85 #define PRINFO(x) ((void)(verbose ? printf(" ") + printf x : 0))
86
87 #define CE_COMPRESS 0x01 /* Compress the achived log files */
88 #define CE_BINARY 0x02 /* Logfile is a binary file/non-syslog */
89 #define CE_NOSIGNAL 0x04 /* Don't send a signal when trimmed */
90 #define CE_CREATE 0x08 /* Create log file if none exists */
91 #define CE_PLAIN0 0x10 /* Do not compress zero'th history file */
92
93 struct conf_entry {
94 uid_t uid; /* Owner of log */
95 gid_t gid; /* Group of log */
96 mode_t mode; /* File permissions */
97 int numhist; /* Number of historical logs to keep */
98 size_t maxsize; /* Maximum log size */
99 int maxage; /* Hours between log trimming */
100 time_t trimat; /* Specific trim time */
101 int flags; /* Flags (CE_*) */
102 int signum; /* Signal to send */
103 char pidfile[MAXPATHLEN]; /* File containing PID to signal */
104 char logfile[MAXPATHLEN]; /* Path to log file */
105 };
106
107 int verbose = 0; /* Be verbose */
108 int noaction = 0; /* Take no action */
109 char hostname[MAXHOSTNAMELEN + 1]; /* Hostname, stripped of domain */
110 uid_t myeuid; /* EUID we are running with */
111
112 int getsig(const char *);
113 int isnumber(const char *);
114 int main(int, char **);
115 int parse_cfgline(struct conf_entry *, FILE *, size_t *);
116 time_t parse_iso8601(char *);
117 time_t parse_dwm(char *);
118 int parse_userspec(const char *, struct passwd **, struct group **);
119 pid_t readpidfile(const char *);
120 void usage(void);
121
122 void log_compress(struct conf_entry *, const char *);
123 void log_create(struct conf_entry *);
124 void log_examine(struct conf_entry *, int);
125 void log_trim(struct conf_entry *);
126 void log_trimmed(struct conf_entry *);
127
128 /*
129 * Program entry point.
130 */
131 int
132 main(int argc, char **argv)
133 {
134 struct conf_entry log;
135 FILE *fd;
136 char *p, *cfile;
137 int c, needroot, i, force;
138 size_t lineno;
139
140 force = 0;
141 needroot = 1;
142 cfile = _PATH_NEWSYSLOGCONF;
143
144 gethostname(hostname, sizeof (hostname));
145 hostname[sizeof (hostname) - 1] = '\0';
146
147 /* Truncate domain. */
148 if ((p = strchr(hostname, '.')) != NULL)
149 *p = '\0';
150
151 /* Parse command line options. */
152 while ((c = getopt(argc, argv, "f:nrvF")) != -1) {
153 switch (c) {
154 case 'f':
155 cfile = optarg;
156 break;
157 case 'n':
158 noaction = 1;
159 verbose = 1;
160 break;
161 case 'r':
162 needroot = 0;
163 break;
164 case 'v':
165 verbose = 1;
166 break;
167 case 'F':
168 force = 1;
169 break;
170 default:
171 usage();
172 /* NOTREACHED */
173 }
174 }
175
176 myeuid = geteuid();
177 if (needroot && myeuid != 0)
178 errx(EXIT_FAILURE, "must be run as root");
179
180 argc -= optind;
181 argv += optind;
182
183 if (strcmp(cfile, "-") == 0)
184 fd = stdin;
185 else if ((fd = fopen(cfile, "rt")) == NULL)
186 err(EXIT_FAILURE, "%s", cfile);
187
188 for (lineno = 0; !parse_cfgline(&log, fd, &lineno);) {
189 /*
190 * If specific log files were specified, touch only
191 * those.
192 */
193 if (argc != 0) {
194 for (i = 0; i < argc; i++)
195 if (strcmp(log.logfile, argv[i]) == 0)
196 break;
197 if (i == argc)
198 continue;
199 }
200 log_examine(&log, force);
201 }
202
203 if (fd != stdin)
204 fclose(fd);
205
206 exit(EXIT_SUCCESS);
207 /* NOTREACHED */
208 }
209
210 /*
211 * Parse a single line from the configuration file.
212 */
213 int
214 parse_cfgline(struct conf_entry *log, FILE *fd, size_t *_lineno)
215 {
216 char *line, *q, **ap, *argv[10];
217 struct passwd *pw;
218 struct group *gr;
219 int nf, lineno, i, rv;
220
221 rv = -1;
222 line = NULL;
223
224 /* Place the white-space separated fields into an array. */
225 do {
226 if (line != NULL)
227 free(line);
228 if ((line = fparseln(fd, NULL, _lineno, NULL, 0)) == NULL)
229 return (rv);
230 lineno = (int)*_lineno;
231
232 for (ap = argv, nf = 0; (*ap = strsep(&line, " \t")) != NULL;)
233 if (**ap != '\0') {
234 if (++nf == sizeof (argv) / sizeof (argv[0])) {
235 warnx("config line %d: "
236 "too many fields", lineno);
237 goto bad;
238 }
239 ap++;
240 }
241 } while (nf == 0);
242
243 if (nf < 6)
244 errx(EXIT_FAILURE, "config line %d: too few fields", lineno);
245
246 memset(log, 0, sizeof (*log));
247
248 /* logfile_name */
249 ap = argv;
250 strlcpy(log->logfile, *ap++, sizeof (log->logfile));
251 if (log->logfile[0] != '/')
252 errx(EXIT_FAILURE,
253 "config line %d: logfile must have a full path", lineno);
254
255 /* owner:group */
256 if (strchr(*ap, ':') != NULL || strchr(*ap, '.') != NULL) {
257 if (parse_userspec(*ap++, &pw, &gr)) {
258 warnx("config line %d: unknown user/group", lineno);
259 goto bad;
260 }
261
262 /*
263 * We may only change the file's group as non-root.
264 */
265 if (myeuid != 0) {
266 if (pw->pw_uid != myeuid)
267 errx(EXIT_FAILURE, "config line %d: user:group "
268 "as non-root must match current user",
269 lineno);
270 log->uid = (uid_t)-1;
271 } else
272 log->uid = pw->pw_uid;
273 log->gid = gr->gr_gid;
274 if (nf < 7)
275 errx(EXIT_FAILURE, "config line %d: too few fields",
276 lineno);
277 } else if (myeuid != 0) {
278 log->uid = (uid_t)-1;
279 log->gid = getegid();
280 }
281
282 /* mode */
283 if (sscanf(*ap++, "%o", &i) != 1) {
284 warnx("config line %d: bad permissions", lineno);
285 goto bad;
286 }
287 log->mode = (mode_t)i;
288
289 /* count */
290 if (sscanf(*ap++, "%d", &log->numhist) != 1) {
291 warnx("config line %d: bad log count", lineno);
292 goto bad;
293 }
294
295 /* size */
296 if (isdigit(**ap)) {
297 log->maxsize = (int)strtol(*ap, &q, 0);
298 if (*q != '\0') {
299 warnx("config line %d: bad log size", lineno);
300 goto bad;
301 }
302 } else if (**ap == '*')
303 log->maxsize = (size_t)-1;
304 else {
305 warnx("config line %d: bad log size", lineno);
306 goto bad;
307 }
308 ap++;
309
310 /* when */
311 log->maxage = -1;
312 log->trimat = (time_t)-1;
313 q = *ap++;
314
315 if (strcmp(q, "*") != 0) {
316 if (isdigit(*q))
317 log->maxage = (int)strtol(q, &q, 10);
318
319 /*
320 * One class of periodic interval specification can follow a
321 * maximum age specification. Handle it.
322 */
323 if (*q == '@') {
324 log->trimat = parse_iso8601(q + 1);
325 if (log->trimat == (time_t)-1) {
326 warnx("config line %d: bad trim time", lineno);
327 goto bad;
328 }
329 } else if (*q == '$') {
330 if ((log->trimat = parse_dwm(q + 1)) == (time_t)-1) {
331 warnx("config line %d: bad trim time", lineno);
332 goto bad;
333 }
334 } else if (log->maxage == -1) {
335 warnx("config line %d: bad log age", lineno);
336 goto bad;
337 }
338 }
339
340 /* flags */
341 log->flags = 0;
342 for (q = *ap++; q != NULL && *q != '\0'; q++) {
343 switch (tolower(*q)) {
344 case 'b':
345 log->flags |= CE_BINARY;
346 break;
347 case 'c':
348 log->flags |= CE_CREATE;
349 break;
350 case 'n':
351 log->flags |= CE_NOSIGNAL;
352 break;
353 case 'p':
354 log->flags |= CE_PLAIN0;
355 break;
356 case 'z':
357 log->flags |= CE_COMPRESS;
358 break;
359 case '-':
360 break;
361 default:
362 warnx("config line %d: bad flags", lineno);
363 goto bad;
364 }
365 }
366
367 /* path_to_pidfile */
368 if (*ap != NULL && **ap == '/')
369 strlcpy(log->pidfile, *ap++, sizeof (log->pidfile));
370 else
371 log->pidfile[0] = '\0';
372
373 /* sigtype */
374 if (*ap != NULL && (log->signum = getsig(*ap++)) < 0) {
375 warnx("config line %d: bad signal type", lineno);
376 goto bad;
377 } else
378 log->signum = SIGHUP;
379
380 rv = 0;
381
382 bad:
383 free(line);
384 return (rv);
385 }
386
387 /*
388 * Examine a log file. If the trim conditions are met, call log_trim() to
389 * trim the log file.
390 */
391 void
392 log_examine(struct conf_entry *log, int force)
393 {
394 struct stat sb;
395 size_t size;
396 int age, trim;
397 char tmp[MAXPATHLEN];
398 const char *reason;
399 time_t now;
400
401 now = time(NULL);
402
403 PRHDRINFO(("\n%s <%d%s>: ", log->logfile, log->numhist,
404 (log->flags & CE_COMPRESS) != 0 ? "Z" : ""));
405
406 /*
407 * stat() the logfile. If it doesn't exist and the `c' flag has
408 * been specified, create it. If it doesn't exist and the `c' flag
409 * hasn't been specified, give up.
410 */
411 if (stat(log->logfile, &sb) < 0) {
412 if (errno == ENOENT && (log->flags & CE_CREATE) != 0) {
413 PRHDRINFO(("creating; "));
414 if (!noaction)
415 log_create(log);
416 else {
417 PRHDRINFO(("can't proceed with `-n'\n"));
418 return;
419 }
420 if (stat(log->logfile, &sb))
421 err(EXIT_FAILURE, "%s", log->logfile);
422 } else if (errno == ENOENT) {
423 PRHDRINFO(("does not exist --> skip log\n"));
424 return;
425 } else if (errno != 0)
426 err(EXIT_FAILURE, "%s", log->logfile);
427 }
428
429 /* Size of the log file in kB. */
430 size = ((size_t)sb.st_blocks * S_BLKSIZE) >> 10;
431
432 /*
433 * Get the age (expressed in hours) of the current log file with
434 * respect to the newest historical log file.
435 */
436 strlcpy(tmp, log->logfile, sizeof (tmp));
437 strlcat(tmp, ".0", sizeof (tmp));
438 if (stat(tmp, &sb) < 0) {
439 strlcat(tmp, ".gz", sizeof (tmp));
440 if (stat(tmp, &sb) < 0)
441 age = -1;
442 else
443 age = (int)(now - sb.st_mtime + 1800) / 3600;
444 } else
445 age = (int)(now - sb.st_mtime + 1800) / 3600;
446
447 /*
448 * Examine the set of given trim conditions and if any one is met,
449 * trim the log.
450 *
451 * Note: if `maxage' or `trimat' is used as a trim condition, we
452 * need at least one historical log file to determine the `age' of
453 * the active log file. WRT `trimat', we will trim up to one hour
454 * after the specific trim time has passed - we need to know if
455 * we've trimmed to meet that condition with a previous invocation
456 * of newsyslog(8).
457 */
458 if (log->maxage >= 0 && (age >= log->maxage || age < 0)) {
459 trim = 1;
460 reason = "log age > interval";
461 } else if (size >= log->maxsize) {
462 trim = 1;
463 reason = "log size > size";
464 } else if (log->trimat != (time_t)-1 && now >= log->trimat &&
465 age > 1 && difftime(now, log->trimat) < 60 * 60) {
466 trim = 1;
467 reason = "specific trim time";
468 } else {
469 trim = force;
470 reason = "trim forced";
471 }
472
473 if (trim) {
474 PRHDRINFO(("--> trim log (%s)\n", reason));
475 log_trim(log);
476 } else
477 PRHDRINFO(("--> skip log (trim conditions not met)\n"));
478 }
479
480 /*
481 * Trim the specified log file.
482 */
483 void
484 log_trim(struct conf_entry *log)
485 {
486 char file1[MAXPATHLEN], file2[MAXPATHLEN];
487 int i;
488 struct stat st;
489 pid_t pid;
490
491 /* Remove oldest historical log. */
492 snprintf(file1, sizeof (file1), "%s.%d", log->logfile, log->numhist - 1);
493
494 PRINFO(("rm -f %s\n", file1));
495 if (!noaction)
496 unlink(file1);
497 strlcat(file1, ".gz", sizeof (file1));
498 PRINFO(("rm -f %s\n", file1));
499 if (!noaction)
500 unlink(file1);
501
502 /* Move down log files. */
503 for (i = log->numhist - 1; i != 0; i--) {
504 snprintf(file1, sizeof (file1), "%s.%d", log->logfile, i - 1);
505 snprintf(file2, sizeof (file2), "%s.%d", log->logfile, i);
506
507 if (lstat(file1, &st) != 0) {
508 strlcat(file1, ".gz", sizeof (file1));
509 strlcat(file2, ".gz", sizeof (file2));
510 if (lstat(file1, &st) != 0)
511 continue;
512 }
513
514 PRINFO(("mv %s %s\n", file1, file2));
515 if (!noaction)
516 if (rename(file1, file2))
517 err(EXIT_FAILURE, "%s", file1);
518 PRINFO(("chmod %o %s\n", log->mode, file2));
519 if (!noaction)
520 if (chmod(file2, log->mode))
521 err(EXIT_FAILURE, "%s", file2);
522 PRINFO(("chown %d:%d %s\n", log->uid, log->gid,
523 file2));
524 if (!noaction)
525 if (chown(file2, log->uid, log->gid))
526 err(EXIT_FAILURE, "%s", file2);
527 }
528
529 /*
530 * If a historical log file isn't compressed, and 'z' has been
531 * specified, compress it. (This is convenient, but is also needed
532 * if 'p' has been specified.) It should be noted that gzip(1)
533 * preserves file ownership and file mode.
534 */
535 for (i = (log->flags & CE_PLAIN0) != 0; i < log->numhist; i++) {
536 snprintf(file1, sizeof (file1), "%s.%d", log->logfile, i);
537 if (lstat(file1, &st) != 0)
538 continue;
539 snprintf(file2, sizeof (file2), "%s.gz", file1);
540 if (lstat(file2, &st) == 0)
541 continue;
542 log_compress(log, file1);
543 }
544
545 log_trimmed(log);
546
547 /* Create the historical log file if we're maintaining history. */
548 if (log->numhist == 0) {
549 PRINFO(("rm -f %s\n", log->logfile));
550 if (!noaction)
551 if (unlink(log->logfile))
552 err(EXIT_FAILURE, "%s", log->logfile);
553 } else {
554 snprintf(file1, sizeof (file1), "%s.0", log->logfile);
555 PRINFO(("mv %s %s\n", log->logfile, file1));
556 if (!noaction)
557 if (rename(log->logfile, file1))
558 err(EXIT_FAILURE, "%s", log->logfile);
559 }
560
561 PRINFO(("(create new log)\n"));
562 log_create(log);
563 log_trimmed(log);
564
565 /* Set the correct permissions on the log. */
566 PRINFO(("chmod %o %s\n", log->mode, log->logfile));
567 if (!noaction)
568 if (chmod(log->logfile, log->mode))
569 err(EXIT_FAILURE, "%s", log->logfile);
570
571 /* Do we need to signal a daemon? */
572 if ((log->flags & CE_NOSIGNAL) == 0) {
573 if (log->pidfile[0] != '\0')
574 pid = readpidfile(log->pidfile);
575 else
576 pid = readpidfile(_PATH_SYSLOGDPID);
577
578 if (pid != (pid_t)-1) {
579 PRINFO(("kill -%s %lu\n",
580 sys_signame[log->signum], (u_long)pid));
581 if (!noaction)
582 if (kill(pid, log->signum))
583 warn("kill");
584 }
585 }
586
587 /* If the newest historical log is to be compressed, do it here. */
588 if ((log->flags & (CE_PLAIN0 | CE_COMPRESS)) == CE_COMPRESS) {
589 snprintf(file1, sizeof (file1), "%s.0", log->logfile);
590 log_compress(log, file1);
591 }
592 }
593
594 /*
595 * Write an entry to the log file recording the fact that it was trimmed.
596 */
597 void
598 log_trimmed(struct conf_entry *log)
599 {
600 FILE *fd;
601 time_t now;
602 char *daytime;
603
604 if ((log->flags & CE_BINARY) != 0)
605 return;
606 PRINFO(("(append rotation notice to %s)\n", log->logfile));
607 if (noaction)
608 return;
609
610 if ((fd = fopen(log->logfile, "at")) == NULL)
611 err(EXIT_FAILURE, "%s", log->logfile);
612
613 now = time(NULL);
614 daytime = ctime(&now) + 4;
615 daytime[15] = '\0';
616
617 fprintf(fd, "%s %s newsyslog[%lu]: log file turned over\n", daytime,
618 hostname, (u_long)getpid());
619 fclose(fd);
620 }
621
622 /*
623 * Create a new log file.
624 */
625 void
626 log_create(struct conf_entry *log)
627 {
628 int fd;
629
630 if (noaction)
631 return;
632
633 if ((fd = creat(log->logfile, log->mode)) < 0)
634 err(EXIT_FAILURE, "%s", log->logfile);
635 if (fchown(fd, log->uid, log->gid) < 0)
636 err(EXIT_FAILURE, "%s", log->logfile);
637 close(fd);
638 }
639
640 /*
641 * Fork off gzip(1) to compress a log file. This routine takes an
642 * additional string argument (the name of the file to compress): it is also
643 * used to compress historical log files other than the newest.
644 */
645 void
646 log_compress(struct conf_entry *log, const char *fn)
647 {
648 char tmp[MAXPATHLEN];
649 pid_t pid;
650
651 PRINFO(("gzip %s\n", fn));
652 if (!noaction) {
653 if ((pid = fork()) < 0)
654 err(EXIT_FAILURE, "fork");
655 else if (pid == 0) {
656 execl(_PATH_GZIP, "gzip", "-f", fn, NULL);
657 err(EXIT_FAILURE, _PATH_GZIP);
658 }
659 }
660
661 snprintf(tmp, sizeof (tmp), "%s.gz", fn);
662 PRINFO(("chown %d:%d %s\n", log->uid, log->gid, tmp));
663 if (!noaction)
664 if (!chown(tmp, log->uid, log->gid))
665 err(EXIT_FAILURE, "%s", tmp);
666 }
667
668 /*
669 * Display program usage information.
670 */
671 void
672 usage(void)
673 {
674
675 fprintf(stderr,
676 "usage: newsyslog [-nrvF] [-f config-file] [file ...]\n");
677 exit(EXIT_FAILURE);
678 }
679
680 /*
681 * Return non-zero if a string represents a decimal value.
682 */
683 int
684 isnumber(const char *string)
685 {
686
687 while (isdigit(*string))
688 string++;
689
690 return (*string == '\0');
691 }
692
693 /*
694 * Given a signal name, attempt to find the corresponding signal number.
695 */
696 int
697 getsig(const char *sig)
698 {
699 char *p;
700 int n;
701
702 if (isnumber(sig)) {
703 n = (int)strtol(sig, &p, 0);
704 if (p != '\0' || n < 0 || n >= NSIG)
705 return (-1);
706 return (n);
707 }
708
709 if (strncasecmp(sig, "SIG", 3) == 0)
710 sig += 3;
711 for (n = 1; n < NSIG; n++)
712 if (strcasecmp(sys_signame[n], sig) == 0)
713 return (n);
714 return (-1);
715 }
716
717 /*
718 * Given a path to a PID file, return the PID contained within.
719 */
720 pid_t
721 readpidfile(const char *file)
722 {
723 FILE *fd;
724 char line[BUFSIZ];
725 pid_t pid;
726
727 #ifdef notyet
728 if (file[0] != '/')
729 snprintf(tmp, sizeof (tmp), "%s%s", _PATH_VARRUN, file);
730 else
731 strlcpy(tmp, file, sizeof (tmp));
732 #endif
733
734 if ((fd = fopen(file, "rt")) == NULL) {
735 warn("%s", file);
736 return (-1);
737 }
738
739 if (fgets(line, sizeof (line) - 1, fd) != NULL) {
740 line[sizeof (line) - 1] = '\0';
741 pid = (pid_t)strtol(line, NULL, 0);
742 } else {
743 warnx("unable to read %s", file);
744 pid = (pid_t)-1;
745 }
746
747 fclose(fd);
748 return (pid);
749 }
750
751 /*
752 * Parse a user:group specification.
753 *
754 * XXX This is over the top for newsyslog(8). It should be moved to libutil.
755 */
756 int
757 parse_userspec(const char *name, struct passwd **pw, struct group **gr)
758 {
759 char buf[MAXLOGNAME * 2 + 2], *group;
760
761 strlcpy(buf, name, sizeof (buf));
762 *gr = NULL;
763
764 /*
765 * Before attempting to use '.' as a separator, see if the whole
766 * string resolves as a user name.
767 */
768 if ((*pw = getpwnam(buf)) != NULL) {
769 *gr = getgrgid((*pw)->pw_gid);
770 return (0);
771 }
772
773 /* Split the user and group name. */
774 if ((group = strchr(buf, ':')) != NULL ||
775 (group = strchr(buf, '.')) != NULL)
776 *group++ = '\0';
777
778 if (isnumber(buf))
779 *pw = getpwuid((uid_t)atoi(buf));
780 else
781 *pw = getpwnam(buf);
782
783 /*
784 * Find the group. If a group wasn't specified, use the user's
785 * `natural' group. We get to this point even if no user was found.
786 * This is to allow the caller to get a better idea of what went
787 * wrong, if anything.
788 */
789 if (group == NULL || *group == '\0') {
790 if (*pw == NULL)
791 return (-1);
792 *gr = getgrgid((*pw)->pw_gid);
793 } else if (isnumber(group))
794 *gr = getgrgid((gid_t)atoi(group));
795 else
796 *gr = getgrnam(group);
797
798 return (*pw != NULL && *gr != NULL ? 0 : -1);
799 }
800
801 /*
802 * Parse a cyclic time specification, the format is as follows:
803 *
804 * [Dhh] or [Wd[Dhh]] or [Mdd[Dhh]]
805 *
806 * to rotate a log file cyclic at
807 *
808 * - every day (D) within a specific hour (hh) (hh = 0...23)
809 * - once a week (W) at a specific day (d) OR (d = 0..6, 0 = Sunday)
810 * - once a month (M) at a specific day (d) (d = 1..31,l|L)
811 *
812 * We don't accept a timezone specification; missing fields are defaulted to
813 * the current date but time zero.
814 */
815 time_t
816 parse_dwm(char *s)
817 {
818 char *t;
819 struct tm tm, *tmp;
820 u_long ul;
821 time_t now;
822 static int mtab[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
823 int wmseen, dseen, nd, save;
824
825 wmseen = 0;
826 dseen = 0;
827
828 now = time(NULL);
829 tmp = localtime(&now);
830 tm = *tmp;
831
832 /* Set no. of days per month */
833 nd = mtab[tm.tm_mon];
834
835 if (tm.tm_mon == 1 &&
836 ((tm.tm_year + 1900) % 4 == 0) &&
837 ((tm.tm_year + 1900) % 100 != 0) &&
838 ((tm.tm_year + 1900) % 400 == 0))
839 nd++; /* leap year, 29 days in february */
840 tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
841
842 for (;;) {
843 switch (*s) {
844 case 'D':
845 if (dseen)
846 return ((time_t)-1);
847 dseen++;
848 s++;
849 ul = strtoul(s, &t, 10);
850 if (ul < 0 || ul > 23)
851 return ((time_t)-1);
852 tm.tm_hour = ul;
853 break;
854
855 case 'W':
856 if (wmseen)
857 return (-1);
858 wmseen++;
859 s++;
860 ul = strtoul(s, &t, 10);
861 if (ul < 0 || ul > 6)
862 return (-1);
863 if (ul != tm.tm_wday) {
864 if (ul < tm.tm_wday) {
865 save = 6 - tm.tm_wday;
866 save += (ul + 1);
867 } else
868 save = ul - tm.tm_wday;
869 tm.tm_mday += save;
870
871 if (tm.tm_mday > nd) {
872 tm.tm_mon++;
873 tm.tm_mday = tm.tm_mday - nd;
874 }
875 }
876 break;
877
878 case 'M':
879 if (wmseen)
880 return (-1);
881 wmseen++;
882 s++;
883 if (tolower(*s) == 'l') {
884 tm.tm_mday = nd;
885 s++;
886 t = s;
887 } else {
888 ul = strtoul(s, &t, 10);
889 if (ul < 1 || ul > 31)
890 return (-1);
891
892 if (ul > nd)
893 return (-1);
894 tm.tm_mday = ul;
895 }
896 break;
897
898 default:
899 return (-1);
900 break;
901 }
902
903 if (*t == '\0' || isspace(*t))
904 break;
905 else
906 s = t;
907 }
908
909 return (mktime(&tm));
910 }
911
912 /*
913 * Parse a limited subset of ISO 8601. The specific format is as follows:
914 *
915 * [CC[YY[MM[DD]]]][THH[MM[SS]]] (where `T' is the literal letter)
916 *
917 * We don't accept a timezone specification; missing fields (including
918 * timezone) are defaulted to the current date but time zero.
919 */
920 time_t
921 parse_iso8601(char *s)
922 {
923 char *t;
924 struct tm tm, *tmp;
925 u_long ul;
926 time_t now;
927
928 now = time(NULL);
929 tmp = localtime(&now);
930 tm = *tmp;
931
932 tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
933
934 ul = strtoul(s, &t, 10);
935 if (*t != '\0' && *t != 'T')
936 return ((time_t)-1);
937
938 /*
939 * Now t points either to the end of the string (if no time was
940 * provided) or to the letter `T' which separates date and time in
941 * ISO 8601. The pointer arithmetic is the same for either case.
942 */
943 switch (t - s) {
944 case 8:
945 tm.tm_year = ((ul / 1000000) - 19) * 100;
946 ul = ul % 1000000;
947 /* FALLTHROUGH */
948 case 6:
949 tm.tm_year = tm.tm_year - (tm.tm_year % 100);
950 tm.tm_year += ul / 10000;
951 ul = ul % 10000;
952 /* FALLTHROUGH */
953 case 4:
954 tm.tm_mon = (ul / 100) - 1;
955 ul = ul % 100;
956 /* FALLTHROUGH */
957 case 2:
958 tm.tm_mday = ul;
959 /* FALLTHROUGH */
960 case 0:
961 break;
962 default:
963 return ((time_t)-1);
964 }
965
966 /* Sanity check */
967 if (tm.tm_year < 70 || tm.tm_mon < 0 || tm.tm_mon > 12 ||
968 tm.tm_mday < 1 || tm.tm_mday > 31)
969 return ((time_t)-1);
970
971 if (*t != '\0') {
972 s = ++t;
973 ul = strtoul(s, &t, 10);
974 if (*t != '\0' && !isspace(*t))
975 return ((time_t)-1);
976
977 switch (t - s) {
978 case 6:
979 tm.tm_sec = ul % 100;
980 ul /= 100;
981 /* FALLTHROUGH */
982 case 4:
983 tm.tm_min = ul % 100;
984 ul /= 100;
985 /* FALLTHROUGH */
986 case 2:
987 tm.tm_hour = ul;
988 /* FALLTHROUGH */
989 case 0:
990 break;
991 default:
992 return ((time_t)-1);
993 }
994
995 /* Sanity check */
996 if (tm.tm_sec < 0 || tm.tm_sec > 60 || tm.tm_min < 0 ||
997 tm.tm_min > 59 || tm.tm_hour < 0 || tm.tm_hour > 23)
998 return ((time_t)-1);
999 }
1000
1001 return (mktime(&tm));
1002 }
1003