2 * ------+---------+---------+-------- + --------+---------+---------+---------*
3 * This file includes significant modifications done by:
4 * Copyright (c) 2003, 2004 - Garance Alistair Drosehn <gad@FreeBSD.org>.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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
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
52 * newsyslog - roll over selected logs at the appropriate time, keeping the a
53 * specified number of backup files around.
56 #include <sys/cdefs.h>
57 __FBSDID("$FreeBSD$");
61 #include <sys/param.h>
62 #include <sys/queue.h>
86 #include "pathnames.h"
90 * Compression suffixes
92 #ifndef COMPRESS_SUFFIX_GZ
93 #define COMPRESS_SUFFIX_GZ ".gz"
96 #ifndef COMPRESS_SUFFIX_BZ2
97 #define COMPRESS_SUFFIX_BZ2 ".bz2"
100 #ifndef COMPRESS_SUFFIX_XZ
101 #define COMPRESS_SUFFIX_XZ ".xz"
104 #define COMPRESS_SUFFIX_MAXLEN MAX(MAX(sizeof(COMPRESS_SUFFIX_GZ),sizeof(COMPRESS_SUFFIX_BZ2)),sizeof(COMPRESS_SUFFIX_XZ))
109 #define COMPRESS_TYPES 4 /* Number of supported compression types */
111 #define COMPRESS_NONE 0
112 #define COMPRESS_GZIP 1
113 #define COMPRESS_BZIP2 2
114 #define COMPRESS_XZ 3
117 * Bit-values for the 'flags' parsed from a config-file entry.
119 #define CE_BINARY 0x0008 /* Logfile is in binary, do not add status */
120 /* messages to logfile(s) when rotating. */
121 #define CE_NOSIGNAL 0x0010 /* There is no process to signal when */
122 /* trimming this file. */
123 #define CE_TRIMAT 0x0020 /* trim file at a specific time. */
124 #define CE_GLOB 0x0040 /* name of the log is file name pattern. */
125 #define CE_SIGNALGROUP 0x0080 /* Signal a process-group instead of a single */
126 /* process when trimming this file. */
127 #define CE_CREATE 0x0100 /* Create the log file if it does not exist. */
128 #define CE_NODUMP 0x0200 /* Set 'nodump' on newly created log file. */
129 #define CE_PID2CMD 0x0400 /* Replace PID file with a shell command.*/
130 #define CE_PLAIN0 0x0800 /* Do not compress zero'th history file */
131 #define CE_RFC5424 0x1000 /* Use RFC5424 format rotation message */
133 #define MIN_PID 5 /* Don't touch pids lower than this */
134 #define MAX_PID 99999 /* was lower, see /usr/include/sys/proc.h */
136 #define kbytes(size) (((size) + 1023) >> 10)
138 #define DEFAULT_MARKER "<default>"
139 #define DEBUG_MARKER "<debug>"
140 #define INCLUDE_MARKER "<include>"
141 #define DEFAULT_TIMEFNAME_FMT "%Y%m%dT%H%M%S"
143 #define MAX_OLDLOGS 65536 /* Default maximum number of old logfiles */
145 struct compress_types {
146 const char *flag; /* Flag in configuration file */
147 const char *suffix; /* Compression suffix */
148 const char *path; /* Path to compression program */
151 static const struct compress_types compress_type[COMPRESS_TYPES] = {
152 { "", "", "" }, /* no compression */
153 { "Z", COMPRESS_SUFFIX_GZ, _PATH_GZIP }, /* gzip compression */
154 { "J", COMPRESS_SUFFIX_BZ2, _PATH_BZIP2 }, /* bzip2 compression */
155 { "X", COMPRESS_SUFFIX_XZ, _PATH_XZ } /* xz compression */
159 STAILQ_ENTRY(conf_entry) cf_nextp;
160 char *log; /* Name of the log */
161 char *pid_cmd_file; /* PID or command file */
162 char *r_reason; /* The reason this file is being rotated */
163 int firstcreate; /* Creating log for the first time (-C). */
164 int rotate; /* Non-zero if this file should be rotated */
165 int fsize; /* size found for the log file */
166 uid_t uid; /* Owner of log */
167 gid_t gid; /* Group of log */
168 int numlogs; /* Number of logs to keep */
169 int trsize; /* Size cutoff to trigger trimming the log */
170 int hours; /* Hours between log trimming */
171 struct ptime_data *trim_at; /* Specific time to do trimming */
172 unsigned int permissions; /* File permissions on the log */
173 int flags; /* CE_BINARY */
174 int compress; /* Compression */
175 int sig; /* Signal to send */
176 int def_cfg; /* Using the <default> rule for this file */
179 struct sigwork_entry {
180 SLIST_ENTRY(sigwork_entry) sw_nextp;
181 int sw_signum; /* the signal to send */
182 int sw_pidok; /* true if pid value is valid */
183 pid_t sw_pid; /* the process id from the PID file */
184 const char *sw_pidtype; /* "daemon" or "process group" */
185 int sw_runcmd; /* run command or send PID to signal */
186 char sw_fname[1]; /* file the PID was read from or shell cmd */
189 struct zipwork_entry {
190 SLIST_ENTRY(zipwork_entry) zw_nextp;
191 const struct conf_entry *zw_conf; /* for chown/perm/flag info */
192 const struct sigwork_entry *zw_swork; /* to know success of signal */
193 int zw_fsize; /* size of the file to compress */
194 char zw_fname[1]; /* the file to compress */
197 struct include_entry {
198 STAILQ_ENTRY(include_entry) inc_nextp;
199 const char *file; /* Name of file to process */
202 struct oldlog_entry {
203 char *fname; /* Filename of the log file */
204 time_t t; /* Parsed timestamp of the logfile */
211 STAILQ_HEAD(cflist, conf_entry);
212 static SLIST_HEAD(swlisthead, sigwork_entry) swhead =
213 SLIST_HEAD_INITIALIZER(swhead);
214 static SLIST_HEAD(zwlisthead, zipwork_entry) zwhead =
215 SLIST_HEAD_INITIALIZER(zwhead);
216 STAILQ_HEAD(ilist, include_entry);
218 int dbg_at_times; /* -D Show details of 'trim_at' code */
220 static int archtodir = 0; /* Archive old logfiles to other directory */
221 static int createlogs; /* Create (non-GLOB) logfiles which do not */
222 /* already exist. 1=='for entries with */
223 /* C flag', 2=='for all entries'. */
224 int verbose = 0; /* Print out what's going on */
225 static int needroot = 1; /* Root privs are necessary */
226 int noaction = 0; /* Don't do anything, just show it */
227 static int norotate = 0; /* Don't rotate */
228 static int nosignal; /* Do not send any signals */
229 static int enforcepid = 0; /* If PID file does not exist or empty, do nothing */
230 static int force = 0; /* Force the trim no matter what */
231 static int rotatereq = 0; /* -R = Always rotate the file(s) as given */
232 /* on the command (this also requires */
233 /* that a list of files *are* given on */
234 /* the run command). */
235 static char *requestor; /* The name given on a -R request */
236 static char *timefnamefmt = NULL;/* Use time based filenames instead of .0 */
237 static char *archdirname; /* Directory path to old logfiles archive */
238 static char *destdir = NULL; /* Directory to treat at root for logs */
239 static const char *conf; /* Configuration file to use */
241 struct ptime_data *dbg_timenow; /* A "timenow" value set via -D option */
242 static struct ptime_data *timenow; /* The time to use for checking at-fields */
244 #define DAYTIME_LEN 16
245 static char daytime[DAYTIME_LEN];/* The current time in human readable form,
246 * used for rotation-tracking messages. */
248 /* Another buffer to hold the current time in RFC5424 format. Fractional
249 * seconds are allowed by the RFC, but are not included in the
250 * rotation-tracking messages written by newsyslog and so are not accounted for
251 * in the length below.
253 #define DAYTIME_RFC5424_LEN sizeof("YYYY-MM-DDTHH:MM:SS+00:00")
254 static char daytime_rfc5424[DAYTIME_RFC5424_LEN];
256 static char hostname[MAXHOSTNAMELEN]; /* hostname */
257 static size_t hostname_shortlen;
259 static const char *path_syslogpid = _PATH_SYSLOGPID;
261 static struct cflist *get_worklist(char **files);
262 static void parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
263 struct conf_entry **defconf, struct ilist *inclist);
264 static void add_to_queue(const char *fname, struct ilist *inclist);
265 static char *sob(char *p);
266 static char *son(char *p);
267 static int isnumberstr(const char *);
268 static int isglobstr(const char *);
269 static char *missing_field(char *p, char *errline);
270 static void change_attrs(const char *, const struct conf_entry *);
271 static const char *get_logfile_suffix(const char *logfile);
272 static fk_entry do_entry(struct conf_entry *);
273 static fk_entry do_rotate(const struct conf_entry *);
274 static void do_sigwork(struct sigwork_entry *);
275 static void do_zipwork(struct zipwork_entry *);
276 static struct sigwork_entry *
277 save_sigwork(const struct conf_entry *);
278 static struct zipwork_entry *
279 save_zipwork(const struct conf_entry *, const struct
280 sigwork_entry *, int, const char *);
281 static void set_swpid(struct sigwork_entry *, const struct conf_entry *);
282 static int sizefile(const char *);
283 static void expand_globs(struct cflist *work_p, struct cflist *glob_p);
284 static void free_clist(struct cflist *list);
285 static void free_entry(struct conf_entry *ent);
286 static struct conf_entry *init_entry(const char *fname,
287 struct conf_entry *src_entry);
288 static void parse_args(int argc, char **argv);
289 static int parse_doption(const char *doption);
290 static void usage(void);
291 static int log_trim(const char *logname, const struct conf_entry *log_ent);
292 static int age_old_log(const char *file);
293 static void savelog(char *from, char *to);
294 static void createdir(const struct conf_entry *ent, char *dirpart);
295 static void createlog(const struct conf_entry *ent);
296 static int parse_signal(const char *str);
299 * All the following take a parameter of 'int', but expect values in the
300 * range of unsigned char. Define wrappers which take values of type 'char',
301 * whether signed or unsigned, and ensure they end up in the right range.
303 #define isdigitch(Anychar) isdigit((u_char)(Anychar))
304 #define isprintch(Anychar) isprint((u_char)(Anychar))
305 #define isspacech(Anychar) isspace((u_char)(Anychar))
306 #define tolowerch(Anychar) tolower((u_char)(Anychar))
309 main(int argc, char **argv)
311 struct cflist *worklist;
312 struct conf_entry *p;
313 struct sigwork_entry *stmp;
314 struct zipwork_entry *ztmp;
319 parse_args(argc, argv);
323 if (needroot && getuid() && geteuid())
324 errx(1, "must have root privs");
325 worklist = get_worklist(argv);
328 * Rotate all the files which need to be rotated. Note that
329 * some users have *hundreds* of entries in newsyslog.conf!
331 while (!STAILQ_EMPTY(worklist)) {
332 p = STAILQ_FIRST(worklist);
333 STAILQ_REMOVE_HEAD(worklist, cf_nextp);
334 if (do_entry(p) == FREE_ENT)
339 * Send signals to any processes which need a signal to tell
340 * them to close and re-open the log file(s) we have rotated.
341 * Note that zipwork_entries include pointers to these
342 * sigwork_entry's, so we can not free the entries here.
344 if (!SLIST_EMPTY(&swhead)) {
345 if (noaction || verbose)
346 printf("Signal all daemon process(es)...\n");
347 SLIST_FOREACH(stmp, &swhead, sw_nextp)
349 if (!(rotatereq && nosignal)) {
351 printf("\tsleep 10\n");
354 printf("Pause 10 seconds to allow "
355 "daemon(s) to close log file(s)\n");
361 * Compress all files that we're expected to compress, now
362 * that all processes should have closed the files which
365 if (!SLIST_EMPTY(&zwhead)) {
366 if (noaction || verbose)
367 printf("Compress all rotated log file(s)...\n");
368 while (!SLIST_EMPTY(&zwhead)) {
369 ztmp = SLIST_FIRST(&zwhead);
371 SLIST_REMOVE_HEAD(&zwhead, zw_nextp);
375 /* Now free all the sigwork entries. */
376 while (!SLIST_EMPTY(&swhead)) {
377 stmp = SLIST_FIRST(&swhead);
378 SLIST_REMOVE_HEAD(&swhead, sw_nextp);
382 while (wait(NULL) > 0 || errno == EINTR)
387 static struct conf_entry *
388 init_entry(const char *fname, struct conf_entry *src_entry)
390 struct conf_entry *tempwork;
393 printf("\t--> [creating entry for %s]\n", fname);
395 tempwork = malloc(sizeof(struct conf_entry));
396 if (tempwork == NULL)
397 err(1, "malloc of conf_entry for %s", fname);
399 if (destdir == NULL || fname[0] != '/')
400 tempwork->log = strdup(fname);
402 asprintf(&tempwork->log, "%s%s", destdir, fname);
403 if (tempwork->log == NULL)
404 err(1, "strdup for %s", fname);
406 if (src_entry != NULL) {
407 tempwork->pid_cmd_file = NULL;
408 if (src_entry->pid_cmd_file)
409 tempwork->pid_cmd_file = strdup(src_entry->pid_cmd_file);
410 tempwork->r_reason = NULL;
411 tempwork->firstcreate = 0;
412 tempwork->rotate = 0;
413 tempwork->fsize = -1;
414 tempwork->uid = src_entry->uid;
415 tempwork->gid = src_entry->gid;
416 tempwork->numlogs = src_entry->numlogs;
417 tempwork->trsize = src_entry->trsize;
418 tempwork->hours = src_entry->hours;
419 tempwork->trim_at = NULL;
420 if (src_entry->trim_at != NULL)
421 tempwork->trim_at = ptime_init(src_entry->trim_at);
422 tempwork->permissions = src_entry->permissions;
423 tempwork->flags = src_entry->flags;
424 tempwork->compress = src_entry->compress;
425 tempwork->sig = src_entry->sig;
426 tempwork->def_cfg = src_entry->def_cfg;
428 /* Initialize as a "do-nothing" entry */
429 tempwork->pid_cmd_file = NULL;
430 tempwork->r_reason = NULL;
431 tempwork->firstcreate = 0;
432 tempwork->rotate = 0;
433 tempwork->fsize = -1;
434 tempwork->uid = (uid_t)-1;
435 tempwork->gid = (gid_t)-1;
436 tempwork->numlogs = 1;
437 tempwork->trsize = -1;
438 tempwork->hours = -1;
439 tempwork->trim_at = NULL;
440 tempwork->permissions = 0;
442 tempwork->compress = COMPRESS_NONE;
443 tempwork->sig = SIGHUP;
444 tempwork->def_cfg = 0;
451 free_entry(struct conf_entry *ent)
457 if (ent->log != NULL) {
459 printf("\t--> [freeing entry for %s]\n", ent->log);
464 if (ent->pid_cmd_file != NULL) {
465 free(ent->pid_cmd_file);
466 ent->pid_cmd_file = NULL;
469 if (ent->r_reason != NULL) {
471 ent->r_reason = NULL;
474 if (ent->trim_at != NULL) {
475 ptime_free(ent->trim_at);
483 free_clist(struct cflist *list)
485 struct conf_entry *ent;
487 while (!STAILQ_EMPTY(list)) {
488 ent = STAILQ_FIRST(list);
489 STAILQ_REMOVE_HEAD(list, cf_nextp);
498 do_entry(struct conf_entry * ent)
500 #define REASON_MAX 80
502 fk_entry free_or_keep;
504 char temp_reason[REASON_MAX];
507 free_or_keep = FREE_ENT;
509 printf("%s <%d%s>: ", ent->log, ent->numlogs,
510 compress_type[ent->compress].flag);
511 ent->fsize = sizefile(ent->log);
512 oversized = ((ent->trsize > 0) && (ent->fsize >= ent->trsize));
513 modtime = age_old_log(ent->log);
515 ent->firstcreate = 0;
516 if (ent->fsize < 0) {
518 * If either the C flag or the -C option was specified,
519 * and if we won't be creating the file, then have the
520 * verbose message include a hint as to why the file
521 * will not be created.
523 temp_reason[0] = '\0';
525 ent->firstcreate = 1;
526 else if ((ent->flags & CE_CREATE) && createlogs)
527 ent->firstcreate = 1;
528 else if (ent->flags & CE_CREATE)
529 strlcpy(temp_reason, " (no -C option)", REASON_MAX);
531 strlcpy(temp_reason, " (no C flag)", REASON_MAX);
533 if (ent->firstcreate) {
535 printf("does not exist -> will create.\n");
537 } else if (verbose) {
538 printf("does not exist, skipped%s.\n", temp_reason);
541 if (ent->flags & CE_TRIMAT && !force && !rotatereq &&
543 diffsecs = ptimeget_diff(timenow, ent->trim_at);
544 if (diffsecs < 0.0) {
545 /* trim_at is some time in the future. */
547 ptime_adjust4dst(ent->trim_at,
549 printf("--> will trim at %s",
550 ptimeget_ctime(ent->trim_at));
552 return (free_or_keep);
553 } else if (diffsecs >= 3600.0) {
555 * trim_at is more than an hour in the past,
556 * so find the next valid trim_at time, and
557 * tell the user what that will be.
559 if (verbose && dbg_at_times)
560 printf("\n\t--> prev trim at %s\t",
561 ptimeget_ctime(ent->trim_at));
563 ptimeset_nxtime(ent->trim_at);
564 printf("--> will trim at %s",
565 ptimeget_ctime(ent->trim_at));
567 return (free_or_keep);
568 } else if (verbose && noaction && dbg_at_times) {
570 * If we are just debugging at-times, then
571 * a detailed message is helpful. Also
572 * skip "doing" any commands, since they
573 * would all be turned off by no-action.
575 printf("\n\t--> timematch at %s",
576 ptimeget_ctime(ent->trim_at));
577 return (free_or_keep);
578 } else if (verbose && ent->hours <= 0) {
579 printf("--> time is up\n");
582 if (verbose && (ent->trsize > 0))
583 printf("size (Kb): %d [%d] ", ent->fsize, ent->trsize);
584 if (verbose && (ent->hours > 0))
585 printf(" age (hr): %d [%d] ", modtime, ent->hours);
588 * Figure out if this logfile needs to be rotated.
590 temp_reason[0] = '\0';
593 snprintf(temp_reason, REASON_MAX, " due to -R from %s",
597 snprintf(temp_reason, REASON_MAX, " due to -F request");
598 } else if (oversized) {
600 snprintf(temp_reason, REASON_MAX, " due to size>%dK",
602 } else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) {
604 } else if ((ent->hours > 0) && ((modtime >= ent->hours) ||
610 * If the file needs to be rotated, then rotate it.
612 if (ent->rotate && !norotate) {
613 if (temp_reason[0] != '\0')
614 ent->r_reason = strdup(temp_reason);
616 printf("--> trimming log....\n");
617 if (noaction && !verbose)
618 printf("%s <%d%s>: trimming\n", ent->log,
620 compress_type[ent->compress].flag);
621 free_or_keep = do_rotate(ent);
624 printf("--> skipping\n");
627 return (free_or_keep);
632 parse_args(int argc, char **argv)
637 timenow = ptime_init(NULL);
638 ptimeset_time(timenow, time(NULL));
639 strlcpy(daytime, ptimeget_ctime(timenow) + 4, DAYTIME_LEN);
640 ptimeget_ctime_rfc5424(timenow, daytime_rfc5424, DAYTIME_RFC5424_LEN);
642 /* Let's get our hostname */
643 (void)gethostname(hostname, sizeof(hostname));
644 hostname_shortlen = strcspn(hostname, ".");
646 /* Parse command line options. */
647 while ((ch = getopt(argc, argv, "a:d:f:nrst:vCD:FNPR:S:")) != -1)
651 archdirname = optarg;
669 if (optarg[0] == '\0' ||
670 strcmp(optarg, "DEFAULT") == 0)
671 timefnamefmt = strdup(DEFAULT_TIMEFNAME_FMT);
673 timefnamefmt = strdup(optarg);
679 /* Useful for things like rc.diskless... */
684 * Set some debugging option. The specific option
685 * depends on the value of optarg. These options
686 * may come and go without notice or documentation.
688 if (parse_doption(optarg))
703 requestor = strdup(optarg);
706 path_syslogpid = optarg;
708 case 'm': /* Used by OpenBSD for "monitor mode" */
714 if (force && norotate) {
715 warnx("Only one of -F and -N may be specified.");
721 if (optind == argc) {
722 warnx("At least one filename must be given when -R is specified.");
726 /* Make sure "requestor" value is safe for a syslog message. */
727 for (p = requestor; *p != '\0'; p++) {
728 if (!isprintch(*p) && (*p != '\t'))
735 * Note that the 'daytime' variable is not changed.
736 * That is only used in messages that track when a
737 * logfile is rotated, and if a file *is* rotated,
738 * then it will still rotated at the "real now" time.
741 timenow = dbg_timenow;
742 fprintf(stderr, "Debug: Running as if TimeNow is %s",
743 ptimeget_ctime(dbg_timenow));
749 * These debugging options are mainly meant for developer use, such
750 * as writing regression-tests. They would not be needed by users
751 * during normal operation of newsyslog...
754 parse_doption(const char *doption)
756 const char TN[] = "TN=";
759 if (strncmp(doption, TN, sizeof(TN) - 1) == 0) {
761 * The "TimeNow" debugging option. This might be off
762 * by an hour when crossing a timezone change.
764 dbg_timenow = ptime_init(NULL);
765 res = ptime_relparse(dbg_timenow, PTM_PARSE_ISO8601,
766 time(NULL), doption + sizeof(TN) - 1);
768 warnx("Non-existent time specified on -D %s", doption);
769 return (0); /* failure */
770 } else if (res < 0) {
771 warnx("Malformed time given on -D %s", doption);
772 return (0); /* failure */
774 return (1); /* successfully parsed */
778 if (strcmp(doption, "ats") == 0) {
780 return (1); /* successfully parsed */
783 /* XXX - This check could probably be dropped. */
784 if ((strcmp(doption, "neworder") == 0) || (strcmp(doption, "oldorder")
786 warnx("NOTE: newsyslog always uses 'neworder'.");
787 return (1); /* successfully parsed */
790 warnx("Unknown -D (debug) option: '%s'", doption);
791 return (0); /* failure */
799 "usage: newsyslog [-CFNPnrsv] [-a directory] [-d directory] [-f config_file]\n"
800 " [-S pidfile] [-t timefmt] [[-R tagname] file ...]\n");
805 * Parse a configuration file and return a linked list of all the logs
806 * which should be processed.
808 static struct cflist *
809 get_worklist(char **files)
813 struct cflist *cmdlist, *filelist, *globlist;
814 struct conf_entry *defconf, *dupent, *ent;
815 struct ilist inclist;
816 struct include_entry *inc;
820 STAILQ_INIT(&inclist);
822 filelist = malloc(sizeof(struct cflist));
823 if (filelist == NULL)
824 err(1, "malloc of filelist");
825 STAILQ_INIT(filelist);
826 globlist = malloc(sizeof(struct cflist));
827 if (globlist == NULL)
828 err(1, "malloc of globlist");
829 STAILQ_INIT(globlist);
831 inc = malloc(sizeof(struct include_entry));
833 err(1, "malloc of inc");
835 if (inc->file == NULL)
836 inc->file = _PATH_CONF;
837 STAILQ_INSERT_TAIL(&inclist, inc, inc_nextp);
839 STAILQ_FOREACH(inc, &inclist, inc_nextp) {
840 if (strcmp(inc->file, "-") != 0)
841 f = fopen(inc->file, "r");
844 inc->file = "<stdin>";
847 err(1, "%s", inc->file);
850 printf("Processing %s\n", inc->file);
851 parse_file(f, filelist, globlist, &defconf, &inclist);
856 * All config-file information has been read in and turned into
857 * a filelist and a globlist. If there were no specific files
858 * given on the run command, then the only thing left to do is to
859 * call a routine which finds all files matched by the globlist
860 * and adds them to the filelist. Then return the worklist.
862 if (*files == NULL) {
863 expand_globs(filelist, globlist);
864 free_clist(globlist);
871 * If newsyslog was given a specific list of files to process,
872 * it may be that some of those files were not listed in any
873 * config file. Those unlisted files should get the default
874 * rotation action. First, create the default-rotation action
875 * if none was found in a system config file.
877 if (defconf == NULL) {
878 defconf = init_entry(DEFAULT_MARKER, NULL);
879 defconf->numlogs = 3;
880 defconf->trsize = 50;
881 defconf->permissions = S_IRUSR|S_IWUSR;
885 * If newsyslog was run with a list of specific filenames,
886 * then create a new worklist which has only those files in
887 * it, picking up the rotation-rules for those files from
888 * the original filelist.
890 * XXX - Note that this will copy multiple rules for a single
891 * logfile, if multiple entries are an exact match for
892 * that file. That matches the historic behavior, but do
893 * we want to continue to allow it? If so, it should
894 * probably be handled more intelligently.
896 cmdlist = malloc(sizeof(struct cflist));
898 err(1, "malloc of cmdlist");
899 STAILQ_INIT(cmdlist);
901 for (given = files; *given; ++given) {
903 * First try to find exact-matches for this given file.
906 STAILQ_FOREACH(ent, filelist, cf_nextp) {
907 if (strcmp(ent->log, *given) == 0) {
909 dupent = init_entry(*given, ent);
910 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
915 printf("\t+ Matched entry %s\n", *given);
920 * There was no exact-match for this given file, so look
921 * for a "glob" entry which does match.
925 printf("\t+ Checking globs for %s\n", *given);
926 STAILQ_FOREACH(ent, globlist, cf_nextp) {
927 fnres = fnmatch(ent->log, *given, FNM_PATHNAME);
929 printf("\t+ = %d for pattern %s\n", fnres,
933 dupent = init_entry(*given, ent);
934 /* This new entry is not a glob! */
935 dupent->flags &= ~CE_GLOB;
936 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
937 /* Only allow a match to one glob-entry */
943 printf("\t+ Matched %s via %s\n", *given,
949 * This given file was not found in any config file, so
950 * add a worklist item based on the default entry.
953 printf("\t+ No entry matched %s (will use %s)\n",
954 *given, DEFAULT_MARKER);
955 dupent = init_entry(*given, defconf);
956 /* Mark that it was *not* found in a config file */
958 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
962 * Free all the entries in the original work list, the list of
963 * glob entries, and the default entry.
965 free_clist(filelist);
966 free_clist(globlist);
969 /* And finally, return a worklist which matches the given files. */
974 * Expand the list of entries with filename patterns, and add all files
975 * which match those glob-entries onto the worklist.
978 expand_globs(struct cflist *work_p, struct cflist *glob_p)
983 struct conf_entry *dupent, *ent, *globent;
988 * The worklist contains all fully-specified (non-GLOB) names.
990 * Now expand the list of filename-pattern (GLOB) entries into
991 * a second list, which (by definition) will only match files
992 * that already exist. Do not add a glob-related entry for any
993 * file which already exists in the fully-specified list.
995 STAILQ_FOREACH(globent, glob_p, cf_nextp) {
996 gres = glob(globent->log, GLOB_NOCHECK, NULL, &pglob);
998 warn("cannot expand pattern (%d): %s", gres,
1004 printf("\t+ Expanding pattern %s\n", globent->log);
1005 for (i = 0; i < pglob.gl_matchc; i++) {
1006 mfname = pglob.gl_pathv[i];
1008 /* See if this file already has a specific entry. */
1010 STAILQ_FOREACH(ent, work_p, cf_nextp) {
1011 if (strcmp(mfname, ent->log) == 0) {
1019 /* Make sure the named matched is a file. */
1020 gres = lstat(mfname, &st_fm);
1022 /* Error on a file that glob() matched?!? */
1023 warn("Skipping %s - lstat() error", mfname);
1026 if (!S_ISREG(st_fm.st_mode)) {
1027 /* We only rotate files! */
1029 printf("\t+ . skipping %s (!file)\n",
1035 printf("\t+ . add file %s\n", mfname);
1036 dupent = init_entry(mfname, globent);
1037 /* This new entry is not a glob! */
1038 dupent->flags &= ~CE_GLOB;
1040 /* Add to the worklist. */
1041 STAILQ_INSERT_TAIL(work_p, dupent, cf_nextp);
1045 printf("\t+ Done with pattern %s\n", globent->log);
1050 * Parse a configuration file and update a linked list of all the logs to
1054 parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
1055 struct conf_entry **defconf_p, struct ilist *inclist)
1057 char line[BUFSIZ], *parse, *q;
1058 char *cp, *errline, *group;
1059 struct conf_entry *working;
1063 int eol, ptm_opts, res, special;
1067 while (fgets(line, BUFSIZ, cf)) {
1068 if ((line[0] == '\n') || (line[0] == '#') ||
1069 (strlen(line) == 0))
1071 if (errline != NULL)
1073 errline = strdup(line);
1074 for (cp = line + 1; *cp != '\0'; cp++) {
1077 if (*(cp - 1) == '\\') {
1086 q = parse = missing_field(sob(line), errline);
1089 errx(1, "malformed line (missing fields):\n%s",
1094 * Allow people to set debug options via the config file.
1095 * (NOTE: debug options are undocumented, and may disappear
1096 * at any time, etc).
1098 if (strcasecmp(DEBUG_MARKER, q) == 0) {
1099 q = parse = missing_field(sob(parse + 1), errline);
1102 warnx("debug line specifies no option:\n%s",
1109 } else if (strcasecmp(INCLUDE_MARKER, q) == 0) {
1111 printf("Found: %s", errline);
1112 q = parse = missing_field(sob(parse + 1), errline);
1115 warnx("include line missing argument:\n%s",
1123 res = glob(q, GLOB_NOCHECK, NULL, &pglob);
1125 warn("cannot expand pattern (%d): %s",
1131 printf("\t+ Expanding pattern %s\n", q);
1133 for (i = 0; i < pglob.gl_matchc; i++)
1134 add_to_queue(pglob.gl_pathv[i],
1138 add_to_queue(q, inclist);
1143 working = init_entry(q, NULL);
1144 if (strcasecmp(DEFAULT_MARKER, q) == 0) {
1146 if (*defconf_p != NULL) {
1147 warnx("Ignoring duplicate entry for %s!", q);
1148 free_entry(working);
1151 *defconf_p = working;
1154 q = parse = missing_field(sob(parse + 1), errline);
1157 errx(1, "malformed line (missing fields):\n%s",
1160 if ((group = strchr(q, ':')) != NULL ||
1161 (group = strrchr(q, '.')) != NULL) {
1164 if (!(isnumberstr(q))) {
1165 if ((pwd = getpwnam(q)) == NULL)
1167 "error in config file; unknown user:\n%s",
1169 working->uid = pwd->pw_uid;
1171 working->uid = atoi(q);
1173 working->uid = (uid_t)-1;
1177 if (!(isnumberstr(q))) {
1178 if ((grp = getgrnam(q)) == NULL)
1180 "error in config file; unknown group:\n%s",
1182 working->gid = grp->gr_gid;
1184 working->gid = atoi(q);
1186 working->gid = (gid_t)-1;
1188 q = parse = missing_field(sob(parse + 1), errline);
1191 errx(1, "malformed line (missing fields):\n%s",
1195 working->uid = (uid_t)-1;
1196 working->gid = (gid_t)-1;
1199 if (!sscanf(q, "%o", &working->permissions))
1200 errx(1, "error in config file; bad permissions:\n%s",
1203 q = parse = missing_field(sob(parse + 1), errline);
1206 errx(1, "malformed line (missing fields):\n%s",
1209 if (!sscanf(q, "%d", &working->numlogs) || working->numlogs < 0)
1210 errx(1, "error in config file; bad value for count of logs to save:\n%s",
1213 q = parse = missing_field(sob(parse + 1), errline);
1216 errx(1, "malformed line (missing fields):\n%s",
1220 working->trsize = atoi(q);
1221 else if (strcmp(q, "*") == 0)
1222 working->trsize = -1;
1224 warnx("Invalid value of '%s' for 'size' in line:\n%s",
1226 working->trsize = -1;
1230 working->compress = COMPRESS_NONE;
1231 q = parse = missing_field(sob(parse + 1), errline);
1239 ul = strtoul(q, &ep, 10);
1242 else if (*ep == '*')
1243 working->hours = -1;
1244 else if (ul > INT_MAX)
1245 errx(1, "interval is too large:\n%s", errline);
1247 working->hours = ul;
1249 if (*ep == '\0' || strcmp(ep, "*") == 0)
1251 if (*ep != '@' && *ep != '$')
1252 errx(1, "malformed interval/at:\n%s", errline);
1254 working->flags |= CE_TRIMAT;
1255 working->trim_at = ptime_init(NULL);
1256 ptm_opts = PTM_PARSE_ISO8601;
1258 ptm_opts = PTM_PARSE_DWM;
1259 ptm_opts |= PTM_PARSE_MATCHDOM;
1260 res = ptime_relparse(working->trim_at, ptm_opts,
1261 ptimeget_secs(timenow), ep + 1);
1263 errx(1, "nonexistent time for 'at' value:\n%s",
1266 errx(1, "malformed 'at' value:\n%s", errline);
1273 q = parse = sob(parse + 1); /* Optional field */
1280 for (; q && *q && !isspacech(*q); q++) {
1281 switch (tolowerch(*q)) {
1283 working->flags |= CE_BINARY;
1286 working->flags |= CE_CREATE;
1289 working->flags |= CE_NODUMP;
1292 working->flags |= CE_GLOB;
1295 working->compress = COMPRESS_BZIP2;
1298 working->flags |= CE_NOSIGNAL;
1301 working->flags |= CE_PLAIN0;
1304 working->flags |= CE_PID2CMD;
1307 working->flags |= CE_RFC5424;
1310 working->flags |= CE_SIGNALGROUP;
1313 /* Deprecated flag - keep for compatibility purposes */
1316 working->compress = COMPRESS_XZ;
1319 working->compress = COMPRESS_GZIP;
1323 case 'f': /* Used by OpenBSD for "CE_FOLLOW" */
1324 case 'm': /* Used by OpenBSD for "CE_MONITOR" */
1326 errx(1, "illegal flag in config file -- %c",
1334 q = parse = sob(parse + 1); /* Optional field */
1341 working->pid_cmd_file = NULL;
1344 working->pid_cmd_file = strdup(q);
1345 else if (isalnum(*q))
1349 "illegal pid file or signal in config file:\n%s",
1356 q = parse = sob(parse + 1); /* Optional field */
1361 working->sig = SIGHUP;
1364 working->sig = parse_signal(q);
1365 if (working->sig < 1 || working->sig >= sys_nsig) {
1367 "illegal signal in config file:\n%s",
1373 * Finish figuring out what pid-file to use (if any) in
1374 * later processing if this logfile needs to be rotated.
1376 if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) {
1378 * This config-entry specified 'n' for nosignal,
1379 * see if it also specified an explicit pid_cmd_file.
1380 * This would be a pretty pointless combination.
1382 if (working->pid_cmd_file != NULL) {
1383 warnx("Ignoring '%s' because flag 'n' was specified in line:\n%s",
1384 working->pid_cmd_file, errline);
1385 free(working->pid_cmd_file);
1386 working->pid_cmd_file = NULL;
1388 } else if (working->pid_cmd_file == NULL) {
1390 * This entry did not specify the 'n' flag, which
1391 * means it should signal syslogd unless it had
1392 * specified some other pid-file (and obviously the
1393 * syslog pid-file will not be for a process-group).
1394 * Also, we should only try to notify syslog if we
1397 if (working->flags & CE_SIGNALGROUP) {
1398 warnx("Ignoring flag 'U' in line:\n%s",
1400 working->flags &= ~CE_SIGNALGROUP;
1403 working->pid_cmd_file = strdup(path_syslogpid);
1407 * Add this entry to the appropriate list of entries, unless
1408 * it was some kind of special entry (eg: <default>).
1411 ; /* Do not add to any list */
1412 } else if (working->flags & CE_GLOB) {
1413 STAILQ_INSERT_TAIL(glob_p, working, cf_nextp);
1415 STAILQ_INSERT_TAIL(work_p, working, cf_nextp);
1418 if (errline != NULL)
1423 missing_field(char *p, char *errline)
1427 errx(1, "missing field in config file:\n%s", errline);
1432 * In our sort we return it in the reverse of what qsort normally
1433 * would do, as we want the newest files first. If we have two
1434 * entries with the same time we don't really care about order.
1436 * Support function for qsort() in delete_oldest_timelog().
1439 oldlog_entry_compare(const void *a, const void *b)
1441 const struct oldlog_entry *ola = a, *olb = b;
1443 if (ola->t > olb->t)
1445 else if (ola->t < olb->t)
1452 * Check whether the file corresponding to dp is an archive of the logfile
1453 * logfname, based on the timefnamefmt format string. Return true and fill out
1454 * tm if this is the case; otherwise return false.
1457 validate_old_timelog(int fd, const struct dirent *dp, const char *logfname,
1461 size_t logfname_len;
1465 logfname_len = strlen(logfname);
1467 if (dp->d_type != DT_REG) {
1469 * Some filesystems (e.g. NFS) don't fill out the d_type field
1470 * and leave it set to DT_UNKNOWN; in this case we must obtain
1471 * the file type ourselves.
1473 if (dp->d_type != DT_UNKNOWN ||
1474 fstatat(fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) != 0 ||
1475 !S_ISREG(sb.st_mode))
1478 /* Ignore everything but files with our logfile prefix. */
1479 if (strncmp(dp->d_name, logfname, logfname_len) != 0)
1481 /* Ignore the actual non-rotated logfile. */
1482 if (dp->d_namlen == logfname_len)
1486 * Make sure we created have found a logfile, so the
1487 * postfix is valid, IE format is: '.<time>(.[bgx]z)?'.
1489 if (dp->d_name[logfname_len] != '.') {
1491 printf("Ignoring %s which has unexpected "
1492 "extension '%s'\n", dp->d_name,
1493 &dp->d_name[logfname_len]);
1496 memset(tm, 0, sizeof(*tm));
1497 if ((s = strptime(&dp->d_name[logfname_len + 1],
1498 timefnamefmt, tm)) == NULL) {
1500 * We could special case "old" sequentially named logfiles here,
1501 * but we do not as that would require special handling to
1502 * decide which one was the oldest compared to "new" time based
1506 printf("Ignoring %s which does not "
1507 "match time format\n", dp->d_name);
1511 for (c = 0; c < COMPRESS_TYPES; c++)
1512 if (strcmp(s, compress_type[c].suffix) == 0)
1517 printf("Ignoring %s which has unexpected extension '%s'\n",
1524 * Delete the oldest logfiles, when using time based filenames.
1527 delete_oldest_timelog(const struct conf_entry *ent, const char *archive_dir)
1529 char *logfname, *s, *dir, errbuf[80];
1530 int dir_fd, i, logcnt, max_logcnt;
1531 struct oldlog_entry *oldlogs;
1537 oldlogs = malloc(MAX_OLDLOGS * sizeof(struct oldlog_entry));
1538 max_logcnt = MAX_OLDLOGS;
1541 if (archive_dir != NULL && archive_dir[0] != '\0')
1544 if ((cdir = dirname(ent->log)) == NULL)
1545 err(1, "dirname()");
1546 if ((dir = strdup(cdir)) == NULL)
1549 if ((s = basename(ent->log)) == NULL)
1550 err(1, "basename()");
1551 if ((logfname = strdup(s)) == NULL)
1553 if (strcmp(logfname, "/") == 0)
1554 errx(1, "Invalid log filename - became '/'");
1557 printf("Searching for old logs in %s\n", dir);
1559 /* First we create a 'list' of all archived logfiles */
1560 if ((dirp = opendir(dir)) == NULL)
1561 err(1, "Cannot open log directory '%s'", dir);
1562 dir_fd = dirfd(dirp);
1563 while ((dp = readdir(dirp)) != NULL) {
1564 if (validate_old_timelog(dir_fd, dp, logfname, &tm) == 0)
1568 * We should now have old an old rotated logfile, so
1569 * add it to the 'list'.
1571 if ((oldlogs[logcnt].t = timegm(&tm)) == -1)
1572 err(1, "Could not convert time string to time value");
1573 if ((oldlogs[logcnt].fname = strdup(dp->d_name)) == NULL)
1578 * It is very unlikely we ever run out of space in the
1579 * logfile array from the default size, but lets
1580 * handle it anyway...
1582 if (logcnt >= max_logcnt) {
1584 /* Detect integer overflow */
1585 if (max_logcnt < logcnt)
1586 errx(1, "Too many old logfiles found");
1587 oldlogs = realloc(oldlogs,
1588 max_logcnt * sizeof(struct oldlog_entry));
1589 if (oldlogs == NULL)
1590 err(1, "realloc()");
1594 /* Second, if needed we delete oldest archived logfiles */
1595 if (logcnt > 0 && logcnt >= ent->numlogs && ent->numlogs > 1) {
1596 oldlogs = realloc(oldlogs, logcnt *
1597 sizeof(struct oldlog_entry));
1598 if (oldlogs == NULL)
1599 err(1, "realloc()");
1602 * We now sort the logs in the order of newest to
1603 * oldest. That way we can simply skip over the
1604 * number of records we want to keep.
1606 qsort(oldlogs, logcnt, sizeof(struct oldlog_entry),
1607 oldlog_entry_compare);
1608 for (i = ent->numlogs - 1; i < logcnt; i++) {
1610 printf("\trm -f %s/%s\n", dir,
1612 else if (unlinkat(dir_fd, oldlogs[i].fname, 0) != 0) {
1613 snprintf(errbuf, sizeof(errbuf),
1614 "Could not delete old logfile '%s'",
1619 } else if (verbose > 1)
1620 printf("No old logs to delete for logfile %s\n", ent->log);
1622 /* Third, cleanup */
1624 for (i = 0; i < logcnt; i++) {
1625 assert(oldlogs[i].fname != NULL);
1626 free(oldlogs[i].fname);
1634 * Generate a log filename, when using classic filenames.
1637 gen_classiclog_fname(char *fname, size_t fname_sz, const char *archive_dir,
1638 const char *namepart, int numlogs_c)
1641 if (archive_dir[0] != '\0')
1642 (void) snprintf(fname, fname_sz, "%s/%s.%d", archive_dir,
1643 namepart, numlogs_c);
1645 (void) snprintf(fname, fname_sz, "%s.%d", namepart, numlogs_c);
1649 * Delete a rotated logfile, when using classic filenames.
1652 delete_classiclog(const char *archive_dir, const char *namepart, int numlog_c)
1654 char file1[MAXPATHLEN], zfile1[MAXPATHLEN];
1657 gen_classiclog_fname(file1, sizeof(file1), archive_dir, namepart,
1660 for (c = 0; c < COMPRESS_TYPES; c++) {
1661 (void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1662 compress_type[c].suffix);
1664 printf("\trm -f %s\n", zfile1);
1666 (void) unlink(zfile1);
1671 * Only add to the queue if the file hasn't already been added. This is
1672 * done to prevent circular include loops.
1675 add_to_queue(const char *fname, struct ilist *inclist)
1677 struct include_entry *inc;
1679 STAILQ_FOREACH(inc, inclist, inc_nextp) {
1680 if (strcmp(fname, inc->file) == 0) {
1681 warnx("duplicate include detected: %s", fname);
1686 inc = malloc(sizeof(struct include_entry));
1688 err(1, "malloc of inc");
1689 inc->file = strdup(fname);
1692 printf("\t+ Adding %s to the processing queue.\n", fname);
1694 STAILQ_INSERT_TAIL(inclist, inc, inc_nextp);
1698 * Search for logfile and return its compression suffix (if supported)
1699 * The suffix detection is first-match in the order of compress_types
1701 * Note: if logfile without suffix exists (uncompressed, COMPRESS_NONE)
1702 * a zero-length string is returned
1705 get_logfile_suffix(const char *logfile)
1708 char zfile[MAXPATHLEN];
1711 for (c = 0; c < COMPRESS_TYPES; c++) {
1712 (void) strlcpy(zfile, logfile, MAXPATHLEN);
1713 (void) strlcat(zfile, compress_type[c].suffix, MAXPATHLEN);
1714 if (lstat(zfile, &st) == 0)
1715 return (compress_type[c].suffix);
1721 do_rotate(const struct conf_entry *ent)
1723 char dirpart[MAXPATHLEN], namepart[MAXPATHLEN];
1724 char file1[MAXPATHLEN], file2[MAXPATHLEN];
1725 char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN];
1726 const char *logfile_suffix;
1727 char datetimestr[30];
1728 int flags, numlogs_c;
1729 fk_entry free_or_keep;
1730 struct sigwork_entry *swork;
1736 free_or_keep = FREE_ENT;
1741 /* build complete name of archive directory into dirpart */
1742 if (*archdirname == '/') { /* absolute */
1743 strlcpy(dirpart, archdirname, sizeof(dirpart));
1744 } else { /* relative */
1745 /* get directory part of logfile */
1746 strlcpy(dirpart, ent->log, sizeof(dirpart));
1747 if ((p = strrchr(dirpart, '/')) == NULL)
1751 strlcat(dirpart, archdirname, sizeof(dirpart));
1754 /* check if archive directory exists, if not, create it */
1755 if (lstat(dirpart, &st))
1756 createdir(ent, dirpart);
1758 /* get filename part of logfile */
1759 if ((p = strrchr(ent->log, '/')) == NULL)
1760 strlcpy(namepart, ent->log, sizeof(namepart));
1762 strlcpy(namepart, p + 1, sizeof(namepart));
1765 * Tell utility functions we are not using an archive
1769 strlcpy(namepart, ent->log, sizeof(namepart));
1772 /* Delete old logs */
1773 if (timefnamefmt != NULL)
1774 delete_oldest_timelog(ent, dirpart);
1777 * Handle cleaning up after legacy newsyslog where we
1778 * kept ent->numlogs + 1 files. This code can go away
1779 * at some point in the future.
1781 delete_classiclog(dirpart, namepart, ent->numlogs);
1783 if (ent->numlogs > 0)
1784 delete_classiclog(dirpart, namepart, ent->numlogs - 1);
1788 if (timefnamefmt != NULL) {
1789 /* If time functions fails we can't really do any sensible */
1790 if (time(&now) == (time_t)-1 ||
1791 localtime_r(&now, &tm) == NULL)
1792 bzero(&tm, sizeof(tm));
1794 strftime(datetimestr, sizeof(datetimestr), timefnamefmt, &tm);
1796 (void) snprintf(file1, sizeof(file1), "%s/%s.%s",
1797 dirpart, namepart, datetimestr);
1799 (void) snprintf(file1, sizeof(file1), "%s.%s",
1800 ent->log, datetimestr);
1802 /* Don't run the code to move down logs */
1805 gen_classiclog_fname(file1, sizeof(file1), dirpart, namepart,
1807 numlogs_c = ent->numlogs - 2; /* copy for countdown */
1810 /* Move down log files */
1811 for (; numlogs_c >= 0; numlogs_c--) {
1812 (void) strlcpy(file2, file1, sizeof(file2));
1814 gen_classiclog_fname(file1, sizeof(file1), dirpart, namepart,
1817 logfile_suffix = get_logfile_suffix(file1);
1818 if (logfile_suffix == NULL)
1820 (void) strlcpy(zfile1, file1, MAXPATHLEN);
1821 (void) strlcpy(zfile2, file2, MAXPATHLEN);
1822 (void) strlcat(zfile1, logfile_suffix, MAXPATHLEN);
1823 (void) strlcat(zfile2, logfile_suffix, MAXPATHLEN);
1826 printf("\tmv %s %s\n", zfile1, zfile2);
1828 /* XXX - Ought to be checking for failure! */
1829 (void)rename(zfile1, zfile2);
1830 change_attrs(zfile2, ent);
1831 if (ent->compress && !strlen(logfile_suffix)) {
1832 /* compress old rotation */
1833 struct zipwork_entry zwork;
1835 memset(&zwork, 0, sizeof(zwork));
1836 zwork.zw_conf = ent;
1837 zwork.zw_fsize = sizefile(zfile2);
1838 strcpy(zwork.zw_fname, zfile2);
1844 if (ent->numlogs > 0) {
1847 * Note that savelog() may succeed with using link()
1848 * for the archtodir case, but there is no good way
1849 * of knowing if it will when doing "noaction", so
1850 * here we claim that it will have to do a copy...
1853 printf("\tcp %s %s\n", ent->log, file1);
1855 printf("\tln %s %s\n", ent->log, file1);
1856 printf("\ttouch %s\t\t"
1857 "# Update mtime for 'when'-interval processing\n",
1860 if (!(flags & CE_BINARY)) {
1861 /* Report the trimming to the old log */
1862 log_trim(ent->log, ent);
1864 savelog(ent->log, file1);
1866 * Interval-based rotations are done using the mtime of
1867 * the most recently archived log, so make sure it gets
1868 * updated during a rotation.
1870 utimes(file1, NULL);
1872 change_attrs(file1, ent);
1875 /* Create the new log file and move it into place */
1877 printf("Start new log...\n");
1881 * Save all signalling and file-compression to be done after log
1882 * files from all entries have been rotated. This way any one
1883 * process will not be sent the same signal multiple times when
1884 * multiple log files had to be rotated.
1887 if (ent->pid_cmd_file != NULL)
1888 swork = save_sigwork(ent);
1889 if (ent->numlogs > 0 && ent->compress > COMPRESS_NONE) {
1890 if (!(ent->flags & CE_PLAIN0) ||
1891 strcmp(&file1[strlen(file1) - 2], ".0") != 0) {
1893 * The zipwork_entry will include a pointer to this
1894 * conf_entry, so the conf_entry should not be freed.
1896 free_or_keep = KEEP_ENT;
1897 save_zipwork(ent, swork, ent->fsize, file1);
1901 return (free_or_keep);
1905 do_sigwork(struct sigwork_entry *swork)
1907 struct sigwork_entry *nextsig;
1911 if (swork->sw_runcmd == 0 && (!(swork->sw_pidok) || swork->sw_pid == 0))
1912 return; /* no work to do... */
1915 * If nosignal (-s) was specified, then do not signal any process.
1916 * Note that a nosignal request triggers a warning message if the
1917 * rotated logfile needs to be compressed, *unless* -R was also
1918 * specified. We assume that an `-sR' request came from a process
1919 * which writes to the logfile, and as such, we assume that process
1920 * has already made sure the logfile is not presently in use. This
1921 * just sets swork->sw_pidok to a special value, and do_zipwork
1922 * will print any necessary warning(s).
1926 swork->sw_pidok = -1;
1931 * Compute the pause between consecutive signals. Use a longer
1932 * sleep time if we will be sending two signals to the same
1933 * daemon or process-group.
1936 nextsig = SLIST_NEXT(swork, sw_nextp);
1937 if (nextsig != NULL) {
1938 if (swork->sw_pid == nextsig->sw_pid)
1945 if (swork->sw_runcmd)
1946 printf("\tsh -c '%s %d'\n", swork->sw_fname,
1949 printf("\tkill -%d %d \t\t# %s\n", swork->sw_signum,
1950 (int)swork->sw_pid, swork->sw_fname);
1952 printf("\tsleep %d\n", secs);
1957 if (swork->sw_runcmd) {
1958 asprintf(&tmp, "%s %d", swork->sw_fname, swork->sw_signum);
1960 warn("can't allocate memory to run %s",
1965 printf("Run command: %s\n", tmp);
1968 warnx("%s: returned non-zero exit code: %d",
1975 kres = kill(swork->sw_pid, swork->sw_signum);
1978 * Assume that "no such process" (ESRCH) is something
1979 * to warn about, but is not an error. Presumably the
1980 * process which writes to the rotated log file(s) is
1981 * gone, in which case we should have no problem with
1982 * compressing the rotated log file(s).
1985 swork->sw_pidok = 0;
1986 warn("can't notify %s, pid %d = %s", swork->sw_pidtype,
1987 (int)swork->sw_pid, swork->sw_fname);
1990 printf("Notified %s pid %d = %s\n", swork->sw_pidtype,
1991 (int)swork->sw_pid, swork->sw_fname);
1994 printf("Pause %d second(s) between signals\n",
2002 do_zipwork(struct zipwork_entry *zwork)
2004 const char *pgm_name, *pgm_path;
2005 int errsav, fcount, zstatus;
2007 char zresult[MAXPATHLEN];
2010 assert(zwork != NULL);
2012 strlcpy(zresult, zwork->zw_fname, sizeof(zresult));
2013 if (zwork->zw_conf != NULL &&
2014 zwork->zw_conf->compress > COMPRESS_NONE)
2015 for (c = 1; c < COMPRESS_TYPES; c++) {
2016 if (zwork->zw_conf->compress == c) {
2017 pgm_path = compress_type[c].path;
2018 (void) strlcat(zresult,
2019 compress_type[c].suffix, sizeof(zresult));
2023 if (pgm_path == NULL) {
2024 warnx("invalid entry for %s in do_zipwork", zwork->zw_fname);
2027 pgm_name = strrchr(pgm_path, '/');
2028 if (pgm_name == NULL)
2029 pgm_name = pgm_path;
2033 if (zwork->zw_swork != NULL && zwork->zw_swork->sw_runcmd == 0 &&
2034 zwork->zw_swork->sw_pidok <= 0) {
2036 "log %s not compressed because daemon(s) not notified",
2038 change_attrs(zwork->zw_fname, zwork->zw_conf);
2043 printf("\t%s %s\n", pgm_name, zwork->zw_fname);
2044 change_attrs(zresult, zwork->zw_conf);
2050 while (pidzip < 0) {
2052 * The fork failed. If the failure was due to a temporary
2053 * problem, then wait a short time and try it again.
2056 warn("fork() for `%s %s'", pgm_name, zwork->zw_fname);
2057 if (errsav != EAGAIN || fcount > 5)
2058 errx(1, "Exiting...");
2064 /* The child process executes the compression command */
2065 execl(pgm_path, pgm_path, "-f", zwork->zw_fname, (char *)0);
2066 err(1, "execl(`%s -f %s')", pgm_path, zwork->zw_fname);
2069 wpid = waitpid(pidzip, &zstatus, 0);
2071 /* XXX - should this be a fatal error? */
2072 warn("%s: waitpid(%d)", pgm_path, pidzip);
2075 if (!WIFEXITED(zstatus)) {
2076 warnx("`%s -f %s' did not terminate normally", pgm_name,
2080 if (WEXITSTATUS(zstatus)) {
2081 warnx("`%s -f %s' terminated with a non-zero status (%d)",
2082 pgm_name, zwork->zw_fname, WEXITSTATUS(zstatus));
2086 /* Compression was successful, set file attributes on the result. */
2087 change_attrs(zresult, zwork->zw_conf);
2091 * Save information on any process we need to signal. Any single
2092 * process may need to be sent different signal-values for different
2093 * log files, but usually a single signal-value will cause the process
2094 * to close and re-open all of it's log files.
2096 static struct sigwork_entry *
2097 save_sigwork(const struct conf_entry *ent)
2099 struct sigwork_entry *sprev, *stmp;
2105 SLIST_FOREACH(stmp, &swhead, sw_nextp) {
2106 ndiff = strcmp(ent->pid_cmd_file, stmp->sw_fname);
2110 if (ent->sig == stmp->sw_signum)
2112 if (ent->sig > stmp->sw_signum) {
2119 if (stmp != NULL && ndiff == 0)
2122 tmpsiz = sizeof(struct sigwork_entry) + strlen(ent->pid_cmd_file) + 1;
2123 stmp = malloc(tmpsiz);
2125 stmp->sw_runcmd = 0;
2126 /* If this is a command to run we just set the flag and run command */
2127 if (ent->flags & CE_PID2CMD) {
2130 stmp->sw_runcmd = 1;
2132 set_swpid(stmp, ent);
2134 stmp->sw_signum = ent->sig;
2135 strcpy(stmp->sw_fname, ent->pid_cmd_file);
2137 SLIST_INSERT_HEAD(&swhead, stmp, sw_nextp);
2139 SLIST_INSERT_AFTER(sprev, stmp, sw_nextp);
2144 * Save information on any file we need to compress. We may see the same
2145 * file multiple times, so check the full list to avoid duplicates. The
2146 * list itself is sorted smallest-to-largest, because that's the order we
2147 * want to compress the files. If the partition is very low on disk space,
2148 * then the smallest files are the most likely to compress, and compressing
2149 * them first will free up more space for the larger files.
2151 static struct zipwork_entry *
2152 save_zipwork(const struct conf_entry *ent, const struct sigwork_entry *swork,
2153 int zsize, const char *zipfname)
2155 struct zipwork_entry *zprev, *ztmp;
2159 /* Compute the size if the caller did not know it. */
2161 zsize = sizefile(zipfname);
2165 SLIST_FOREACH(ztmp, &zwhead, zw_nextp) {
2166 ndiff = strcmp(zipfname, ztmp->zw_fname);
2169 if (zsize > ztmp->zw_fsize)
2172 if (ztmp != NULL && ndiff == 0)
2175 tmpsiz = sizeof(struct zipwork_entry) + strlen(zipfname) + 1;
2176 ztmp = malloc(tmpsiz);
2177 ztmp->zw_conf = ent;
2178 ztmp->zw_swork = swork;
2179 ztmp->zw_fsize = zsize;
2180 strcpy(ztmp->zw_fname, zipfname);
2182 SLIST_INSERT_HEAD(&zwhead, ztmp, zw_nextp);
2184 SLIST_INSERT_AFTER(zprev, ztmp, zw_nextp);
2188 /* Send a signal to the pid specified by pidfile */
2190 set_swpid(struct sigwork_entry *swork, const struct conf_entry *ent)
2193 long minok, maxok, rval;
2194 char *endp, *linep, line[BUFSIZ];
2198 swork->sw_pidok = 0;
2200 swork->sw_pidtype = "daemon";
2201 if (ent->flags & CE_SIGNALGROUP) {
2203 * If we are expected to signal a process-group when
2204 * rotating this logfile, then the value read in should
2205 * be the negative of a valid process ID.
2209 swork->sw_pidtype = "process-group";
2212 f = fopen(ent->pid_cmd_file, "r");
2214 if (errno == ENOENT && enforcepid == 0) {
2216 * Warn if the PID file doesn't exist, but do
2217 * not consider it an error. Most likely it
2218 * means the process has been terminated,
2219 * so it should be safe to rotate any log
2220 * files that the process would have been using.
2222 swork->sw_pidok = 1;
2223 warnx("pid file doesn't exist: %s", ent->pid_cmd_file);
2225 warn("can't open pid file: %s", ent->pid_cmd_file);
2229 if (fgets(line, BUFSIZ, f) == NULL) {
2231 * Warn if the PID file is empty, but do not consider
2232 * it an error. Most likely it means the process has
2233 * has terminated, so it should be safe to rotate any
2234 * log files that the process would have been using.
2236 if (feof(f) && enforcepid == 0) {
2237 swork->sw_pidok = 1;
2238 warnx("pid/cmd file is empty: %s", ent->pid_cmd_file);
2240 warn("can't read from pid file: %s", ent->pid_cmd_file);
2248 while (*linep == ' ')
2250 rval = strtol(linep, &endp, 10);
2251 if (*endp != '\0' && !isspacech(*endp)) {
2252 warnx("pid file does not start with a valid number: %s",
2254 } else if (rval < minok || rval > maxok) {
2255 warnx("bad value '%ld' for process number in %s",
2256 rval, ent->pid_cmd_file);
2258 warnx("\t(expecting value between %ld and %ld)",
2261 swork->sw_pidok = 1;
2262 swork->sw_pid = rval;
2268 /* Log the fact that the logs were turned over */
2270 log_trim(const char *logname, const struct conf_entry *log_ent)
2275 if ((f = fopen(logname, "a")) == NULL)
2278 if (log_ent->def_cfg)
2279 xtra = " using <default> rule";
2280 if (log_ent->flags & CE_RFC5424) {
2281 if (log_ent->firstcreate) {
2282 fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s\n",
2283 LOG_MAKEPRI(LOG_USER, LOG_INFO),
2284 daytime_rfc5424, hostname, getpid(),
2285 "logfile first created", xtra);
2286 } else if (log_ent->r_reason != NULL) {
2287 fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s%s\n",
2288 LOG_MAKEPRI(LOG_USER, LOG_INFO),
2289 daytime_rfc5424, hostname, getpid(),
2290 "logfile turned over", log_ent->r_reason, xtra);
2292 fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s\n",
2293 LOG_MAKEPRI(LOG_USER, LOG_INFO),
2294 daytime_rfc5424, hostname, getpid(),
2295 "logfile turned over", xtra);
2298 if (log_ent->firstcreate)
2300 "%s %.*s newsyslog[%d]: logfile first created%s\n",
2301 daytime, (int)hostname_shortlen, hostname, getpid(),
2303 else if (log_ent->r_reason != NULL)
2305 "%s %.*s newsyslog[%d]: logfile turned over%s%s\n",
2306 daytime, (int)hostname_shortlen, hostname, getpid(),
2307 log_ent->r_reason, xtra);
2310 "%s %.*s newsyslog[%d]: logfile turned over%s\n",
2311 daytime, (int)hostname_shortlen, hostname, getpid(),
2314 if (fclose(f) == EOF)
2315 err(1, "log_trim: fclose");
2319 /* Return size in kilobytes of a file */
2321 sizefile(const char *file)
2325 if (stat(file, &sb) < 0)
2327 return (kbytes(sb.st_size));
2331 * Return the mtime of the most recent archive of the logfile, using timestamp
2335 mtime_old_timelog(const char *file)
2343 char *s, *logfname, *dir;
2347 if ((dir = dirname(file)) == NULL) {
2348 warn("dirname() of '%s'", file);
2351 if ((s = basename(file)) == NULL) {
2352 warn("basename() of '%s'", file);
2354 } else if (s[0] == '/') {
2355 warnx("Invalid log filename '%s'", s);
2357 } else if ((logfname = strdup(s)) == NULL)
2360 if ((dirp = opendir(dir)) == NULL) {
2361 warn("Cannot open log directory '%s'", dir);
2364 dir_fd = dirfd(dirp);
2365 /* Open the archive dir and find the most recent archive of logfname. */
2366 while ((dp = readdir(dirp)) != NULL) {
2367 if (validate_old_timelog(dir_fd, dp, logfname, &tm) == 0)
2370 if (fstatat(dir_fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
2371 warn("Cannot stat '%s'", file);
2374 if (t < sb.st_mtime)
2382 /* Return the age in hours of the most recent archive of the logfile. */
2384 age_old_log(const char *file)
2387 const char *logfile_suffix;
2388 char tmp[MAXPATHLEN + sizeof(".0") + COMPRESS_SUFFIX_MAXLEN + 1];
2394 /* build name of archive directory into tmp */
2395 if (*archdirname == '/') { /* absolute */
2396 strlcpy(tmp, archdirname, sizeof(tmp));
2397 } else { /* relative */
2398 /* get directory part of logfile */
2399 strlcpy(tmp, file, sizeof(tmp));
2400 if ((p = strrchr(tmp, '/')) == NULL)
2404 strlcat(tmp, archdirname, sizeof(tmp));
2407 strlcat(tmp, "/", sizeof(tmp));
2409 /* get filename part of logfile */
2410 if ((p = strrchr(file, '/')) == NULL)
2411 strlcat(tmp, file, sizeof(tmp));
2413 strlcat(tmp, p + 1, sizeof(tmp));
2415 (void) strlcpy(tmp, file, sizeof(tmp));
2418 if (timefnamefmt != NULL) {
2419 mtime = mtime_old_timelog(tmp);
2423 strlcat(tmp, ".0", sizeof(tmp));
2424 logfile_suffix = get_logfile_suffix(tmp);
2425 if (logfile_suffix == NULL)
2427 (void) strlcat(tmp, logfile_suffix, sizeof(tmp));
2428 if (stat(tmp, &sb) < 0)
2430 mtime = sb.st_mtime;
2433 return ((int)(ptimeget_secs(timenow) - mtime + 1800) / 3600);
2436 /* Skip Over Blanks */
2440 while (p && *p && isspace(*p))
2445 /* Skip Over Non-Blanks */
2449 while (p && *p && !isspace(*p))
2454 /* Check if string is actually a number */
2456 isnumberstr(const char *string)
2459 if (!isdigitch(*string++))
2465 /* Check if string contains a glob */
2467 isglobstr(const char *string)
2471 while ((chr = *string++)) {
2472 if (chr == '*' || chr == '?' || chr == '[')
2479 * Save the active log file under a new name. A link to the new name
2480 * is the quick-and-easy way to do this. If that fails (which it will
2481 * if the destination is on another partition), then make a copy of
2482 * the file to the new location.
2485 savelog(char *from, char *to)
2490 res = link(from, to);
2494 if ((src = fopen(from, "r")) == NULL)
2495 err(1, "can't fopen %s for reading", from);
2496 if ((dst = fopen(to, "w")) == NULL)
2497 err(1, "can't fopen %s for writing", to);
2499 while ((c = getc(src)) != EOF) {
2500 if ((putc(c, dst)) == EOF)
2501 err(1, "error writing to %s", to);
2505 err(1, "error reading from %s", from);
2506 if ((fclose(src)) != 0)
2507 err(1, "can't fclose %s", to);
2508 if ((fclose(dst)) != 0)
2509 err(1, "can't fclose %s", from);
2512 /* create one or more directory components of a path */
2514 createdir(const struct conf_entry *ent, char *dirpart)
2518 char mkdirpath[MAXPATHLEN];
2526 if (*s != '/' && *s != '\0')
2529 res = lstat(mkdirpath, &st);
2532 printf("\tmkdir %s\n", mkdirpath);
2534 res = mkdir(mkdirpath, 0755);
2536 err(1, "Error on mkdir(\"%s\") for -a",
2544 if (ent->firstcreate)
2545 printf("Created directory '%s' for new %s\n",
2548 printf("Created directory '%s' for -a\n", dirpart);
2553 * Create a new log file, destroying any currently-existing version
2554 * of the log file in the process. If the caller wants a backup copy
2555 * of the file to exist, they should call 'link(logfile,logbackup)'
2556 * before calling this routine.
2559 createlog(const struct conf_entry *ent)
2563 char *realfile, *slash, tempfile[MAXPATHLEN];
2566 realfile = ent->log;
2569 * If this log file is being created for the first time (-C option),
2570 * then it may also be true that the parent directory does not exist
2571 * yet. Check, and create that directory if it is missing.
2573 if (ent->firstcreate) {
2574 strlcpy(tempfile, realfile, sizeof(tempfile));
2575 slash = strrchr(tempfile, '/');
2576 if (slash != NULL) {
2578 failed = stat(tempfile, &st);
2579 if (failed && errno != ENOENT)
2580 err(1, "Error on stat(%s)", tempfile);
2582 createdir(ent, tempfile);
2583 else if (!S_ISDIR(st.st_mode))
2584 errx(1, "%s exists but is not a directory",
2590 * First create an unused filename, so it can be chown'ed and
2591 * chmod'ed before it is moved into the real location. mkstemp
2592 * will create the file mode=600 & owned by us. Note that all
2593 * temp files will have a suffix of '.z<something>'.
2595 strlcpy(tempfile, realfile, sizeof(tempfile));
2596 strlcat(tempfile, ".zXXXXXX", sizeof(tempfile));
2598 printf("\tmktemp %s\n", tempfile);
2600 fd = mkstemp(tempfile);
2602 err(1, "can't mkstemp logfile %s", tempfile);
2605 * Add status message to what will become the new log file.
2607 if (!(ent->flags & CE_BINARY)) {
2608 if (log_trim(tempfile, ent))
2609 err(1, "can't add status message to log");
2613 /* Change the owner/group, if we are supposed to */
2614 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2616 printf("\tchown %u:%u %s\n", ent->uid, ent->gid,
2619 failed = fchown(fd, ent->uid, ent->gid);
2621 err(1, "can't fchown temp file %s", tempfile);
2625 /* Turn on NODUMP if it was requested in the config-file. */
2626 if (ent->flags & CE_NODUMP) {
2628 printf("\tchflags nodump %s\n", tempfile);
2630 failed = fchflags(fd, UF_NODUMP);
2632 warn("log_trim: fchflags(NODUMP)");
2638 * Note that if the real logfile still exists, and if the call
2639 * to rename() fails, then "neither the old file nor the new
2640 * file shall be changed or created" (to quote the standard).
2641 * If the call succeeds, then the file will be replaced without
2642 * any window where some other process might find that the file
2644 * XXX - ? It may be that for some error conditions, we could
2645 * retry by first removing the realfile and then renaming.
2648 printf("\tchmod %o %s\n", ent->permissions, tempfile);
2649 printf("\tmv %s %s\n", tempfile, realfile);
2651 failed = fchmod(fd, ent->permissions);
2653 err(1, "can't fchmod temp file '%s'", tempfile);
2654 failed = rename(tempfile, realfile);
2656 err(1, "can't mv %s to %s", tempfile, realfile);
2664 * Change the attributes of a given filename to what was specified in
2665 * the newsyslog.conf entry. This routine is only called for files
2666 * that newsyslog expects that it has created, and thus it is a fatal
2667 * error if this routine finds that the file does not exist.
2670 change_attrs(const char *fname, const struct conf_entry *ent)
2675 printf("\tchmod %o %s\n", ent->permissions, fname);
2677 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
2678 printf("\tchown %u:%u %s\n",
2679 ent->uid, ent->gid, fname);
2681 if (ent->flags & CE_NODUMP)
2682 printf("\tchflags nodump %s\n", fname);
2686 failed = chmod(fname, ent->permissions);
2689 err(1, "chmod(%s) in change_attrs", fname);
2690 warn("change_attrs couldn't chmod(%s)", fname);
2693 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2694 failed = chown(fname, ent->uid, ent->gid);
2696 warn("can't chown %s", fname);
2699 if (ent->flags & CE_NODUMP) {
2700 failed = chflags(fname, UF_NODUMP);
2702 warn("can't chflags %s NODUMP", fname);
2707 * Parse a signal number or signal name. Returns the signal number parsed or -1
2711 parse_signal(const char *str)
2716 sig = strtonum(str, 1, sys_nsig - 1, &errstr);
2720 if (strncasecmp(str, "SIG", 3) == 0)
2723 for (i = 1; i < sys_nsig; i++) {
2724 if (strcasecmp(str, sys_signame[i]) == 0)