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