newsyslog.c revision 1.35 1 /* $NetBSD: newsyslog.c,v 1.35 2000/07/24 15:15:25 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.35 2000/07/24 15:15:25 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 owner 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,
493 log->numhist - 1);
494
495 PRINFO(("rm -f %s\n", file1));
496 if (!noaction)
497 unlink(file1);
498 strlcat(file1, ".gz", sizeof (file1));
499 PRINFO(("rm -f %s\n", file1));
500 if (!noaction)
501 unlink(file1);
502
503 /* Move down log files. */
504 for (i = log->numhist - 1; i != 0; i--) {
505 snprintf(file1, sizeof (file1), "%s.%d", log->logfile, i - 1);
506 snprintf(file2, sizeof (file2), "%s.%d", log->logfile, i);
507
508 if (lstat(file1, &st) != 0) {
509 strlcat(file1, ".gz", sizeof (file1));
510 strlcat(file2, ".gz", sizeof (file2));
511 if (lstat(file1, &st) != 0)
512 continue;
513 }
514
515 PRINFO(("mv %s %s\n", file1, file2));
516 if (!noaction)
517 if (rename(file1, file2))
518 err(EXIT_FAILURE, "%s", file1);
519 PRINFO(("chmod %o %s\n", log->mode, file2));
520 if (!noaction)
521 if (chmod(file2, log->mode))
522 err(EXIT_FAILURE, "%s", file2);
523 PRINFO(("chown %d:%d %s\n", log->uid, log->gid,
524 file2));
525 if (!noaction)
526 if (chown(file2, log->uid, log->gid))
527 err(EXIT_FAILURE, "%s", file2);
528 }
529
530 /*
531 * If a historical log file isn't compressed, and 'z' has been
532 * specified, compress it. (This is convenient, but is also needed
533 * if 'p' has been specified.) It should be noted that gzip(1)
534 * preserves file ownership and file mode.
535 */
536 for (i = (log->flags & CE_PLAIN0) != 0; i < log->numhist; i++) {
537 snprintf(file1, sizeof (file1), "%s.%d", log->logfile, i);
538 if (lstat(file1, &st) != 0)
539 continue;
540 snprintf(file2, sizeof (file2), "%s.gz", file1);
541 if (lstat(file2, &st) == 0)
542 continue;
543 log_compress(log, file1);
544 }
545
546 log_trimmed(log);
547
548 /* Create the historical log file if we're maintaining history. */
549 if (log->numhist == 0) {
550 PRINFO(("rm -f %s\n", log->logfile));
551 if (!noaction)
552 if (unlink(log->logfile))
553 err(EXIT_FAILURE, "%s", log->logfile);
554 } else {
555 snprintf(file1, sizeof (file1), "%s.0", log->logfile);
556 PRINFO(("mv %s %s\n", log->logfile, file1));
557 if (!noaction)
558 if (rename(log->logfile, file1))
559 err(EXIT_FAILURE, "%s", log->logfile);
560 }
561
562 PRINFO(("(create new log)\n"));
563 log_create(log);
564 log_trimmed(log);
565
566 /* Set the correct permissions on the log. */
567 PRINFO(("chmod %o %s\n", log->mode, log->logfile));
568 if (!noaction)
569 if (chmod(log->logfile, log->mode))
570 err(EXIT_FAILURE, "%s", log->logfile);
571
572 /* Do we need to signal a daemon? */
573 if ((log->flags & CE_NOSIGNAL) == 0) {
574 if (log->pidfile[0] != '\0')
575 pid = readpidfile(log->pidfile);
576 else
577 pid = readpidfile(_PATH_SYSLOGDPID);
578
579 if (pid != (pid_t)-1) {
580 PRINFO(("kill -%s %lu\n",
581 sys_signame[log->signum], (u_long)pid));
582 if (!noaction)
583 if (kill(pid, log->signum))
584 warn("kill");
585 }
586 }
587
588 /* If the newest historical log is to be compressed, do it here. */
589 if ((log->flags & (CE_PLAIN0 | CE_COMPRESS)) == CE_COMPRESS) {
590 snprintf(file1, sizeof (file1), "%s.0", log->logfile);
591 log_compress(log, file1);
592 }
593 }
594
595 /*
596 * Write an entry to the log file recording the fact that it was trimmed.
597 */
598 void
599 log_trimmed(struct conf_entry *log)
600 {
601 FILE *fd;
602 time_t now;
603 char *daytime;
604
605 if ((log->flags & CE_BINARY) != 0)
606 return;
607 PRINFO(("(append rotation notice to %s)\n", log->logfile));
608 if (noaction)
609 return;
610
611 if ((fd = fopen(log->logfile, "at")) == NULL)
612 err(EXIT_FAILURE, "%s", log->logfile);
613
614 now = time(NULL);
615 daytime = ctime(&now) + 4;
616 daytime[15] = '\0';
617
618 fprintf(fd, "%s %s newsyslog[%lu]: log file turned over\n", daytime,
619 hostname, (u_long)getpid());
620 fclose(fd);
621 }
622
623 /*
624 * Create a new log file.
625 */
626 void
627 log_create(struct conf_entry *log)
628 {
629 int fd;
630
631 if (noaction)
632 return;
633
634 if ((fd = creat(log->logfile, log->mode)) < 0)
635 err(EXIT_FAILURE, "%s", log->logfile);
636 if (fchown(fd, log->uid, log->gid) < 0)
637 err(EXIT_FAILURE, "%s", log->logfile);
638 close(fd);
639 }
640
641 /*
642 * Fork off gzip(1) to compress a log file. This routine takes an
643 * additional string argument (the name of the file to compress): it is also
644 * used to compress historical log files other than the newest.
645 */
646 void
647 log_compress(struct conf_entry *log, const char *fn)
648 {
649 char tmp[MAXPATHLEN];
650 pid_t pid;
651
652 PRINFO(("gzip %s\n", fn));
653 if (!noaction) {
654 if ((pid = fork()) < 0)
655 err(EXIT_FAILURE, "fork");
656 else if (pid == 0) {
657 execl(_PATH_GZIP, "gzip", "-f", fn, NULL);
658 err(EXIT_FAILURE, _PATH_GZIP);
659 }
660 }
661
662 snprintf(tmp, sizeof (tmp), "%s.gz", fn);
663 PRINFO(("chown %d:%d %s\n", log->uid, log->gid, tmp));
664 if (!noaction)
665 if (!chown(tmp, log->uid, log->gid))
666 err(EXIT_FAILURE, "%s", tmp);
667 }
668
669 /*
670 * Display program usage information.
671 */
672 void
673 usage(void)
674 {
675
676 fprintf(stderr,
677 "usage: newsyslog [-nrvF] [-f config-file] [file ...]\n");
678 exit(EXIT_FAILURE);
679 }
680
681 /*
682 * Return non-zero if a string represents a decimal value.
683 */
684 int
685 isnumber(const char *string)
686 {
687
688 while (isdigit(*string))
689 string++;
690
691 return (*string == '\0');
692 }
693
694 /*
695 * Given a signal name, attempt to find the corresponding signal number.
696 */
697 int
698 getsig(const char *sig)
699 {
700 char *p;
701 int n;
702
703 if (isnumber(sig)) {
704 n = (int)strtol(sig, &p, 0);
705 if (p != '\0' || n < 0 || n >= NSIG)
706 return (-1);
707 return (n);
708 }
709
710 if (strncasecmp(sig, "SIG", 3) == 0)
711 sig += 3;
712 for (n = 1; n < NSIG; n++)
713 if (strcasecmp(sys_signame[n], sig) == 0)
714 return (n);
715 return (-1);
716 }
717
718 /*
719 * Given a path to a PID file, return the PID contained within.
720 */
721 pid_t
722 readpidfile(const char *file)
723 {
724 FILE *fd;
725 char line[BUFSIZ];
726 pid_t pid;
727
728 #ifdef notyet
729 if (file[0] != '/')
730 snprintf(tmp, sizeof (tmp), "%s%s", _PATH_VARRUN, file);
731 else
732 strlcpy(tmp, file, sizeof (tmp));
733 #endif
734
735 if ((fd = fopen(file, "rt")) == NULL) {
736 warn("%s", file);
737 return (-1);
738 }
739
740 if (fgets(line, sizeof (line) - 1, fd) != NULL) {
741 line[sizeof (line) - 1] = '\0';
742 pid = (pid_t)strtol(line, NULL, 0);
743 } else {
744 warnx("unable to read %s", file);
745 pid = (pid_t)-1;
746 }
747
748 fclose(fd);
749 return (pid);
750 }
751
752 /*
753 * Parse a user:group specification.
754 *
755 * XXX This is over the top for newsyslog(8). It should be moved to libutil.
756 */
757 int
758 parse_userspec(const char *name, struct passwd **pw, struct group **gr)
759 {
760 char buf[MAXLOGNAME * 2 + 2], *group;
761
762 strlcpy(buf, name, sizeof (buf));
763 *gr = NULL;
764
765 /*
766 * Before attempting to use '.' as a separator, see if the whole
767 * string resolves as a user name.
768 */
769 if ((*pw = getpwnam(buf)) != NULL) {
770 *gr = getgrgid((*pw)->pw_gid);
771 return (0);
772 }
773
774 /* Split the user and group name. */
775 if ((group = strchr(buf, ':')) != NULL ||
776 (group = strchr(buf, '.')) != NULL)
777 *group++ = '\0';
778
779 if (isnumber(buf))
780 *pw = getpwuid((uid_t)atoi(buf));
781 else
782 *pw = getpwnam(buf);
783
784 /*
785 * Find the group. If a group wasn't specified, use the user's
786 * `natural' group. We get to this point even if no user was found.
787 * This is to allow the caller to get a better idea of what went
788 * wrong, if anything.
789 */
790 if (group == NULL || *group == '\0') {
791 if (*pw == NULL)
792 return (-1);
793 *gr = getgrgid((*pw)->pw_gid);
794 } else if (isnumber(group))
795 *gr = getgrgid((gid_t)atoi(group));
796 else
797 *gr = getgrnam(group);
798
799 return (*pw != NULL && *gr != NULL ? 0 : -1);
800 }
801
802 /*
803 * Parse a cyclic time specification, the format is as follows:
804 *
805 * [Dhh] or [Wd[Dhh]] or [Mdd[Dhh]]
806 *
807 * to rotate a log file cyclic at
808 *
809 * - every day (D) within a specific hour (hh) (hh = 0...23)
810 * - once a week (W) at a specific day (d) OR (d = 0..6, 0 = Sunday)
811 * - once a month (M) at a specific day (d) (d = 1..31,l|L)
812 *
813 * We don't accept a timezone specification; missing fields are defaulted to
814 * the current date but time zero.
815 */
816 time_t
817 parse_dwm(char *s)
818 {
819 char *t;
820 struct tm tm, *tmp;
821 u_long ul;
822 time_t now;
823 static int mtab[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
824 int wmseen, dseen, nd, save;
825
826 wmseen = 0;
827 dseen = 0;
828
829 now = time(NULL);
830 tmp = localtime(&now);
831 tm = *tmp;
832
833 /* Set no. of days per month */
834 nd = mtab[tm.tm_mon];
835
836 if (tm.tm_mon == 1 &&
837 ((tm.tm_year + 1900) % 4 == 0) &&
838 ((tm.tm_year + 1900) % 100 != 0) &&
839 ((tm.tm_year + 1900) % 400 == 0))
840 nd++; /* leap year, 29 days in february */
841 tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
842
843 for (;;) {
844 switch (*s) {
845 case 'D':
846 if (dseen)
847 return ((time_t)-1);
848 dseen++;
849 s++;
850 ul = strtoul(s, &t, 10);
851 if (ul < 0 || ul > 23)
852 return ((time_t)-1);
853 tm.tm_hour = ul;
854 break;
855
856 case 'W':
857 if (wmseen)
858 return (-1);
859 wmseen++;
860 s++;
861 ul = strtoul(s, &t, 10);
862 if (ul < 0 || ul > 6)
863 return (-1);
864 if (ul != tm.tm_wday) {
865 if (ul < tm.tm_wday) {
866 save = 6 - tm.tm_wday;
867 save += (ul + 1);
868 } else
869 save = ul - tm.tm_wday;
870 tm.tm_mday += save;
871
872 if (tm.tm_mday > nd) {
873 tm.tm_mon++;
874 tm.tm_mday = tm.tm_mday - nd;
875 }
876 }
877 break;
878
879 case 'M':
880 if (wmseen)
881 return (-1);
882 wmseen++;
883 s++;
884 if (tolower(*s) == 'l') {
885 tm.tm_mday = nd;
886 s++;
887 t = s;
888 } else {
889 ul = strtoul(s, &t, 10);
890 if (ul < 1 || ul > 31)
891 return (-1);
892
893 if (ul > nd)
894 return (-1);
895 tm.tm_mday = ul;
896 }
897 break;
898
899 default:
900 return (-1);
901 break;
902 }
903
904 if (*t == '\0' || isspace(*t))
905 break;
906 else
907 s = t;
908 }
909
910 return (mktime(&tm));
911 }
912
913 /*
914 * Parse a limited subset of ISO 8601. The specific format is as follows:
915 *
916 * [CC[YY[MM[DD]]]][THH[MM[SS]]] (where `T' is the literal letter)
917 *
918 * We don't accept a timezone specification; missing fields (including
919 * timezone) are defaulted to the current date but time zero.
920 */
921 time_t
922 parse_iso8601(char *s)
923 {
924 char *t;
925 struct tm tm, *tmp;
926 u_long ul;
927 time_t now;
928
929 now = time(NULL);
930 tmp = localtime(&now);
931 tm = *tmp;
932
933 tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
934
935 ul = strtoul(s, &t, 10);
936 if (*t != '\0' && *t != 'T')
937 return ((time_t)-1);
938
939 /*
940 * Now t points either to the end of the string (if no time was
941 * provided) or to the letter `T' which separates date and time in
942 * ISO 8601. The pointer arithmetic is the same for either case.
943 */
944 switch (t - s) {
945 case 8:
946 tm.tm_year = ((ul / 1000000) - 19) * 100;
947 ul = ul % 1000000;
948 /* FALLTHROUGH */
949 case 6:
950 tm.tm_year = tm.tm_year - (tm.tm_year % 100);
951 tm.tm_year += ul / 10000;
952 ul = ul % 10000;
953 /* FALLTHROUGH */
954 case 4:
955 tm.tm_mon = (ul / 100) - 1;
956 ul = ul % 100;
957 /* FALLTHROUGH */
958 case 2:
959 tm.tm_mday = ul;
960 /* FALLTHROUGH */
961 case 0:
962 break;
963 default:
964 return ((time_t)-1);
965 }
966
967 /* Sanity check */
968 if (tm.tm_year < 70 || tm.tm_mon < 0 || tm.tm_mon > 12 ||
969 tm.tm_mday < 1 || tm.tm_mday > 31)
970 return ((time_t)-1);
971
972 if (*t != '\0') {
973 s = ++t;
974 ul = strtoul(s, &t, 10);
975 if (*t != '\0' && !isspace(*t))
976 return ((time_t)-1);
977
978 switch (t - s) {
979 case 6:
980 tm.tm_sec = ul % 100;
981 ul /= 100;
982 /* FALLTHROUGH */
983 case 4:
984 tm.tm_min = ul % 100;
985 ul /= 100;
986 /* FALLTHROUGH */
987 case 2:
988 tm.tm_hour = ul;
989 /* FALLTHROUGH */
990 case 0:
991 break;
992 default:
993 return ((time_t)-1);
994 }
995
996 /* Sanity check */
997 if (tm.tm_sec < 0 || tm.tm_sec > 60 || tm.tm_min < 0 ||
998 tm.tm_min > 59 || tm.tm_hour < 0 || tm.tm_hour > 23)
999 return ((time_t)-1);
1000 }
1001
1002 return (mktime(&tm));
1003 }
1004