newsyslog.c revision 1.29 1 /* $NetBSD: newsyslog.c,v 1.29 2000/07/11 11:39:47 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(1) - 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.29 2000/07/11 11:39:47 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
81 #include "pathnames.h"
82
83 #define PRHDRINFO(x) ((void)(verbose ? printf x : 0))
84 #define PRINFO(x) ((void)(verbose ? printf(" ") + printf x : 0))
85
86 #define CE_COMPRESS 0x01 /* Compress the achived log files */
87 #define CE_BINARY 0x02 /* Logfile is a binary file/non-syslog */
88 #define CE_NOSIGNAL 0x04 /* Don't send a signal when trimmed */
89 #define CE_CREATE 0x08 /* Create log file if none exists */
90 #define CE_PLAIN0 0x10 /* Do not compress zero'th history file */
91
92 struct conf_entry {
93 uid_t uid; /* Owner of log */
94 gid_t gid; /* Group of log */
95 mode_t mode; /* File permissions */
96 int numhist; /* Number of historical logs to keep */
97 size_t maxsize; /* Maximum log size */
98 int maxage; /* Hours between log trimming */
99 int flags; /* Flags (CE_*) */
100 int signum; /* Signal to send */
101 char pidfile[MAXPATHLEN]; /* File containing PID to signal */
102 char logfile[MAXPATHLEN]; /* Path to log file */
103 };
104
105 int verbose = 0; /* Be verbose */
106 int noaction = 0; /* Take no action */
107 char hostname[MAXHOSTNAMELEN + 1]; /* Hostname, stripped of domain */
108
109 int main(int, char **);
110 int parse(struct conf_entry *, FILE *, size_t *);
111
112 void log_compress(struct conf_entry *, const char *);
113 void log_create(struct conf_entry *);
114 void log_examine(struct conf_entry *, int);
115 void log_trim(struct conf_entry *);
116 void log_trimmed(struct conf_entry *);
117
118 int getsig(const char *);
119 int isnumber(const char *);
120 int parseuserspec(const char *, struct passwd **, struct group **);
121 pid_t readpidfile(const char *);
122 void usage(void);
123
124 /*
125 * Program entry point.
126 */
127 int
128 main(int argc, char **argv)
129 {
130 struct conf_entry log;
131 FILE *fd;
132 char *p, *cfile;
133 int c, force, needroot;
134 size_t lineno;
135
136 force = 0;
137 needroot = 1;
138 cfile = _PATH_NEWSYSLOGCONF;
139
140 gethostname(hostname, sizeof(hostname));
141 hostname[sizeof(hostname) - 1] = '\0';
142
143 /* Truncate domain */
144 if ((p = strchr(hostname, '.')) != NULL)
145 *p = '\0';
146
147 /* Parse command line options */
148 while ((c = getopt(argc, argv, "f:nrvF")) != -1) {
149 switch (c) {
150 case 'f':
151 cfile = optarg;
152 break;
153 case 'n':
154 noaction = 1;
155 verbose = 1;
156 break;
157 case 'r':
158 needroot = 0;
159 break;
160 case 'v':
161 verbose = 1;
162 break;
163 case 'F':
164 force = 1;
165 break;
166 default:
167 usage();
168 /* NOTREACHED */
169 }
170 }
171
172 if (needroot && geteuid() != 0)
173 errx(EXIT_FAILURE, "must be run as root");
174
175 if (strcmp(cfile, "-") == 0)
176 fd = stdin;
177 else if ((fd = fopen(cfile, "rt")) == NULL)
178 err(EXIT_FAILURE, "%s", cfile);
179
180 for (lineno = 0; !parse(&log, fd, &lineno);)
181 log_examine(&log, force);
182
183 if (fd != stdin)
184 fclose(fd);
185
186 exit(EXIT_SUCCESS);
187 /* NOTREACHED */
188 }
189
190 /*
191 * Parse a single line from the configuration file.
192 */
193 int
194 parse(struct conf_entry *log, FILE *fd, size_t *_lineno)
195 {
196 char *line, *q, **ap, *argv[10];
197 struct passwd *pw;
198 struct group *gr;
199 int nf, lineno, i;
200
201 if ((line = fparseln(fd, NULL, _lineno, NULL, 0)) == NULL)
202 return (-1);
203 lineno = (int)*_lineno;
204
205 for (ap = argv, nf = 0; (*ap = strsep(&line, " \t")) != NULL;)
206 if (**ap != '\0') {
207 if (++nf == sizeof(argv) / sizeof(argv[0])) {
208 warnx("config line %d: too many fields",
209 lineno);
210 return (-1);
211 }
212 ap++;
213 }
214
215 if (nf == 0)
216 return (0);
217
218 if (nf < 6)
219 errx(EXIT_FAILURE, "config line %d: too few fields", lineno);
220
221 ap = argv;
222 strlcpy(log->logfile, *ap++, sizeof(log->logfile));
223
224 if (strchr(*ap, ':') != NULL) {
225 if (parseuserspec(*ap++, &pw, &gr)) {
226 warnx("config line %d: unknown user/group", lineno);
227 return (-1);
228 }
229 log->uid = pw->pw_uid;
230 log->gid = gr->gr_gid;
231 if (nf < 7)
232 errx(EXIT_FAILURE, "config line %d: too few fields",
233 lineno);
234 }
235
236 if (sscanf(*ap++, "%o", &i) != 1) {
237 warnx("config line %d: bad permissions", lineno);
238 return (-1);
239 }
240 log->mode = (mode_t)i;
241
242 if (sscanf(*ap++, "%d", &log->numhist) != 1) {
243 warnx("config line %d: bad log count", lineno);
244 return (-1);
245 }
246
247 if (isdigit(**ap))
248 log->maxsize = atoi(*ap);
249 else if (**ap == '*')
250 log->maxsize = (size_t)-1;
251 else {
252 warnx("config line %d: bad log size", lineno);
253 return (-1);
254 }
255 ap++;
256
257 if (isdigit(**ap))
258 log->maxage = atoi(*ap);
259 else if (**ap == '*')
260 log->maxage = -1;
261 else {
262 warnx("config line %d: bad log age", lineno);
263 return (-1);
264 }
265 ap++;
266
267 log->flags = 0;
268 for (q = *ap++; q != NULL && *q != '\0'; q++) {
269 switch (tolower(*q)) {
270 case 'b':
271 log->flags |= CE_BINARY;
272 break;
273 case 'c':
274 log->flags |= CE_CREATE;
275 break;
276 case 'n':
277 log->flags |= CE_NOSIGNAL;
278 break;
279 case 'p':
280 log->flags |= CE_PLAIN0;
281 break;
282 case 'z':
283 log->flags |= CE_COMPRESS;
284 break;
285 case '-':
286 break;
287 default:
288 warnx("config line %d: bad flags", lineno);
289 return (-1);
290 }
291 }
292
293 if (*ap != NULL && **ap == '/')
294 strlcpy(log->pidfile, *ap++, sizeof(log->pidfile));
295 else
296 log->pidfile[0] = '\0';
297
298 if (*ap != NULL && (log->signum = getsig(*ap++)) < 0) {
299 warnx("config line %d: bad signal type", lineno);
300 return (-1);
301 } else
302 log->signum = SIGHUP;
303
304 return (0);
305 }
306
307 /*
308 * Examine a log file. If the trim conditions are met, call log_trim() to
309 * trim the log file.
310 */
311 void
312 log_examine(struct conf_entry *log, int force)
313 {
314 struct stat sb;
315 size_t size;
316 int age;
317 char tmp[MAXPATHLEN];
318 time_t now;
319
320 if (log->logfile[0] == '\0')
321 return;
322
323 PRHDRINFO(("\n%s <%d%s>: ", log->logfile, log->numhist,
324 (log->flags & CE_COMPRESS) != 0 ? "Z" : ""));
325
326 if (stat(log->logfile, &sb) < 0) {
327 if (errno == ENOENT && (log->flags & CE_CREATE) != 0) {
328 PRHDRINFO(("creating; "));
329 if (!noaction)
330 log_create(log);
331 else {
332 PRHDRINFO(("can't proceed with `-n'\n"));
333 return;
334 }
335 if (stat(log->logfile, &sb))
336 err(EXIT_FAILURE, "%s", log->logfile);
337 } else if (errno == ENOENT) {
338 PRHDRINFO(("does not exist --> skip log\n"));
339 return;
340 } else if (errno != 0)
341 err(EXIT_FAILURE, "%s", log->logfile);
342 }
343
344
345 size = ((size_t)sb.st_blocks * S_BLKSIZE) >> 10;
346
347 now = time(NULL);
348 strlcpy(tmp, log->logfile, sizeof(tmp));
349 strlcat(tmp, ".0", sizeof(tmp));
350 if (stat(tmp, &sb) < 0) {
351 strlcat(tmp, ".gz", sizeof(tmp));
352 if (stat(tmp, &sb) < 0)
353 age = -1;
354 else
355 age = (int)(now - sb.st_mtime + 1800) / 3600;
356 } else
357 age = (int)(now - sb.st_mtime + 1800) / 3600;
358
359 if (verbose) {
360 if (log->maxsize != (size_t)-1)
361 PRHDRINFO(("size (Kb): %lu [%lu] ",
362 (u_long)size,
363 (u_long)log->maxsize));
364 if (log->maxage > 0)
365 PRHDRINFO(("age (hr): %d [%d] ", age, log->maxage));
366 }
367
368 /*
369 * Note: if maxage is used as a trim condition, we need at least one
370 * historical log file to determine the `age' of the active log file.
371 */
372 if ((log->maxage > 0 && (age >= log->maxage || age < 0)) ||
373 size >= log->maxsize || force) {
374 PRHDRINFO(("--> trim log\n"));
375 log_trim(log);
376 } else
377 PRHDRINFO(("--> skip log\n"));
378 }
379
380 /*
381 * Trim the specified log file.
382 */
383 void
384 log_trim(struct conf_entry *log)
385 {
386 char file1[MAXPATHLEN], file2[MAXPATHLEN];
387 int i;
388 struct stat st;
389 pid_t pid;
390
391 /* Remove oldest historical log */
392 snprintf(file1, sizeof(file1), "%s.%d", log->logfile, log->numhist - 1);
393
394 PRINFO(("rm -f %s\n", file1));
395 if (!noaction)
396 unlink(file1);
397 strlcat(file1, ".gz", sizeof(file1));
398 PRINFO(("rm -f %s\n", file1));
399 if (!noaction)
400 unlink(file1);
401
402 /* Move down log files */
403 for (i = log->numhist - 1; i != 0; i--) {
404 snprintf(file1, sizeof(file1), "%s.%d", log->logfile, i - 1);
405 snprintf(file2, sizeof(file2), "%s.%d", log->logfile, i);
406
407 if (lstat(file1, &st) != 0) {
408 strlcat(file1, ".gz", sizeof(file1));
409 strlcat(file2, ".gz", sizeof(file2));
410 if (lstat(file1, &st) != 0)
411 continue;
412 }
413
414 PRINFO(("mv %s %s\n", file1, file2));
415 if (!noaction)
416 if (rename(file1, file2))
417 err(EXIT_FAILURE, "%s", file1);
418 PRINFO(("chmod %o %s\n", log->mode, file2));
419 if (!noaction)
420 if (chmod(file2, log->mode))
421 err(EXIT_FAILURE, "%s", file2);
422 PRINFO(("chown %d:%d %s\n", log->uid, log->gid, file2));
423 if (!noaction)
424 if (chown(file2, log->uid, log->gid))
425 err(EXIT_FAILURE, "%s", file2);
426
427 }
428
429 /*
430 * If a historical log file isn't compressed, and 'z' has been
431 * specified, compress it. (This is convenient, but is also needed
432 * if 'p' has been specified.) It should be noted that gzip(1)
433 * preserves file ownership and file mode.
434 */
435 for (i = (log->flags & CE_PLAIN0) != 0; i < log->numhist; i++) {
436 snprintf(file1, sizeof(file1), "%s.%d", log->logfile, i);
437 if (lstat(file1, &st) != 0)
438 continue;
439 snprintf(file2, sizeof(file2), "%s.gz", file1);
440 if (lstat(file2, &st) == 0)
441 continue;
442 log_compress(log, file1);
443 }
444
445 log_trimmed(log);
446
447 if (log->numhist == 0) {
448 PRINFO(("rm -f %s\n", log->logfile));
449 if (!noaction)
450 if (unlink(log->logfile))
451 err(EXIT_FAILURE, "%s", log->logfile);
452 } else {
453 snprintf(file1, sizeof(file1), "%s.0", log->logfile);
454 PRINFO(("mv %s %s\n", log->logfile, file1));
455 if (!noaction)
456 if (rename(log->logfile, file1))
457 err(EXIT_FAILURE, "%s", log->logfile);
458 }
459
460 PRINFO(("(create new log)\n"));
461 log_create(log);
462 log_trimmed(log);
463
464 PRINFO(("chmod %o %s\n", log->mode, log->logfile));
465 if (!noaction)
466 if (chmod(log->logfile, log->mode))
467 err(EXIT_FAILURE, "%s", log->logfile);
468
469 if ((log->flags & CE_NOSIGNAL) == 0) {
470 if (log->pidfile[0] != '\0')
471 pid = readpidfile(log->pidfile);
472 else
473 pid = readpidfile(_PATH_SYSLOGDPID);
474
475 if (pid != (pid_t)-1) {
476 PRINFO(("kill -%s %lu\n", sys_signame[log->signum],
477 (u_long)pid));
478 if (!noaction)
479 if (kill(pid, log->signum))
480 warn("kill");
481 }
482 }
483
484 if ((log->flags & (CE_PLAIN0 | CE_COMPRESS)) == CE_COMPRESS) {
485 snprintf(file1, sizeof(file1), "%s.0", log->logfile);
486 log_compress(log, file1);
487 }
488 }
489
490 /*
491 * Write an entry to the log file recording the fact that it was trimmed.
492 */
493 void
494 log_trimmed(struct conf_entry *log)
495 {
496 FILE *fd;
497 time_t now;
498 char *daytime;
499
500 if ((log->flags & CE_BINARY) != 0)
501 return;
502 PRINFO(("(append rotation notice to %s)\n", log->logfile));
503 if (noaction)
504 return;
505
506 if ((fd = fopen(log->logfile, "at")) == NULL)
507 err(EXIT_FAILURE, "%s", log->logfile);
508
509 now = time(NULL);
510 daytime = ctime(&now) + 4;
511 daytime[15] = '\0';
512
513 fprintf(fd, "%s %s newsyslog[%lu]: log file turned over\n", daytime,
514 hostname, (u_long)getpid());
515 fclose(fd);
516 }
517
518 /*
519 * Create a new log file.
520 */
521 void
522 log_create(struct conf_entry *log)
523 {
524 int fd;
525
526 if (noaction)
527 return;
528
529 if ((fd = creat(log->logfile, log->mode)) < 0)
530 err(EXIT_FAILURE, "%s", log->logfile);
531 if (fchown(fd, log->uid, log->gid) < 0)
532 err(EXIT_FAILURE, "%s", log->logfile);
533 close(fd);
534 }
535
536 /*
537 * Compress a log file. This routine takes an additional string argument:
538 * it is also used to compress historical log files.
539 */
540 void
541 log_compress(struct conf_entry *log, const char *fn)
542 {
543 pid_t pid;
544
545 PRINFO(("gzip %s\n", fn));
546 if (!noaction) {
547 if ((pid = fork()) < 0)
548 err(EXIT_FAILURE, "fork");
549 else if (pid == 0) {
550 execl(_PATH_GZIP, "gzip", "-f", fn, NULL);
551 err(EXIT_FAILURE, _PATH_GZIP);
552 }
553 }
554 }
555
556 /*
557 * Display program usage information.
558 */
559 void
560 usage(void)
561 {
562
563 fprintf(stderr, "usage: newsyslog [-Frv] [-f config-file]\n");
564 exit(EXIT_FAILURE);
565 }
566
567 /*
568 * Return non-zero if a string represents a decimal value.
569 */
570 int
571 isnumber(const char *string)
572 {
573
574 while (isdigit(*string))
575 string++;
576
577 return (*string == '\0');
578 }
579
580 /*
581 * Given a signal name, attempt to find the corresponding signal number.
582 */
583 int
584 getsig(const char *sig)
585 {
586 char *p;
587 int n;
588
589 if (isnumber(sig)) {
590 n = (int)strtol(sig, &p, 0);
591 if (p != '\0' || n < 0 || n >= NSIG)
592 return (-1);
593 return (n);
594 }
595
596 if (strncasecmp(sig, "SIG", 3) == 0)
597 sig += 3;
598 for (n = 1; n < NSIG; n++)
599 if (strcasecmp(sys_signame[n], sig) == 0)
600 return (n);
601 return (-1);
602 }
603
604 /*
605 * Given a path to a PID file, return the PID contained within.
606 */
607 pid_t
608 readpidfile(const char *file)
609 {
610 FILE *fd;
611 char line[BUFSIZ];
612 pid_t pid;
613
614 #ifdef notyet
615 if (file[0] != '/')
616 snprintf(tmp, sizeof(tmp), "%s%s", _PATH_VARRUN, file);
617 else
618 strlcpy(tmp, file, sizeof(tmp));
619 #endif
620
621 if ((fd = fopen(file, "rt")) == NULL) {
622 warn("%s", file);
623 return (-1);
624 }
625
626 if (fgets(line, sizeof(line) - 1, fd) != NULL) {
627 line[sizeof(line) - 1] = '\0';
628 pid = (pid_t)strtol(line, NULL, 0);
629 } else {
630 warnx("unable to read %s", file);
631 pid = (pid_t)-1;
632 }
633
634 fclose(fd);
635 return (pid);
636 }
637
638 /*
639 * Parse a user:group specification.
640 *
641 * XXX This is over the top for newsyslog(1). It should be moved to libutil.
642 */
643 int
644 parseuserspec(const char *name, struct passwd **pw, struct group **gr)
645 {
646 char buf[MAXLOGNAME * 2 + 2], *group;
647
648 strlcpy(buf, name, sizeof(buf));
649 *gr = NULL;
650
651 /*
652 * Before attempting to use '.' as a separator, see if the whole
653 * string resolves as a user name.
654 */
655 if ((*pw = getpwnam(buf)) != NULL) {
656 *gr = getgrgid((*pw)->pw_gid);
657 return (0);
658 }
659
660 /* Split the user and group name. */
661 if ((group = strchr(buf, ':')) != NULL ||
662 (group = strchr(buf, '.')) != NULL)
663 *group++ = '\0';
664
665 if (isnumber(buf))
666 *pw = getpwuid((uid_t)atoi(buf));
667 else
668 *pw = getpwnam(buf);
669
670 /*
671 * Find the group. If a group wasn't specified, use the user's
672 * `natural' group. We get to this point even if no user was found.
673 * This is to allow the caller to get a better idea of what went
674 * wrong, if anything.
675 */
676 if (group == NULL || *group == '\0') {
677 if (*pw == NULL)
678 return (-1);
679 *gr = getgrgid((*pw)->pw_gid);
680 } else if (isnumber(group))
681 *gr = getgrgid((gid_t)atoi(group));
682 else
683 *gr = getgrnam(group);
684
685 return (*pw != NULL && *gr != NULL ? 0 : -1);
686 }
687