periodic - Don't include timestamps in e-mail output by default.
[dragonfly.git] / usr.sbin / newsyslog / newsyslog.c
blob52dfdbc14d77dfeb1b6bed0328d512ba43a6071b
1 /*-
2 * ------+---------+---------+-------- + --------+---------+---------+---------*
3 * This file includes significant modifications done by:
4 * Copyright (c) 2003, 2004 - Garance Alistair Drosehn <gad@FreeBSD.org>.
5 * All rights reserved.
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.
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.
28 * ------+---------+---------+-------- + --------+---------+---------+---------*
32 * This file contains changes from the Open Software Foundation.
36 * Copyright 1988, 1989 by the Massachusetts Institute of Technology
38 * Permission to use, copy, modify, and distribute this software and its
39 * documentation for any purpose and without fee is hereby granted, provided
40 * that the above copyright notice appear in all copies and that both that
41 * copyright notice and this permission notice appear in supporting
42 * documentation, 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 of the
44 * software without specific, written prior permission. M.I.T. and the M.I.T.
45 * S.I.P.B. make no representations about the suitability of this software
46 * for any purpose. It is provided "as is" without express or implied
47 * warranty.
49 * $FreeBSD: src/usr.sbin/newsyslog/newsyslog.c,v 1.106 2006/07/21 22:13:06 sobomax Exp $
50 * $DragonFly: src/usr.sbin/newsyslog/newsyslog.c,v 1.6 2007/05/12 08:52:00 swildner Exp $
54 * newsyslog - roll over selected logs at the appropriate time, keeping the a
55 * specified number of backup files around.
58 #define OSF
59 #ifndef COMPRESS_POSTFIX
60 #define COMPRESS_POSTFIX ".gz"
61 #endif
62 #ifndef BZCOMPRESS_POSTFIX
63 #define BZCOMPRESS_POSTFIX ".bz2"
64 #endif
66 #include <sys/param.h>
67 #include <sys/queue.h>
68 #include <sys/stat.h>
69 #include <sys/wait.h>
71 #include <ctype.h>
72 #include <err.h>
73 #include <errno.h>
74 #include <fcntl.h>
75 #include <fnmatch.h>
76 #include <glob.h>
77 #include <grp.h>
78 #include <paths.h>
79 #include <pwd.h>
80 #include <signal.h>
81 #include <stdio.h>
82 #include <stdlib.h>
83 #include <string.h>
84 #include <time.h>
85 #include <unistd.h>
87 #include "pathnames.h"
88 #include "extern.h"
91 * Bit-values for the 'flags' parsed from a config-file entry.
93 #define CE_COMPACT 0x0001 /* Compact the achived log files with gzip. */
94 #define CE_BZCOMPACT 0x0002 /* Compact the achived log files with bzip2. */
95 #define CE_BINARY 0x0008 /* Logfile is in binary, do not add status */
96 /* messages to logfile(s) when rotating. */
97 #define CE_NOSIGNAL 0x0010 /* There is no process to signal when */
98 /* trimming this file. */
99 #define CE_TRIMAT 0x0020 /* trim file at a specific time. */
100 #define CE_GLOB 0x0040 /* name of the log is file name pattern. */
101 #define CE_SIGNALGROUP 0x0080 /* Signal a process-group instead of a single */
102 /* process when trimming this file. */
103 #define CE_CREATE 0x0100 /* Create the log file if it does not exist. */
104 #define CE_NODUMP 0x0200 /* Set 'nodump' on newly created log file. */
106 #define MIN_PID 5 /* Don't touch pids lower than this */
107 #define MAX_PID 99999 /* was lower, see /usr/include/sys/proc.h */
109 #define kbytes(size) (((size) + 1023) >> 10)
111 #define DEFAULT_MARKER "<default>"
112 #define DEBUG_MARKER "<debug>"
114 struct conf_entry {
115 char *log; /* Name of the log */
116 char *pid_file; /* PID file */
117 char *r_reason; /* The reason this file is being rotated */
118 int firstcreate; /* Creating log for the first time (-C). */
119 int rotate; /* Non-zero if this file should be rotated */
120 int fsize; /* size found for the log file */
121 uid_t uid; /* Owner of log */
122 gid_t gid; /* Group of log */
123 int numlogs; /* Number of logs to keep */
124 int trsize; /* Size cutoff to trigger trimming the log */
125 int hours; /* Hours between log trimming */
126 struct ptime_data *trim_at; /* Specific time to do trimming */
127 unsigned int permissions; /* File permissions on the log */
128 int flags; /* CE_COMPACT, CE_BZCOMPACT, CE_BINARY */
129 int sig; /* Signal to send */
130 int def_cfg; /* Using the <default> rule for this file */
131 struct conf_entry *next;/* Linked list pointer */
134 struct sigwork_entry {
135 SLIST_ENTRY(sigwork_entry) sw_nextp;
136 int sw_signum; /* the signal to send */
137 int sw_pidok; /* true if pid value is valid */
138 pid_t sw_pid; /* the process id from the PID file */
139 const char *sw_pidtype; /* "daemon" or "process group" */
140 char sw_fname[1]; /* file the PID was read from */
143 struct zipwork_entry {
144 SLIST_ENTRY(zipwork_entry) zw_nextp;
145 const struct conf_entry *zw_conf; /* for chown/perm/flag info */
146 const struct sigwork_entry *zw_swork; /* to know success of signal */
147 int zw_fsize; /* size of the file to compress */
148 char zw_fname[1]; /* the file to compress */
151 typedef enum {
152 FREE_ENT, KEEP_ENT
153 } fk_entry;
155 SLIST_HEAD(swlisthead, sigwork_entry) swhead = SLIST_HEAD_INITIALIZER(swhead);
156 SLIST_HEAD(zwlisthead, zipwork_entry) zwhead = SLIST_HEAD_INITIALIZER(zwhead);
158 int dbg_at_times; /* -D Show details of 'trim_at' code */
160 int archtodir = 0; /* Archive old logfiles to other directory */
161 int createlogs; /* Create (non-GLOB) logfiles which do not */
162 /* already exist. 1=='for entries with */
163 /* C flag', 2=='for all entries'. */
164 int verbose = 0; /* Print out what's going on */
165 int needroot = 1; /* Root privs are necessary */
166 int noaction = 0; /* Don't do anything, just show it */
167 int norotate = 0; /* Don't rotate */
168 int nosignal; /* Do not send any signals */
169 int force = 0; /* Force the trim no matter what */
170 int rotatereq = 0; /* -R = Always rotate the file(s) as given */
171 /* on the command (this also requires */
172 /* that a list of files *are* given on */
173 /* the run command). */
174 char *requestor; /* The name given on a -R request */
175 char *archdirname; /* Directory path to old logfiles archive */
176 char *destdir = NULL; /* Directory to treat at root for logs */
177 const char *conf; /* Configuration file to use */
179 struct ptime_data *dbg_timenow; /* A "timenow" value set via -D option */
180 struct ptime_data *timenow; /* The time to use for checking at-fields */
182 #define DAYTIME_LEN 16
183 char daytime[DAYTIME_LEN]; /* The current time in human readable form,
184 * used for rotation-tracking messages. */
185 char hostname[MAXHOSTNAMELEN]; /* hostname */
187 static struct conf_entry *get_worklist(char **files);
188 static void parse_file(FILE *cf, const char *cfname, struct conf_entry **work_p,
189 struct conf_entry **glob_p, struct conf_entry **defconf_p);
190 static char *sob(char *p);
191 static char *son(char *p);
192 static int isnumberstr(const char *);
193 static char *missing_field(char *p, char *errline);
194 static void change_attrs(const char *, const struct conf_entry *);
195 static fk_entry do_entry(struct conf_entry *);
196 static fk_entry do_rotate(const struct conf_entry *);
197 static void do_sigwork(struct sigwork_entry *);
198 static void do_zipwork(struct zipwork_entry *);
199 static struct sigwork_entry *
200 save_sigwork(const struct conf_entry *);
201 static struct zipwork_entry *
202 save_zipwork(const struct conf_entry *, const struct
203 sigwork_entry *, int, const char *);
204 static void set_swpid(struct sigwork_entry *, const struct conf_entry *);
205 static int sizefile(const char *);
206 static void expand_globs(struct conf_entry **work_p,
207 struct conf_entry **glob_p);
208 static void free_clist(struct conf_entry **firstent);
209 static void free_entry(struct conf_entry *ent);
210 static struct conf_entry *init_entry(const char *fname,
211 struct conf_entry *src_entry);
212 static void parse_args(int argc, char **argv);
213 static int parse_doption(const char *doption);
214 static void usage(void);
215 static int log_trim(const char *logname, const struct conf_entry *log_ent);
216 static int age_old_log(char *file);
217 static void savelog(char *from, char *to);
218 static void createdir(const struct conf_entry *ent, char *dirpart);
219 static void createlog(const struct conf_entry *ent);
222 * All the following take a parameter of 'int', but expect values in the
223 * range of unsigned char. Define wrappers which take values of type 'char',
224 * whether signed or unsigned, and ensure they end up in the right range.
226 #define isdigitch(Anychar) isdigit((u_char)(Anychar))
227 #define isprintch(Anychar) isprint((u_char)(Anychar))
228 #define isspacech(Anychar) isspace((u_char)(Anychar))
229 #define tolowerch(Anychar) tolower((u_char)(Anychar))
232 main(int argc, char **argv)
234 fk_entry free_or_keep;
235 struct conf_entry *p, *q;
236 struct sigwork_entry *stmp;
237 struct zipwork_entry *ztmp;
239 SLIST_INIT(&swhead);
240 SLIST_INIT(&zwhead);
242 parse_args(argc, argv);
243 argc -= optind;
244 argv += optind;
246 if (needroot && getuid() && geteuid())
247 errx(1, "must have root privs");
248 p = q = get_worklist(argv);
251 * Rotate all the files which need to be rotated. Note that
252 * some users have *hundreds* of entries in newsyslog.conf!
254 while (p) {
255 free_or_keep = do_entry(p);
256 p = p->next;
257 if (free_or_keep == FREE_ENT)
258 free_entry(q);
259 q = p;
263 * Send signals to any processes which need a signal to tell
264 * them to close and re-open the log file(s) we have rotated.
265 * Note that zipwork_entries include pointers to these
266 * sigwork_entry's, so we can not free the entries here.
268 if (!SLIST_EMPTY(&swhead)) {
269 if (noaction || verbose)
270 printf("Signal all daemon process(es)...\n");
271 SLIST_FOREACH(stmp, &swhead, sw_nextp)
272 do_sigwork(stmp);
273 if (noaction)
274 printf("\tsleep 10\n");
275 else {
276 if (verbose)
277 printf("Pause 10 seconds to allow daemon(s)"
278 " to close log file(s)\n");
279 sleep(10);
283 * Compress all files that we're expected to compress, now
284 * that all processes should have closed the files which
285 * have been rotated.
287 if (!SLIST_EMPTY(&zwhead)) {
288 if (noaction || verbose)
289 printf("Compress all rotated log file(s)...\n");
290 while (!SLIST_EMPTY(&zwhead)) {
291 ztmp = SLIST_FIRST(&zwhead);
292 do_zipwork(ztmp);
293 SLIST_REMOVE_HEAD(&zwhead, zw_nextp);
294 free(ztmp);
297 /* Now free all the sigwork entries. */
298 while (!SLIST_EMPTY(&swhead)) {
299 stmp = SLIST_FIRST(&swhead);
300 SLIST_REMOVE_HEAD(&swhead, sw_nextp);
301 free(stmp);
304 while (wait(NULL) > 0 || errno == EINTR)
306 return (0);
309 static struct conf_entry *
310 init_entry(const char *fname, struct conf_entry *src_entry)
312 struct conf_entry *tempwork;
314 if (verbose > 4)
315 printf("\t--> [creating entry for %s]\n", fname);
317 tempwork = malloc(sizeof(struct conf_entry));
318 if (tempwork == NULL)
319 err(1, "malloc of conf_entry for %s", fname);
321 if (destdir == NULL || fname[0] != '/')
322 tempwork->log = strdup(fname);
323 else
324 asprintf(&tempwork->log, "%s%s", destdir, fname);
325 if (tempwork->log == NULL)
326 err(1, "strdup for %s", fname);
328 if (src_entry != NULL) {
329 tempwork->pid_file = NULL;
330 if (src_entry->pid_file)
331 tempwork->pid_file = strdup(src_entry->pid_file);
332 tempwork->r_reason = NULL;
333 tempwork->firstcreate = 0;
334 tempwork->rotate = 0;
335 tempwork->fsize = -1;
336 tempwork->uid = src_entry->uid;
337 tempwork->gid = src_entry->gid;
338 tempwork->numlogs = src_entry->numlogs;
339 tempwork->trsize = src_entry->trsize;
340 tempwork->hours = src_entry->hours;
341 tempwork->trim_at = NULL;
342 if (src_entry->trim_at != NULL)
343 tempwork->trim_at = ptime_init(src_entry->trim_at);
344 tempwork->permissions = src_entry->permissions;
345 tempwork->flags = src_entry->flags;
346 tempwork->sig = src_entry->sig;
347 tempwork->def_cfg = src_entry->def_cfg;
348 } else {
349 /* Initialize as a "do-nothing" entry */
350 tempwork->pid_file = NULL;
351 tempwork->r_reason = NULL;
352 tempwork->firstcreate = 0;
353 tempwork->rotate = 0;
354 tempwork->fsize = -1;
355 tempwork->uid = (uid_t)-1;
356 tempwork->gid = (gid_t)-1;
357 tempwork->numlogs = 1;
358 tempwork->trsize = -1;
359 tempwork->hours = -1;
360 tempwork->trim_at = NULL;
361 tempwork->permissions = 0;
362 tempwork->flags = 0;
363 tempwork->sig = SIGHUP;
364 tempwork->def_cfg = 0;
366 tempwork->next = NULL;
368 return (tempwork);
371 static void
372 free_entry(struct conf_entry *ent)
375 if (ent == NULL)
376 return;
378 if (ent->log != NULL) {
379 if (verbose > 4)
380 printf("\t--> [freeing entry for %s]\n", ent->log);
381 free(ent->log);
382 ent->log = NULL;
385 if (ent->pid_file != NULL) {
386 free(ent->pid_file);
387 ent->pid_file = NULL;
390 if (ent->r_reason != NULL) {
391 free(ent->r_reason);
392 ent->r_reason = NULL;
395 if (ent->trim_at != NULL) {
396 ptime_free(ent->trim_at);
397 ent->trim_at = NULL;
400 free(ent);
403 static void
404 free_clist(struct conf_entry **firstent)
406 struct conf_entry *ent, *nextent;
408 if (firstent == NULL)
409 return; /* There is nothing to do. */
411 ent = *firstent;
412 firstent = NULL;
414 while (ent) {
415 nextent = ent->next;
416 free_entry(ent);
417 ent = nextent;
421 static fk_entry
422 do_entry(struct conf_entry * ent)
424 #define REASON_MAX 80
425 int modtime;
426 fk_entry free_or_keep;
427 double diffsecs;
428 char temp_reason[REASON_MAX];
430 free_or_keep = FREE_ENT;
431 if (verbose) {
432 if (ent->flags & CE_COMPACT)
433 printf("%s <%dZ>: ", ent->log, ent->numlogs);
434 else if (ent->flags & CE_BZCOMPACT)
435 printf("%s <%dJ>: ", ent->log, ent->numlogs);
436 else
437 printf("%s <%d>: ", ent->log, ent->numlogs);
439 ent->fsize = sizefile(ent->log);
440 modtime = age_old_log(ent->log);
441 ent->rotate = 0;
442 ent->firstcreate = 0;
443 if (ent->fsize < 0) {
445 * If either the C flag or the -C option was specified,
446 * and if we won't be creating the file, then have the
447 * verbose message include a hint as to why the file
448 * will not be created.
450 temp_reason[0] = '\0';
451 if (createlogs > 1)
452 ent->firstcreate = 1;
453 else if ((ent->flags & CE_CREATE) && createlogs)
454 ent->firstcreate = 1;
455 else if (ent->flags & CE_CREATE)
456 strlcpy(temp_reason, " (no -C option)", REASON_MAX);
457 else if (createlogs)
458 strlcpy(temp_reason, " (no C flag)", REASON_MAX);
460 if (ent->firstcreate) {
461 if (verbose)
462 printf("does not exist -> will create.\n");
463 createlog(ent);
464 } else if (verbose) {
465 printf("does not exist, skipped%s.\n", temp_reason);
467 } else {
468 if (ent->flags & CE_TRIMAT && !force && !rotatereq) {
469 diffsecs = ptimeget_diff(timenow, ent->trim_at);
470 if (diffsecs < 0.0) {
471 /* trim_at is some time in the future. */
472 if (verbose) {
473 ptime_adjust4dst(ent->trim_at,
474 timenow);
475 printf("--> will trim at %s",
476 ptimeget_ctime(ent->trim_at));
478 return (free_or_keep);
479 } else if (diffsecs >= 3600.0) {
481 * trim_at is more than an hour in the past,
482 * so find the next valid trim_at time, and
483 * tell the user what that will be.
485 if (verbose && dbg_at_times)
486 printf("\n\t--> prev trim at %s\t",
487 ptimeget_ctime(ent->trim_at));
488 if (verbose) {
489 ptimeset_nxtime(ent->trim_at);
490 printf("--> will trim at %s",
491 ptimeget_ctime(ent->trim_at));
493 return (free_or_keep);
494 } else if (verbose && noaction && dbg_at_times) {
496 * If we are just debugging at-times, then
497 * a detailed message is helpful. Also
498 * skip "doing" any commands, since they
499 * would all be turned off by no-action.
501 printf("\n\t--> timematch at %s",
502 ptimeget_ctime(ent->trim_at));
503 return (free_or_keep);
504 } else if (verbose && ent->hours <= 0) {
505 printf("--> time is up\n");
508 if (verbose && (ent->trsize > 0))
509 printf("size (Kb): %d [%d] ", ent->fsize, ent->trsize);
510 if (verbose && (ent->hours > 0))
511 printf(" age (hr): %d [%d] ", modtime, ent->hours);
514 * Figure out if this logfile needs to be rotated.
516 temp_reason[0] = '\0';
517 if (rotatereq) {
518 ent->rotate = 1;
519 snprintf(temp_reason, REASON_MAX, " due to -R from %s",
520 requestor);
521 } else if (force) {
522 ent->rotate = 1;
523 snprintf(temp_reason, REASON_MAX, " due to -F request");
524 } else if ((ent->trsize > 0) && (ent->fsize >= ent->trsize)) {
525 ent->rotate = 1;
526 snprintf(temp_reason, REASON_MAX, " due to size>%dK",
527 ent->trsize);
528 } else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) {
529 ent->rotate = 1;
530 } else if ((ent->hours > 0) && ((modtime >= ent->hours) ||
531 (modtime < 0))) {
532 ent->rotate = 1;
536 * If the file needs to be rotated, then rotate it.
538 if (ent->rotate && !norotate) {
539 if (temp_reason[0] != '\0')
540 ent->r_reason = strdup(temp_reason);
541 if (verbose)
542 printf("--> trimming log....\n");
543 if (noaction && !verbose) {
544 if (ent->flags & CE_COMPACT)
545 printf("%s <%dZ>: trimming\n",
546 ent->log, ent->numlogs);
547 else if (ent->flags & CE_BZCOMPACT)
548 printf("%s <%dJ>: trimming\n",
549 ent->log, ent->numlogs);
550 else
551 printf("%s <%d>: trimming\n",
552 ent->log, ent->numlogs);
554 free_or_keep = do_rotate(ent);
555 } else {
556 if (verbose)
557 printf("--> skipping\n");
560 return (free_or_keep);
561 #undef REASON_MAX
564 static void
565 parse_args(int argc, char **argv)
567 int ch;
568 char *p;
570 timenow = ptime_init(NULL);
571 ptimeset_time(timenow, time(NULL));
572 strlcpy(daytime, ptimeget_ctime(timenow) + 4, DAYTIME_LEN);
574 /* Let's get our hostname */
575 gethostname(hostname, sizeof(hostname));
577 /* Truncate domain */
578 if ((p = strchr(hostname, '.')) != NULL)
579 *p = '\0';
581 /* Parse command line options. */
582 while ((ch = getopt(argc, argv, "a:d:f:nrsvCD:FNR:")) != -1)
583 switch (ch) {
584 case 'a':
585 archtodir++;
586 archdirname = optarg;
587 break;
588 case 'd':
589 destdir = optarg;
590 break;
591 case 'f':
592 conf = optarg;
593 break;
594 case 'n':
595 noaction++;
596 break;
597 case 'r':
598 needroot = 0;
599 break;
600 case 's':
601 nosignal = 1;
602 break;
603 case 'v':
604 verbose++;
605 break;
606 case 'C':
607 /* Useful for things like rc.diskless... */
608 createlogs++;
609 break;
610 case 'D':
612 * Set some debugging option. The specific option
613 * depends on the value of optarg. These options
614 * may come and go without notice or documentation.
616 if (parse_doption(optarg))
617 break;
618 usage();
619 /* NOTREACHED */
620 case 'F':
621 force++;
622 break;
623 case 'N':
624 norotate++;
625 break;
626 case 'R':
627 rotatereq++;
628 requestor = strdup(optarg);
629 break;
630 case 'm': /* Used by OpenBSD for "monitor mode" */
631 default:
632 usage();
633 /* NOTREACHED */
636 if (force && norotate) {
637 warnx("Only one of -F and -N may be specified.");
638 usage();
639 /* NOTREACHED */
642 if (rotatereq) {
643 if (optind == argc) {
644 warnx("At least one filename must be given when -R is specified.");
645 usage();
646 /* NOTREACHED */
648 /* Make sure "requestor" value is safe for a syslog message. */
649 for (p = requestor; *p != '\0'; p++) {
650 if (!isprintch(*p) && (*p != '\t'))
651 *p = '.';
655 if (dbg_timenow) {
657 * Note that the 'daytime' variable is not changed.
658 * That is only used in messages that track when a
659 * logfile is rotated, and if a file *is* rotated,
660 * then it will still rotated at the "real now" time.
662 ptime_free(timenow);
663 timenow = dbg_timenow;
664 fprintf(stderr, "Debug: Running as if TimeNow is %s",
665 ptimeget_ctime(dbg_timenow));
671 * These debugging options are mainly meant for developer use, such
672 * as writing regression-tests. They would not be needed by users
673 * during normal operation of newsyslog...
675 static int
676 parse_doption(const char *doption)
678 const char TN[] = "TN=";
679 int res;
681 if (strncmp(doption, TN, sizeof(TN) - 1) == 0) {
683 * The "TimeNow" debugging option. This might be off
684 * by an hour when crossing a timezone change.
686 dbg_timenow = ptime_init(NULL);
687 res = ptime_relparse(dbg_timenow, PTM_PARSE_ISO8601,
688 time(NULL), doption + sizeof(TN) - 1);
689 if (res == -2) {
690 warnx("Non-existent time specified on -D %s", doption);
691 return (0); /* failure */
692 } else if (res < 0) {
693 warnx("Malformed time given on -D %s", doption);
694 return (0); /* failure */
696 return (1); /* successfully parsed */
700 if (strcmp(doption, "ats") == 0) {
701 dbg_at_times++;
702 return (1); /* successfully parsed */
705 /* XXX - This check could probably be dropped. */
706 if ((strcmp(doption, "neworder") == 0) || (strcmp(doption, "oldorder")
707 == 0)) {
708 warnx("NOTE: newsyslog always uses 'neworder'.");
709 return (1); /* successfully parsed */
712 warnx("Unknown -D (debug) option: '%s'", doption);
713 return (0); /* failure */
716 static void
717 usage(void)
720 fprintf(stderr,
721 "usage: newsyslog [-CFNnrsv] [-a directory] [-d directory] [-f config-file]\n"
722 " [ [-R requestor] filename ... ]\n");
723 exit(1);
727 * Parse a configuration file and return a linked list of all the logs
728 * which should be processed.
730 static struct conf_entry *
731 get_worklist(char **files)
733 FILE *f;
734 const char *fname;
735 char **given;
736 struct conf_entry *defconf, *dupent, *ent, *firstnew;
737 struct conf_entry *globlist, *lastnew, *worklist;
738 int gmatch, fnres;
740 defconf = globlist = worklist = NULL;
742 fname = conf;
743 if (fname == NULL)
744 fname = _PATH_CONF;
746 if (strcmp(fname, "-") != 0)
747 f = fopen(fname, "r");
748 else {
749 f = stdin;
750 fname = "<stdin>";
752 if (!f)
753 err(1, "%s", fname);
755 parse_file(f, fname, &worklist, &globlist, &defconf);
756 fclose(f);
759 * All config-file information has been read in and turned into
760 * a worklist and a globlist. If there were no specific files
761 * given on the run command, then the only thing left to do is to
762 * call a routine which finds all files matched by the globlist
763 * and adds them to the worklist. Then return the worklist.
765 if (*files == NULL) {
766 expand_globs(&worklist, &globlist);
767 free_clist(&globlist);
768 if (defconf != NULL)
769 free_entry(defconf);
770 return (worklist);
771 /* NOTREACHED */
775 * If newsyslog was given a specific list of files to process,
776 * it may be that some of those files were not listed in any
777 * config file. Those unlisted files should get the default
778 * rotation action. First, create the default-rotation action
779 * if none was found in a system config file.
781 if (defconf == NULL) {
782 defconf = init_entry(DEFAULT_MARKER, NULL);
783 defconf->numlogs = 3;
784 defconf->trsize = 50;
785 defconf->permissions = S_IRUSR|S_IWUSR;
789 * If newsyslog was run with a list of specific filenames,
790 * then create a new worklist which has only those files in
791 * it, picking up the rotation-rules for those files from
792 * the original worklist.
794 * XXX - Note that this will copy multiple rules for a single
795 * logfile, if multiple entries are an exact match for
796 * that file. That matches the historic behavior, but do
797 * we want to continue to allow it? If so, it should
798 * probably be handled more intelligently.
800 firstnew = lastnew = NULL;
801 for (given = files; *given; ++given) {
803 * First try to find exact-matches for this given file.
805 gmatch = 0;
806 for (ent = worklist; ent; ent = ent->next) {
807 if (strcmp(ent->log, *given) == 0) {
808 gmatch++;
809 dupent = init_entry(*given, ent);
810 if (!firstnew)
811 firstnew = dupent;
812 else
813 lastnew->next = dupent;
814 lastnew = dupent;
817 if (gmatch) {
818 if (verbose > 2)
819 printf("\t+ Matched entry %s\n", *given);
820 continue;
824 * There was no exact-match for this given file, so look
825 * for a "glob" entry which does match.
827 gmatch = 0;
828 if (verbose > 2 && globlist != NULL)
829 printf("\t+ Checking globs for %s\n", *given);
830 for (ent = globlist; ent; ent = ent->next) {
831 fnres = fnmatch(ent->log, *given, FNM_PATHNAME);
832 if (verbose > 2)
833 printf("\t+ = %d for pattern %s\n", fnres,
834 ent->log);
835 if (fnres == 0) {
836 gmatch++;
837 dupent = init_entry(*given, ent);
838 if (!firstnew)
839 firstnew = dupent;
840 else
841 lastnew->next = dupent;
842 lastnew = dupent;
843 /* This new entry is not a glob! */
844 dupent->flags &= ~CE_GLOB;
845 /* Only allow a match to one glob-entry */
846 break;
849 if (gmatch) {
850 if (verbose > 2)
851 printf("\t+ Matched %s via %s\n", *given,
852 ent->log);
853 continue;
857 * This given file was not found in any config file, so
858 * add a worklist item based on the default entry.
860 if (verbose > 2)
861 printf("\t+ No entry matched %s (will use %s)\n",
862 *given, DEFAULT_MARKER);
863 dupent = init_entry(*given, defconf);
864 if (!firstnew)
865 firstnew = dupent;
866 else
867 lastnew->next = dupent;
868 /* Mark that it was *not* found in a config file */
869 dupent->def_cfg = 1;
870 lastnew = dupent;
874 * Free all the entries in the original work list, the list of
875 * glob entries, and the default entry.
877 free_clist(&worklist);
878 free_clist(&globlist);
879 free_entry(defconf);
881 /* And finally, return a worklist which matches the given files. */
882 return (firstnew);
886 * Expand the list of entries with filename patterns, and add all files
887 * which match those glob-entries onto the worklist.
889 static void
890 expand_globs(struct conf_entry **work_p, struct conf_entry **glob_p)
892 int gmatch, gres;
893 size_t i;
894 char *mfname;
895 struct conf_entry *dupent, *ent, *firstmatch, *globent;
896 struct conf_entry *lastmatch;
897 glob_t pglob;
898 struct stat st_fm;
900 if ((glob_p == NULL) || (*glob_p == NULL))
901 return; /* There is nothing to do. */
904 * The worklist contains all fully-specified (non-GLOB) names.
906 * Now expand the list of filename-pattern (GLOB) entries into
907 * a second list, which (by definition) will only match files
908 * that already exist. Do not add a glob-related entry for any
909 * file which already exists in the fully-specified list.
911 firstmatch = lastmatch = NULL;
912 for (globent = *glob_p; globent; globent = globent->next) {
914 gres = glob(globent->log, GLOB_NOCHECK, NULL, &pglob);
915 if (gres != 0) {
916 warn("cannot expand pattern (%d): %s", gres,
917 globent->log);
918 continue;
921 if (verbose > 2)
922 printf("\t+ Expanding pattern %s\n", globent->log);
923 for (i = 0; i < pglob.gl_matchc; i++) {
924 mfname = pglob.gl_pathv[i];
926 /* See if this file already has a specific entry. */
927 gmatch = 0;
928 for (ent = *work_p; ent; ent = ent->next) {
929 if (strcmp(mfname, ent->log) == 0) {
930 gmatch++;
931 break;
934 if (gmatch)
935 continue;
937 /* Make sure the named matched is a file. */
938 gres = lstat(mfname, &st_fm);
939 if (gres != 0) {
940 /* Error on a file that glob() matched?!? */
941 warn("Skipping %s - lstat() error", mfname);
942 continue;
944 if (!S_ISREG(st_fm.st_mode)) {
945 /* We only rotate files! */
946 if (verbose > 2)
947 printf("\t+ . skipping %s (!file)\n",
948 mfname);
949 continue;
952 if (verbose > 2)
953 printf("\t+ . add file %s\n", mfname);
954 dupent = init_entry(mfname, globent);
955 if (!firstmatch)
956 firstmatch = dupent;
957 else
958 lastmatch->next = dupent;
959 lastmatch = dupent;
960 /* This new entry is not a glob! */
961 dupent->flags &= ~CE_GLOB;
963 globfree(&pglob);
964 if (verbose > 2)
965 printf("\t+ Done with pattern %s\n", globent->log);
968 /* Add the list of matched files to the end of the worklist. */
969 if (!*work_p)
970 *work_p = firstmatch;
971 else {
972 ent = *work_p;
973 while (ent->next)
974 ent = ent->next;
975 ent->next = firstmatch;
981 * Parse a configuration file and update a linked list of all the logs to
982 * process.
984 static void
985 parse_file(FILE *cf, const char *cfname, struct conf_entry **work_p,
986 struct conf_entry **glob_p, struct conf_entry **defconf_p)
988 char line[BUFSIZ], *parse, *q;
989 char *cp, *errline, *group;
990 struct conf_entry *lastglob, *lastwork, *working;
991 struct passwd *pwd;
992 struct group *grp;
993 int eol, ptm_opts, res, special;
996 * XXX - for now, assume that only one config file will be read,
997 * ie, this routine is only called one time.
999 lastglob = lastwork = NULL;
1001 errline = NULL;
1002 while (fgets(line, BUFSIZ, cf)) {
1003 if ((line[0] == '\n') || (line[0] == '#') ||
1004 (strlen(line) == 0))
1005 continue;
1006 if (errline != NULL)
1007 free(errline);
1008 errline = strdup(line);
1009 for (cp = line + 1; *cp != '\0'; cp++) {
1010 if (*cp != '#')
1011 continue;
1012 if (*(cp - 1) == '\\') {
1013 strcpy(cp - 1, cp);
1014 cp--;
1015 continue;
1017 *cp = '\0';
1018 break;
1021 q = parse = missing_field(sob(line), errline);
1022 parse = son(line);
1023 if (!*parse)
1024 errx(1, "malformed line (missing fields):\n%s",
1025 errline);
1026 *parse = '\0';
1029 * Allow people to set debug options via the config file.
1030 * (NOTE: debug optons are undocumented, and may disappear
1031 * at any time, etc).
1033 if (strcasecmp(DEBUG_MARKER, q) == 0) {
1034 q = parse = missing_field(sob(++parse), errline);
1035 parse = son(parse);
1036 if (!*parse)
1037 warnx("debug line specifies no option:\n%s",
1038 errline);
1039 else {
1040 *parse = '\0';
1041 parse_doption(q);
1043 continue;
1046 special = 0;
1047 working = init_entry(q, NULL);
1048 if (strcasecmp(DEFAULT_MARKER, q) == 0) {
1049 special = 1;
1050 if (defconf_p == NULL) {
1051 warnx("Ignoring entry for %s in %s!", q,
1052 cfname);
1053 free_entry(working);
1054 continue;
1055 } else if (*defconf_p != NULL) {
1056 warnx("Ignoring duplicate entry for %s!", q);
1057 free_entry(working);
1058 continue;
1060 *defconf_p = working;
1063 q = parse = missing_field(sob(++parse), errline);
1064 parse = son(parse);
1065 if (!*parse)
1066 errx(1, "malformed line (missing fields):\n%s",
1067 errline);
1068 *parse = '\0';
1069 if ((group = strchr(q, ':')) != NULL ||
1070 (group = strrchr(q, '.')) != NULL) {
1071 *group++ = '\0';
1072 if (*q) {
1073 if (!(isnumberstr(q))) {
1074 if ((pwd = getpwnam(q)) == NULL)
1075 errx(1,
1076 "error in config file; unknown user:\n%s",
1077 errline);
1078 working->uid = pwd->pw_uid;
1079 } else
1080 working->uid = atoi(q);
1081 } else
1082 working->uid = (uid_t)-1;
1084 q = group;
1085 if (*q) {
1086 if (!(isnumberstr(q))) {
1087 if ((grp = getgrnam(q)) == NULL)
1088 errx(1,
1089 "error in config file; unknown group:\n%s",
1090 errline);
1091 working->gid = grp->gr_gid;
1092 } else
1093 working->gid = atoi(q);
1094 } else
1095 working->gid = (gid_t)-1;
1097 q = parse = missing_field(sob(++parse), errline);
1098 parse = son(parse);
1099 if (!*parse)
1100 errx(1, "malformed line (missing fields):\n%s",
1101 errline);
1102 *parse = '\0';
1103 } else {
1104 working->uid = (uid_t)-1;
1105 working->gid = (gid_t)-1;
1108 if (!sscanf(q, "%o", &working->permissions))
1109 errx(1, "error in config file; bad permissions:\n%s",
1110 errline);
1112 q = parse = missing_field(sob(++parse), errline);
1113 parse = son(parse);
1114 if (!*parse)
1115 errx(1, "malformed line (missing fields):\n%s",
1116 errline);
1117 *parse = '\0';
1118 if (!sscanf(q, "%d", &working->numlogs) || working->numlogs < 0)
1119 errx(1, "error in config file; bad value for count of logs to save:\n%s",
1120 errline);
1122 q = parse = missing_field(sob(++parse), errline);
1123 parse = son(parse);
1124 if (!*parse)
1125 errx(1, "malformed line (missing fields):\n%s",
1126 errline);
1127 *parse = '\0';
1128 if (isdigitch(*q))
1129 working->trsize = atoi(q);
1130 else if (strcmp(q, "*") == 0)
1131 working->trsize = -1;
1132 else {
1133 warnx("Invalid value of '%s' for 'size' in line:\n%s",
1134 q, errline);
1135 working->trsize = -1;
1138 working->flags = 0;
1139 q = parse = missing_field(sob(++parse), errline);
1140 parse = son(parse);
1141 eol = !*parse;
1142 *parse = '\0';
1144 char *ep;
1145 u_long ul;
1147 ul = strtoul(q, &ep, 10);
1148 if (ep == q)
1149 working->hours = 0;
1150 else if (*ep == '*')
1151 working->hours = -1;
1152 else if (ul > INT_MAX)
1153 errx(1, "interval is too large:\n%s", errline);
1154 else
1155 working->hours = ul;
1157 if (*ep == '\0' || strcmp(ep, "*") == 0)
1158 goto no_trimat;
1159 if (*ep != '@' && *ep != '$')
1160 errx(1, "malformed interval/at:\n%s", errline);
1162 working->flags |= CE_TRIMAT;
1163 working->trim_at = ptime_init(NULL);
1164 ptm_opts = PTM_PARSE_ISO8601;
1165 if (*ep == '$')
1166 ptm_opts = PTM_PARSE_DWM;
1167 ptm_opts |= PTM_PARSE_MATCHDOM;
1168 res = ptime_relparse(working->trim_at, ptm_opts,
1169 ptimeget_secs(timenow), ep + 1);
1170 if (res == -2)
1171 errx(1, "nonexistent time for 'at' value:\n%s",
1172 errline);
1173 else if (res < 0)
1174 errx(1, "malformed 'at' value:\n%s", errline);
1176 no_trimat:
1178 if (eol)
1179 q = NULL;
1180 else {
1181 q = parse = sob(++parse); /* Optional field */
1182 parse = son(parse);
1183 if (!*parse)
1184 eol = 1;
1185 *parse = '\0';
1188 for (; q && *q && !isspacech(*q); q++) {
1189 switch (tolowerch(*q)) {
1190 case 'b':
1191 working->flags |= CE_BINARY;
1192 break;
1193 case 'c':
1195 * XXX - Ick! Ugly! Remove ASAP!
1196 * We want `c' and `C' for "create". But we
1197 * will temporarily treat `c' as `g', because
1198 * FreeBSD releases <= 4.8 have a typo of
1199 * checking ('G' || 'c') for CE_GLOB.
1201 if (*q == 'c') {
1202 warnx("Assuming 'g' for 'c' in flags for line:\n%s",
1203 errline);
1204 warnx("The 'c' flag will eventually mean 'CREATE'");
1205 working->flags |= CE_GLOB;
1206 break;
1208 working->flags |= CE_CREATE;
1209 break;
1210 case 'd':
1211 working->flags |= CE_NODUMP;
1212 break;
1213 case 'g':
1214 working->flags |= CE_GLOB;
1215 break;
1216 case 'j':
1217 working->flags |= CE_BZCOMPACT;
1218 break;
1219 case 'n':
1220 working->flags |= CE_NOSIGNAL;
1221 break;
1222 case 'u':
1223 working->flags |= CE_SIGNALGROUP;
1224 break;
1225 case 'w':
1226 /* Deprecated flag - keep for compatibility purposes */
1227 break;
1228 case 'z':
1229 working->flags |= CE_COMPACT;
1230 break;
1231 case '-':
1232 break;
1233 case 'f': /* Used by OpenBSD for "CE_FOLLOW" */
1234 case 'm': /* Used by OpenBSD for "CE_MONITOR" */
1235 case 'p': /* Used by NetBSD for "CE_PLAIN0" */
1236 default:
1237 errx(1, "illegal flag in config file -- %c",
1238 *q);
1242 if (eol)
1243 q = NULL;
1244 else {
1245 q = parse = sob(++parse); /* Optional field */
1246 parse = son(parse);
1247 if (!*parse)
1248 eol = 1;
1249 *parse = '\0';
1252 working->pid_file = NULL;
1253 if (q && *q) {
1254 if (*q == '/')
1255 working->pid_file = strdup(q);
1256 else if (isdigit(*q))
1257 goto got_sig;
1258 else
1259 errx(1,
1260 "illegal pid file or signal number in config file:\n%s",
1261 errline);
1263 if (eol)
1264 q = NULL;
1265 else {
1266 q = parse = sob(++parse); /* Optional field */
1267 *(parse = son(parse)) = '\0';
1270 working->sig = SIGHUP;
1271 if (q && *q) {
1272 if (isdigit(*q)) {
1273 got_sig:
1274 working->sig = atoi(q);
1275 } else {
1276 err_sig:
1277 errx(1,
1278 "illegal signal number in config file:\n%s",
1279 errline);
1281 if (working->sig < 1 || working->sig >= NSIG)
1282 goto err_sig;
1286 * Finish figuring out what pid-file to use (if any) in
1287 * later processing if this logfile needs to be rotated.
1289 if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) {
1291 * This config-entry specified 'n' for nosignal,
1292 * see if it also specified an explicit pid_file.
1293 * This would be a pretty pointless combination.
1295 if (working->pid_file != NULL) {
1296 warnx("Ignoring '%s' because flag 'n' was specified in line:\n%s",
1297 working->pid_file, errline);
1298 free(working->pid_file);
1299 working->pid_file = NULL;
1301 } else if (working->pid_file == NULL) {
1303 * This entry did not specify the 'n' flag, which
1304 * means it should signal syslogd unless it had
1305 * specified some other pid-file (and obviously the
1306 * syslog pid-file will not be for a process-group).
1307 * Also, we should only try to notify syslog if we
1308 * are root.
1310 if (working->flags & CE_SIGNALGROUP) {
1311 warnx("Ignoring flag 'U' in line:\n%s",
1312 errline);
1313 working->flags &= ~CE_SIGNALGROUP;
1315 if (needroot)
1316 working->pid_file = strdup(_PATH_SYSLOGPID);
1320 * Add this entry to the appropriate list of entries, unless
1321 * it was some kind of special entry (eg: <default>).
1323 if (special) {
1324 ; /* Do not add to any list */
1325 } else if (working->flags & CE_GLOB) {
1326 if (!*glob_p)
1327 *glob_p = working;
1328 else
1329 lastglob->next = working;
1330 lastglob = working;
1331 } else {
1332 if (!*work_p)
1333 *work_p = working;
1334 else
1335 lastwork->next = working;
1336 lastwork = working;
1339 if (errline != NULL)
1340 free(errline);
1343 static char *
1344 missing_field(char *p, char *errline)
1347 if (!p || !*p)
1348 errx(1, "missing field in config file:\n%s", errline);
1349 return (p);
1352 static fk_entry
1353 do_rotate(const struct conf_entry *ent)
1355 char dirpart[MAXPATHLEN], namepart[MAXPATHLEN];
1356 char file1[MAXPATHLEN], file2[MAXPATHLEN];
1357 char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN];
1358 char jfile1[MAXPATHLEN];
1359 int flags, numlogs_c;
1360 fk_entry free_or_keep;
1361 struct sigwork_entry *swork;
1362 struct stat st;
1364 flags = ent->flags;
1365 free_or_keep = FREE_ENT;
1367 if (archtodir) {
1368 char *p;
1370 /* build complete name of archive directory into dirpart */
1371 if (*archdirname == '/') { /* absolute */
1372 strlcpy(dirpart, archdirname, sizeof(dirpart));
1373 } else { /* relative */
1374 /* get directory part of logfile */
1375 strlcpy(dirpart, ent->log, sizeof(dirpart));
1376 if ((p = strrchr(dirpart, '/')) == NULL)
1377 dirpart[0] = '\0';
1378 else
1379 *(p + 1) = '\0';
1380 strlcat(dirpart, archdirname, sizeof(dirpart));
1383 /* check if archive directory exists, if not, create it */
1384 if (lstat(dirpart, &st))
1385 createdir(ent, dirpart);
1387 /* get filename part of logfile */
1388 if ((p = strrchr(ent->log, '/')) == NULL)
1389 strlcpy(namepart, ent->log, sizeof(namepart));
1390 else
1391 strlcpy(namepart, p + 1, sizeof(namepart));
1393 /* name of oldest log */
1394 snprintf(file1, sizeof(file1), "%s/%s.%d", dirpart,
1395 namepart, ent->numlogs);
1396 snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1397 COMPRESS_POSTFIX);
1398 snprintf(jfile1, sizeof(jfile1), "%s%s", file1,
1399 BZCOMPRESS_POSTFIX);
1400 } else {
1401 /* name of oldest log */
1402 snprintf(file1, sizeof(file1), "%s.%d", ent->log,
1403 ent->numlogs);
1404 snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1405 COMPRESS_POSTFIX);
1406 snprintf(jfile1, sizeof(jfile1), "%s%s", file1,
1407 BZCOMPRESS_POSTFIX);
1410 if (noaction) {
1411 printf("\trm -f %s\n", file1);
1412 printf("\trm -f %s\n", zfile1);
1413 printf("\trm -f %s\n", jfile1);
1414 } else {
1415 unlink(file1);
1416 unlink(zfile1);
1417 unlink(jfile1);
1420 /* Move down log files */
1421 numlogs_c = ent->numlogs; /* copy for countdown */
1422 while (numlogs_c--) {
1424 strlcpy(file2, file1, sizeof(file2));
1426 if (archtodir)
1427 snprintf(file1, sizeof(file1), "%s/%s.%d",
1428 dirpart, namepart, numlogs_c);
1429 else
1430 snprintf(file1, sizeof(file1), "%s.%d", ent->log,
1431 numlogs_c);
1433 strlcpy(zfile1, file1, sizeof(zfile1));
1434 strlcpy(zfile2, file2, sizeof(zfile2));
1435 if (lstat(file1, &st)) {
1436 strlcat(zfile1, COMPRESS_POSTFIX,
1437 sizeof(zfile1));
1438 strlcat(zfile2, COMPRESS_POSTFIX,
1439 sizeof(zfile2));
1440 if (lstat(zfile1, &st)) {
1441 strlcpy(zfile1, file1, sizeof(zfile1));
1442 strlcpy(zfile2, file2, sizeof(zfile2));
1443 strlcat(zfile1, BZCOMPRESS_POSTFIX,
1444 sizeof(zfile1));
1445 strlcat(zfile2, BZCOMPRESS_POSTFIX,
1446 sizeof(zfile2));
1447 if (lstat(zfile1, &st))
1448 continue;
1451 if (noaction)
1452 printf("\tmv %s %s\n", zfile1, zfile2);
1453 else {
1454 /* XXX - Ought to be checking for failure! */
1455 rename(zfile1, zfile2);
1457 change_attrs(zfile2, ent);
1460 if (ent->numlogs > 0) {
1461 if (noaction) {
1463 * Note that savelog() may succeed with using link()
1464 * for the archtodir case, but there is no good way
1465 * of knowing if it will when doing "noaction", so
1466 * here we claim that it will have to do a copy...
1468 if (archtodir)
1469 printf("\tcp %s %s\n", ent->log, file1);
1470 else
1471 printf("\tln %s %s\n", ent->log, file1);
1472 } else {
1473 if (!(flags & CE_BINARY)) {
1474 /* Report the trimming to the old log */
1475 log_trim(ent->log, ent);
1477 savelog(ent->log, file1);
1479 change_attrs(file1, ent);
1482 /* Create the new log file and move it into place */
1483 if (noaction)
1484 printf("Start new log...\n");
1485 createlog(ent);
1488 * Save all signalling and file-compression to be done after log
1489 * files from all entries have been rotated. This way any one
1490 * process will not be sent the same signal multiple times when
1491 * multiple log files had to be rotated.
1493 swork = NULL;
1494 if (ent->pid_file != NULL)
1495 swork = save_sigwork(ent);
1496 if (ent->numlogs > 0 && (flags & (CE_COMPACT | CE_BZCOMPACT))) {
1498 * The zipwork_entry will include a pointer to this
1499 * conf_entry, so the conf_entry should not be freed.
1501 free_or_keep = KEEP_ENT;
1502 save_zipwork(ent, swork, ent->fsize, file1);
1505 return (free_or_keep);
1508 static void
1509 do_sigwork(struct sigwork_entry *swork)
1511 struct sigwork_entry *nextsig;
1512 int kres, secs;
1514 if (!(swork->sw_pidok) || swork->sw_pid == 0)
1515 return; /* no work to do... */
1518 * If nosignal (-s) was specified, then do not signal any process.
1519 * Note that a nosignal request triggers a warning message if the
1520 * rotated logfile needs to be compressed, *unless* -R was also
1521 * specified. We assume that an `-sR' request came from a process
1522 * which writes to the logfile, and as such, we assume that process
1523 * has already made sure the logfile is not presently in use. This
1524 * just sets swork->sw_pidok to a special value, and do_zipwork
1525 * will print any necessary warning(s).
1527 if (nosignal) {
1528 if (!rotatereq)
1529 swork->sw_pidok = -1;
1530 return;
1534 * Compute the pause between consecutive signals. Use a longer
1535 * sleep time if we will be sending two signals to the same
1536 * deamon or process-group.
1538 secs = 0;
1539 nextsig = SLIST_NEXT(swork, sw_nextp);
1540 if (nextsig != NULL) {
1541 if (swork->sw_pid == nextsig->sw_pid)
1542 secs = 10;
1543 else
1544 secs = 1;
1547 if (noaction) {
1548 printf("\tkill -%d %d \t\t# %s\n", swork->sw_signum,
1549 (int)swork->sw_pid, swork->sw_fname);
1550 if (secs > 0)
1551 printf("\tsleep %d\n", secs);
1552 return;
1555 kres = kill(swork->sw_pid, swork->sw_signum);
1556 if (kres != 0) {
1558 * Assume that "no such process" (ESRCH) is something
1559 * to warn about, but is not an error. Presumably the
1560 * process which writes to the rotated log file(s) is
1561 * gone, in which case we should have no problem with
1562 * compressing the rotated log file(s).
1564 if (errno != ESRCH)
1565 swork->sw_pidok = 0;
1566 warn("can't notify %s, pid %d", swork->sw_pidtype,
1567 (int)swork->sw_pid);
1568 } else {
1569 if (verbose)
1570 printf("Notified %s pid %d = %s\n", swork->sw_pidtype,
1571 (int)swork->sw_pid, swork->sw_fname);
1572 if (secs > 0) {
1573 if (verbose)
1574 printf("Pause %d second(s) between signals\n",
1575 secs);
1576 sleep(secs);
1581 static void
1582 do_zipwork(struct zipwork_entry *zwork)
1584 const char *pgm_name, *pgm_path;
1585 int errsav, fcount, zstatus;
1586 pid_t pidzip, wpid;
1587 char zresult[MAXPATHLEN];
1589 pgm_path = NULL;
1590 strlcpy(zresult, zwork->zw_fname, sizeof(zresult));
1591 if (zwork != NULL && zwork->zw_conf != NULL) {
1592 if (zwork->zw_conf->flags & CE_COMPACT) {
1593 pgm_path = _PATH_GZIP;
1594 strlcat(zresult, COMPRESS_POSTFIX, sizeof(zresult));
1595 } else if (zwork->zw_conf->flags & CE_BZCOMPACT) {
1596 pgm_path = _PATH_BZIP2;
1597 strlcat(zresult, BZCOMPRESS_POSTFIX, sizeof(zresult));
1600 if (pgm_path == NULL) {
1601 warnx("invalid entry for %s in do_zipwork", zwork->zw_fname);
1602 return;
1604 pgm_name = strrchr(pgm_path, '/');
1605 if (pgm_name == NULL)
1606 pgm_name = pgm_path;
1607 else
1608 pgm_name++;
1610 if (zwork->zw_swork != NULL && zwork->zw_swork->sw_pidok <= 0) {
1611 warnx(
1612 "log %s not compressed because daemon(s) not notified",
1613 zwork->zw_fname);
1614 change_attrs(zwork->zw_fname, zwork->zw_conf);
1615 return;
1618 if (noaction) {
1619 printf("\t%s %s\n", pgm_name, zwork->zw_fname);
1620 change_attrs(zresult, zwork->zw_conf);
1621 return;
1624 fcount = 1;
1625 pidzip = fork();
1626 while (pidzip < 0) {
1628 * The fork failed. If the failure was due to a temporary
1629 * problem, then wait a short time and try it again.
1631 errsav = errno;
1632 warn("fork() for `%s %s'", pgm_name, zwork->zw_fname);
1633 if (errsav != EAGAIN || fcount > 5)
1634 errx(1, "Exiting...");
1635 sleep(fcount * 12);
1636 fcount++;
1637 pidzip = fork();
1639 if (!pidzip) {
1640 /* The child process executes the compression command */
1641 execl(pgm_path, pgm_path, "-f", zwork->zw_fname, NULL);
1642 err(1, "execl(`%s -f %s')", pgm_path, zwork->zw_fname);
1645 wpid = waitpid(pidzip, &zstatus, 0);
1646 if (wpid == -1) {
1647 /* XXX - should this be a fatal error? */
1648 warn("%s: waitpid(%d)", pgm_path, pidzip);
1649 return;
1651 if (!WIFEXITED(zstatus)) {
1652 warnx("`%s -f %s' did not terminate normally", pgm_name,
1653 zwork->zw_fname);
1654 return;
1656 if (WEXITSTATUS(zstatus)) {
1657 warnx("`%s -f %s' terminated with a non-zero status (%d)",
1658 pgm_name, zwork->zw_fname, WEXITSTATUS(zstatus));
1659 return;
1662 /* Compression was successful, set file attributes on the result. */
1663 change_attrs(zresult, zwork->zw_conf);
1667 * Save information on any process we need to signal. Any single
1668 * process may need to be sent different signal-values for different
1669 * log files, but usually a single signal-value will cause the process
1670 * to close and re-open all of it's log files.
1672 static struct sigwork_entry *
1673 save_sigwork(const struct conf_entry *ent)
1675 struct sigwork_entry *sprev, *stmp;
1676 int ndiff;
1677 size_t tmpsiz;
1679 sprev = NULL;
1680 ndiff = 1;
1681 SLIST_FOREACH(stmp, &swhead, sw_nextp) {
1682 ndiff = strcmp(ent->pid_file, stmp->sw_fname);
1683 if (ndiff > 0)
1684 break;
1685 if (ndiff == 0) {
1686 if (ent->sig == stmp->sw_signum)
1687 break;
1688 if (ent->sig > stmp->sw_signum) {
1689 ndiff = 1;
1690 break;
1693 sprev = stmp;
1695 if (stmp != NULL && ndiff == 0)
1696 return (stmp);
1698 tmpsiz = sizeof(struct sigwork_entry) + strlen(ent->pid_file) + 1;
1699 stmp = malloc(tmpsiz);
1700 set_swpid(stmp, ent);
1701 stmp->sw_signum = ent->sig;
1702 strcpy(stmp->sw_fname, ent->pid_file);
1703 if (sprev == NULL)
1704 SLIST_INSERT_HEAD(&swhead, stmp, sw_nextp);
1705 else
1706 SLIST_INSERT_AFTER(sprev, stmp, sw_nextp);
1707 return (stmp);
1711 * Save information on any file we need to compress. We may see the same
1712 * file multiple times, so check the full list to avoid duplicates. The
1713 * list itself is sorted smallest-to-largest, because that's the order we
1714 * want to compress the files. If the partition is very low on disk space,
1715 * then the smallest files are the most likely to compress, and compressing
1716 * them first will free up more space for the larger files.
1718 static struct zipwork_entry *
1719 save_zipwork(const struct conf_entry *ent, const struct sigwork_entry *swork,
1720 int zsize, const char *zipfname)
1722 struct zipwork_entry *zprev, *ztmp;
1723 int ndiff;
1724 size_t tmpsiz;
1726 /* Compute the size if the caller did not know it. */
1727 if (zsize < 0)
1728 zsize = sizefile(zipfname);
1730 zprev = NULL;
1731 ndiff = 1;
1732 SLIST_FOREACH(ztmp, &zwhead, zw_nextp) {
1733 ndiff = strcmp(zipfname, ztmp->zw_fname);
1734 if (ndiff == 0)
1735 break;
1736 if (zsize > ztmp->zw_fsize)
1737 zprev = ztmp;
1739 if (ztmp != NULL && ndiff == 0)
1740 return (ztmp);
1742 tmpsiz = sizeof(struct zipwork_entry) + strlen(zipfname) + 1;
1743 ztmp = malloc(tmpsiz);
1744 ztmp->zw_conf = ent;
1745 ztmp->zw_swork = swork;
1746 ztmp->zw_fsize = zsize;
1747 strcpy(ztmp->zw_fname, zipfname);
1748 if (zprev == NULL)
1749 SLIST_INSERT_HEAD(&zwhead, ztmp, zw_nextp);
1750 else
1751 SLIST_INSERT_AFTER(zprev, ztmp, zw_nextp);
1752 return (ztmp);
1755 /* Send a signal to the pid specified by pidfile */
1756 static void
1757 set_swpid(struct sigwork_entry *swork, const struct conf_entry *ent)
1759 FILE *f;
1760 long minok, maxok, rval;
1761 char *endp, *linep, line[BUFSIZ];
1763 minok = MIN_PID;
1764 maxok = MAX_PID;
1765 swork->sw_pidok = 0;
1766 swork->sw_pid = 0;
1767 swork->sw_pidtype = "daemon";
1768 if (ent->flags & CE_SIGNALGROUP) {
1770 * If we are expected to signal a process-group when
1771 * rotating this logfile, then the value read in should
1772 * be the negative of a valid process ID.
1774 minok = -MAX_PID;
1775 maxok = -MIN_PID;
1776 swork->sw_pidtype = "process-group";
1779 f = fopen(ent->pid_file, "r");
1780 if (f == NULL) {
1781 warn("can't open pid file: %s", ent->pid_file);
1782 return;
1785 if (fgets(line, BUFSIZ, f) == NULL) {
1787 * Warn if the PID file is empty, but do not consider
1788 * it an error. Most likely it means the process has
1789 * has terminated, so it should be safe to rotate any
1790 * log files that the process would have been using.
1792 if (feof(f)) {
1793 swork->sw_pidok = 1;
1794 warnx("pid file is empty: %s", ent->pid_file);
1795 } else
1796 warn("can't read from pid file: %s", ent->pid_file);
1797 fclose(f);
1798 return;
1800 fclose(f);
1802 errno = 0;
1803 linep = line;
1804 while (*linep == ' ')
1805 linep++;
1806 rval = strtol(linep, &endp, 10);
1807 if (*endp != '\0' && !isspacech(*endp)) {
1808 warnx("pid file does not start with a valid number: %s",
1809 ent->pid_file);
1810 } else if (rval < minok || rval > maxok) {
1811 warnx("bad value '%ld' for process number in %s",
1812 rval, ent->pid_file);
1813 if (verbose)
1814 warnx("\t(expecting value between %ld and %ld)",
1815 minok, maxok);
1816 } else {
1817 swork->sw_pidok = 1;
1818 swork->sw_pid = rval;
1821 return;
1824 /* Log the fact that the logs were turned over */
1825 static int
1826 log_trim(const char *logname, const struct conf_entry *log_ent)
1828 FILE *f;
1829 const char *xtra;
1831 if ((f = fopen(logname, "a")) == NULL)
1832 return (-1);
1833 xtra = "";
1834 if (log_ent->def_cfg)
1835 xtra = " using <default> rule";
1836 if (log_ent->firstcreate)
1837 fprintf(f, "%s %s newsyslog[%d]: logfile first created%s\n",
1838 daytime, hostname, (int) getpid(), xtra);
1839 else if (log_ent->r_reason != NULL)
1840 fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s%s\n",
1841 daytime, hostname, (int) getpid(), log_ent->r_reason, xtra);
1842 else
1843 fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s\n",
1844 daytime, hostname, (int) getpid(), xtra);
1845 if (fclose(f) == EOF)
1846 err(1, "log_trim: fclose");
1847 return (0);
1850 /* Return size in kilobytes of a file */
1851 static int
1852 sizefile(const char *file)
1854 struct stat sb;
1856 if (stat(file, &sb) < 0)
1857 return (-1);
1858 return (kbytes(dbtob(sb.st_blocks)));
1861 /* Return the age of old log file (file.0) */
1862 static int
1863 age_old_log(char *file)
1865 struct stat sb;
1866 char *endp;
1867 char tmp[MAXPATHLEN + sizeof(".0") + sizeof(COMPRESS_POSTFIX) +
1868 sizeof(BZCOMPRESS_POSTFIX) + 1];
1870 if (archtodir) {
1871 char *p;
1873 /* build name of archive directory into tmp */
1874 if (*archdirname == '/') { /* absolute */
1875 strlcpy(tmp, archdirname, sizeof(tmp));
1876 } else { /* relative */
1877 /* get directory part of logfile */
1878 strlcpy(tmp, file, sizeof(tmp));
1879 if ((p = strrchr(tmp, '/')) == NULL)
1880 tmp[0] = '\0';
1881 else
1882 *(p + 1) = '\0';
1883 strlcat(tmp, archdirname, sizeof(tmp));
1886 strlcat(tmp, "/", sizeof(tmp));
1888 /* get filename part of logfile */
1889 if ((p = strrchr(file, '/')) == NULL)
1890 strlcat(tmp, file, sizeof(tmp));
1891 else
1892 strlcat(tmp, p + 1, sizeof(tmp));
1893 } else {
1894 strlcpy(tmp, file, sizeof(tmp));
1897 strlcat(tmp, ".0", sizeof(tmp));
1898 if (stat(tmp, &sb) < 0) {
1900 * A plain '.0' file does not exist. Try again, first
1901 * with the added suffix of '.gz', then with an added
1902 * suffix of '.bz2' instead of '.gz'.
1904 endp = strchr(tmp, '\0');
1905 strlcat(tmp, COMPRESS_POSTFIX, sizeof(tmp));
1906 if (stat(tmp, &sb) < 0) {
1907 *endp = '\0'; /* Remove .gz */
1908 strlcat(tmp, BZCOMPRESS_POSTFIX, sizeof(tmp));
1909 if (stat(tmp, &sb) < 0)
1910 return (-1);
1913 return ((int)(ptimeget_secs(timenow) - sb.st_mtime + 1800) / 3600);
1916 /* Skip Over Blanks */
1917 static char *
1918 sob(char *p)
1920 while (p && *p && isspace(*p))
1921 p++;
1922 return (p);
1925 /* Skip Over Non-Blanks */
1926 static char *
1927 son(char *p)
1929 while (p && *p && !isspace(*p))
1930 p++;
1931 return (p);
1934 /* Check if string is actually a number */
1935 static int
1936 isnumberstr(const char *string)
1938 while (*string) {
1939 if (!isdigitch(*string++))
1940 return (0);
1942 return (1);
1946 * Save the active log file under a new name. A link to the new name
1947 * is the quick-and-easy way to do this. If that fails (which it will
1948 * if the destination is on another partition), then make a copy of
1949 * the file to the new location.
1951 static void
1952 savelog(char *from, char *to)
1954 FILE *src, *dst;
1955 int c, res;
1957 res = link(from, to);
1958 if (res == 0)
1959 return;
1961 if ((src = fopen(from, "r")) == NULL)
1962 err(1, "can't fopen %s for reading", from);
1963 if ((dst = fopen(to, "w")) == NULL)
1964 err(1, "can't fopen %s for writing", to);
1966 while ((c = getc(src)) != EOF) {
1967 if ((putc(c, dst)) == EOF)
1968 err(1, "error writing to %s", to);
1971 if (ferror(src))
1972 err(1, "error reading from %s", from);
1973 if ((fclose(src)) != 0)
1974 err(1, "can't fclose %s", to);
1975 if ((fclose(dst)) != 0)
1976 err(1, "can't fclose %s", from);
1979 /* create one or more directory components of a path */
1980 static void
1981 createdir(const struct conf_entry *ent, char *dirpart)
1983 int res;
1984 char *s, *d;
1985 char mkdirpath[MAXPATHLEN];
1986 struct stat st;
1988 s = dirpart;
1989 d = mkdirpath;
1991 for (;;) {
1992 *d++ = *s++;
1993 if (*s != '/' && *s != '\0')
1994 continue;
1995 *d = '\0';
1996 res = lstat(mkdirpath, &st);
1997 if (res != 0) {
1998 if (noaction) {
1999 printf("\tmkdir %s\n", mkdirpath);
2000 } else {
2001 res = mkdir(mkdirpath, 0755);
2002 if (res != 0)
2003 err(1, "Error on mkdir(\"%s\") for -a",
2004 mkdirpath);
2007 if (*s == '\0')
2008 break;
2010 if (verbose) {
2011 if (ent->firstcreate)
2012 printf("Created directory '%s' for new %s\n",
2013 dirpart, ent->log);
2014 else
2015 printf("Created directory '%s' for -a\n", dirpart);
2020 * Create a new log file, destroying any currently-existing version
2021 * of the log file in the process. If the caller wants a backup copy
2022 * of the file to exist, they should call 'link(logfile,logbackup)'
2023 * before calling this routine.
2025 void
2026 createlog(const struct conf_entry *ent)
2028 int fd, failed;
2029 struct stat st;
2030 char *realfile, *slash, tempfile[MAXPATHLEN];
2032 fd = -1;
2033 realfile = ent->log;
2036 * If this log file is being created for the first time (-C option),
2037 * then it may also be true that the parent directory does not exist
2038 * yet. Check, and create that directory if it is missing.
2040 if (ent->firstcreate) {
2041 strlcpy(tempfile, realfile, sizeof(tempfile));
2042 slash = strrchr(tempfile, '/');
2043 if (slash != NULL) {
2044 *slash = '\0';
2045 failed = stat(tempfile, &st);
2046 if (failed && errno != ENOENT)
2047 err(1, "Error on stat(%s)", tempfile);
2048 if (failed)
2049 createdir(ent, tempfile);
2050 else if (!S_ISDIR(st.st_mode))
2051 errx(1, "%s exists but is not a directory",
2052 tempfile);
2057 * First create an unused filename, so it can be chown'ed and
2058 * chmod'ed before it is moved into the real location. mkstemp
2059 * will create the file mode=600 & owned by us. Note that all
2060 * temp files will have a suffix of '.z<something>'.
2062 strlcpy(tempfile, realfile, sizeof(tempfile));
2063 strlcat(tempfile, ".zXXXXXX", sizeof(tempfile));
2064 if (noaction)
2065 printf("\tmktemp %s\n", tempfile);
2066 else {
2067 fd = mkstemp(tempfile);
2068 if (fd < 0)
2069 err(1, "can't mkstemp logfile %s", tempfile);
2072 * Add status message to what will become the new log file.
2074 if (!(ent->flags & CE_BINARY)) {
2075 if (log_trim(tempfile, ent))
2076 err(1, "can't add status message to log");
2080 /* Change the owner/group, if we are supposed to */
2081 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2082 if (noaction)
2083 printf("\tchown %u:%u %s\n", ent->uid, ent->gid,
2084 tempfile);
2085 else {
2086 failed = fchown(fd, ent->uid, ent->gid);
2087 if (failed)
2088 err(1, "can't fchown temp file %s", tempfile);
2092 /* Turn on NODUMP if it was requested in the config-file. */
2093 if (ent->flags & CE_NODUMP) {
2094 if (noaction)
2095 printf("\tchflags nodump %s\n", tempfile);
2096 else {
2097 failed = fchflags(fd, UF_NODUMP);
2098 if (failed) {
2099 warn("log_trim: fchflags(NODUMP)");
2105 * Note that if the real logfile still exists, and if the call
2106 * to rename() fails, then "neither the old file nor the new
2107 * file shall be changed or created" (to quote the standard).
2108 * If the call succeeds, then the file will be replaced without
2109 * any window where some other process might find that the file
2110 * did not exist.
2111 * XXX - ? It may be that for some error conditions, we could
2112 * retry by first removing the realfile and then renaming.
2114 if (noaction) {
2115 printf("\tchmod %o %s\n", ent->permissions, tempfile);
2116 printf("\tmv %s %s\n", tempfile, realfile);
2117 } else {
2118 failed = fchmod(fd, ent->permissions);
2119 if (failed)
2120 err(1, "can't fchmod temp file '%s'", tempfile);
2121 failed = rename(tempfile, realfile);
2122 if (failed)
2123 err(1, "can't mv %s to %s", tempfile, realfile);
2126 if (fd >= 0)
2127 close(fd);
2131 * Change the attributes of a given filename to what was specified in
2132 * the newsyslog.conf entry. This routine is only called for files
2133 * that newsyslog expects that it has created, and thus it is a fatal
2134 * error if this routine finds that the file does not exist.
2136 static void
2137 change_attrs(const char *fname, const struct conf_entry *ent)
2139 int failed;
2141 if (noaction) {
2142 printf("\tchmod %o %s\n", ent->permissions, fname);
2144 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
2145 printf("\tchown %u:%u %s\n",
2146 ent->uid, ent->gid, fname);
2148 if (ent->flags & CE_NODUMP)
2149 printf("\tchflags nodump %s\n", fname);
2150 return;
2153 failed = chmod(fname, ent->permissions);
2154 if (failed) {
2155 if (errno != EPERM)
2156 err(1, "chmod(%s) in change_attrs", fname);
2157 warn("change_attrs couldn't chmod(%s)", fname);
2160 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2161 failed = chown(fname, ent->uid, ent->gid);
2162 if (failed)
2163 warn("can't chown %s", fname);
2166 if (ent->flags & CE_NODUMP) {
2167 failed = chflags(fname, UF_NODUMP);
2168 if (failed)
2169 warn("can't chflags %s NODUMP", fname);