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