newsyslog.c revision 1.27 1 /* $NetBSD: newsyslog.c,v 1.27 2000/07/10 02:23:04 assar 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.27 2000/07/10 02:23:04 assar 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): %lu [%lu] ",
350 (u_long)size,
351 (u_long)ent->maxsize));
352 if (ent->maxage > 0)
353 PRINFO((" age (hr): %d [%d] ", modtime, ent->maxage));
354 }
355
356 /*
357 * Note: if maxage is used as a trim condition, we need at least one
358 * historical log file to determine the `age' of the active log file.
359 */
360 if ((ent->maxage > 0 && (modtime >= ent->maxage || modtime < 0)) ||
361 size >= ent->maxsize || force) {
362 PRINFO(("--> trimming log....\n"));
363 log_trim(ent);
364 } else
365 PRINFO(("--> skipping\n"));
366 }
367
368 /*
369 * Trim the specified log file.
370 */
371 void
372 log_trim(struct conf_entry *log)
373 {
374 char file1[MAXPATHLEN], file2[MAXPATHLEN];
375 char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN];
376 int i;
377 struct stat st;
378 pid_t pid;
379
380 /* Remove oldest log */
381 snprintf(file1, sizeof(file1), "%s.%d", log->logfile,
382 log->numhist - 1);
383 strcpy(zfile1, file1);
384 strlcat(zfile1, ".gz", sizeof(zfile1));
385
386 PRINFO(("rm -f %s\n", file1));
387 unlink(file1);
388 PRINFO(("rm -f %s\n", zfile1));
389 unlink(zfile1);
390
391 /* Move down log files. */
392 for (i = log->numhist - 1; i != 0; i--) {
393 strcpy(file2, file1);
394 snprintf(file1, sizeof(file1), "%s.%d", log->logfile, i - 1);
395 strcpy(zfile1, file1);
396 strcpy(zfile2, file2);
397
398 if (lstat(file1, &st) != 0) {
399 strlcat(zfile1, ".gz", sizeof(zfile1));
400 strlcat(zfile2, ".gz", sizeof(zfile2));
401 if (lstat(zfile1, &st) != 0)
402 continue;
403 }
404
405 PRINFO(("mv %s %s\n", zfile1, zfile2));
406 rename(zfile1, zfile2);
407 PRINFO(("chmod %o %s\n", log->mode, zfile2));
408 chmod(zfile2, log->mode);
409 PRINFO(("chown %d.%d %s\n", log->uid, log->gid, zfile2));
410 chown(zfile2, log->uid, log->gid);
411 }
412
413 if ((log->flags & CE_BINARY) == 0)
414 log_trimmed(log);
415
416 if (log->numhist == 0) {
417 PRINFO(("rm %s\n", log->logfile));
418 unlink(log->logfile);
419 } else {
420 PRINFO(("mv %s to %s\n", log->logfile, file1));
421 rename(log->logfile, file1);
422 }
423
424 PRINFO(("Start new log...\n"));
425 log_create(log);
426
427 if ((log->flags & CE_BINARY) == 0)
428 log_trimmed(log);
429
430 PRINFO(("chmod %o %s\n", log->mode, log->logfile));
431 chmod(log->logfile, log->mode);
432
433 if ((log->flags & CE_NOSIGNAL) == 0) {
434 if (log->pidfile[0] != '\0')
435 pid = readpidfile(log->pidfile);
436 else
437 pid = readpidfile(_PATH_SYSLOGDPID);
438
439 if (pid != (pid_t)-1) {
440 PRINFO(("kill -%s %d\n", sys_signame[log->signum],
441 pid));
442 if (kill(pid, log->signum))
443 warn("warning - could not signal daemon");
444 }
445 }
446
447 if ((log->flags & CE_COMPACT) != 0) {
448 PRINFO(("gzip %s.0\n", log->logfile));
449
450 if ((pid = fork()) < 0)
451 err(EXIT_FAILURE, "fork");
452 else if (pid == 0) {
453 snprintf(file1, sizeof(file1), "%s.0", log->logfile);
454 execl(_PATH_GZIP, "gzip", "-f", file1, NULL);
455 err(EXIT_FAILURE, _PATH_GZIP);
456 }
457 }
458 }
459
460 /*
461 * Write an entry to the log file recording the fact that it was trimmed.
462 */
463 void
464 log_trimmed(struct conf_entry *log)
465 {
466 FILE *fd;
467 time_t now;
468 char *daytime;
469
470 if ((fd = fopen(log->logfile, "at")) == NULL)
471 err(EXIT_FAILURE, "%s", log->logfile);
472
473 now = time(NULL);
474 daytime = ctime(&now) + 4;
475 daytime[15] = '\0';
476
477 fprintf(fd, "%s %s newsyslog[%ld]: log file turned over\n", daytime,
478 hostname, (u_long)getpid());
479 fclose(fd);
480 }
481
482 /*
483 * Create a new log file.
484 */
485 void
486 log_create(struct conf_entry *ent)
487 {
488 int fd;
489
490 if ((fd = creat(ent->logfile, ent->mode)) < 0)
491 err(EXIT_FAILURE, "%s", ent->logfile);
492 if (fchown(fd, ent->uid, ent->gid) < 0)
493 err(EXIT_FAILURE, "%s", ent->logfile);
494 if (close(fd) < 0)
495 err(EXIT_FAILURE, "%s", ent->logfile);
496 }
497
498 /*
499 * Display program usage information.
500 */
501 void
502 usage(void)
503 {
504
505 fprintf(stderr, "usage: newsyslog [-Frv] [-f config-file]\n");
506 exit(EXIT_FAILURE);
507 }
508
509 /*
510 * Return non-zero if a string represents a decimal value.
511 */
512 int
513 isnumber(const char *string)
514 {
515
516 while (isdigit(*string))
517 string++;
518
519 return (*string == '\0');
520 }
521
522 /*
523 * Given a signal name, attempt to find the corresponding signal number.
524 */
525 int
526 getsig(const char *sig)
527 {
528 char *p;
529 int n;
530
531 if (isnumber(sig)) {
532 n = (int)strtol(sig, &p, 0);
533 if (p != '\0' || (unsigned)n >= NSIG)
534 return (-1);
535 return (n);
536 }
537
538 if (strncasecmp(sig, "sig", 3) == 0)
539 sig += 3;
540 for (n = 1; n < NSIG; n++)
541 if (strcasecmp(sys_signame[n], sig) == 0)
542 return (n);
543 return (-1);
544 }
545
546 /*
547 * Given a path to a PID file, return the PID contained within.
548 */
549 pid_t
550 readpidfile(const char *file)
551 {
552 FILE *fd;
553 char line[BUFSIZ];
554 pid_t pid;
555
556 if ((fd = fopen(file, "rt")) == NULL) {
557 warn("%s", file);
558 return (-1);
559 }
560
561 if (fgets(line, sizeof(line) - 1, fd) != NULL) {
562 line[sizeof(line) - 1] = '\0';
563 pid = (pid_t)strtol(line, NULL, 0);
564 }
565
566 fclose(fd);
567 return (pid);
568 }
569
570 /*
571 * Parse a user:group specification.
572 *
573 * XXX This is over the top for newsyslog(1). It should be moved to libutil.
574 */
575 int
576 parseuserspec(const char *name, struct passwd **pw, struct group **gr)
577 {
578 char buf[MAXLOGNAME * 2 + 2], *group;
579
580 strlcpy(buf, name, sizeof(buf));
581 *gr = NULL;
582
583 /*
584 * Before attempting to use '.' as a separator, see if the whole
585 * string resolves as a user name or UID.
586 */
587 if ((*pw = getpwnam(buf)) != NULL) {
588 *gr = getgrgid((*pw)->pw_gid);
589 return (0);
590 }
591
592 /* Split the user and group name. */
593 if ((group = strchr(buf, ':')) != NULL ||
594 (group = strchr(buf, '.')) != NULL)
595 *group++ = '\0';
596
597 if (isnumber(buf))
598 *pw = getpwuid((uid_t)atoi(buf));
599 else
600 *pw = getpwnam(buf);
601
602 /*
603 * Find the group. If a group wasn't specified, use the user's
604 * `natural' group. We get to this point even if no user was found.
605 * This is to allow the caller to get a better idea of what went
606 * wrong, if anything.
607 */
608 if (group == NULL || *group == '\0') {
609 if (*pw == NULL)
610 return (-1);
611 *gr = getgrgid((*pw)->pw_gid);
612 } else if (isnumber(group))
613 *gr = getgrgid((gid_t)atoi(group));
614 else
615 *gr = getgrnam(group);
616
617 return (*gr != NULL ? 0 : -1);
618 }
619