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