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