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 #ifndef COMPRESS_SUFFIX_ZST
105 #define COMPRESS_SUFFIX_ZST ".zst"
108 #define COMPRESS_SUFFIX_MAXLEN MAX(MAX(sizeof(COMPRESS_SUFFIX_GZ),sizeof(COMPRESS_SUFFIX_BZ2)),sizeof(COMPRESS_SUFFIX_XZ))
113 #define COMPRESS_TYPES 5 /* Number of supported compression types */
115 #define COMPRESS_NONE 0
116 #define COMPRESS_GZIP 1
117 #define COMPRESS_BZIP2 2
118 #define COMPRESS_XZ 3
119 #define COMPRESS_ZSTD 4
122 * Bit-values for the 'flags' parsed from a config-file entry.
124 #define CE_BINARY 0x0008 /* Logfile is in binary, do not add status */
125 /* messages to logfile(s) when rotating. */
126 #define CE_NOSIGNAL 0x0010 /* There is no process to signal when */
127 /* trimming this file. */
128 #define CE_TRIMAT 0x0020 /* trim file at a specific time. */
129 #define CE_GLOB 0x0040 /* name of the log is file name pattern. */
130 #define CE_SIGNALGROUP 0x0080 /* Signal a process-group instead of a single */
131 /* process when trimming this file. */
132 #define CE_CREATE 0x0100 /* Create the log file if it does not exist. */
133 #define CE_NODUMP 0x0200 /* Set 'nodump' on newly created log file. */
134 #define CE_PID2CMD 0x0400 /* Replace PID file with a shell command.*/
136 #define CE_RFC5424 0x0800 /* Use RFC5424 format rotation message */
138 #define MIN_PID 5 /* Don't touch pids lower than this */
139 #define MAX_PID 99999 /* was lower, see /usr/include/sys/proc.h */
141 #define kbytes(size) (((size) + 1023) >> 10)
143 #define DEFAULT_MARKER "<default>"
144 #define DEBUG_MARKER "<debug>"
145 #define INCLUDE_MARKER "<include>"
146 #define DEFAULT_TIMEFNAME_FMT "%Y%m%dT%H%M%S"
148 #define MAX_OLDLOGS 65536 /* Default maximum number of old logfiles */
150 struct compress_types {
151 const char *flag; /* Flag in configuration file */
152 const char *suffix; /* Compression suffix */
153 const char *path; /* Path to compression program */
156 static const struct compress_types compress_type[COMPRESS_TYPES] = {
157 { "", "", "" }, /* no compression */
158 { "Z", COMPRESS_SUFFIX_GZ, _PATH_GZIP }, /* gzip compression */
159 { "J", COMPRESS_SUFFIX_BZ2, _PATH_BZIP2 }, /* bzip2 compression */
160 { "X", COMPRESS_SUFFIX_XZ, _PATH_XZ }, /* xz compression */
161 { "Y", COMPRESS_SUFFIX_ZST, _PATH_ZSTD } /* zst compression */
165 STAILQ_ENTRY(conf_entry) cf_nextp;
166 char *log; /* Name of the log */
167 char *pid_cmd_file; /* PID or command file */
168 char *r_reason; /* The reason this file is being rotated */
169 int firstcreate; /* Creating log for the first time (-C). */
170 int rotate; /* Non-zero if this file should be rotated */
171 int fsize; /* size found for the log file */
172 uid_t uid; /* Owner of log */
173 gid_t gid; /* Group of log */
174 int numlogs; /* Number of logs to keep */
175 int trsize; /* Size cutoff to trigger trimming the log */
176 int hours; /* Hours between log trimming */
177 struct ptime_data *trim_at; /* Specific time to do trimming */
178 unsigned int permissions; /* File permissions on the log */
179 int flags; /* CE_BINARY */
180 int compress; /* Compression */
181 int sig; /* Signal to send */
182 int def_cfg; /* Using the <default> rule for this file */
185 struct sigwork_entry {
186 SLIST_ENTRY(sigwork_entry) sw_nextp;
187 int sw_signum; /* the signal to send */
188 int sw_pidok; /* true if pid value is valid */
189 pid_t sw_pid; /* the process id from the PID file */
190 const char *sw_pidtype; /* "daemon" or "process group" */
191 int sw_runcmd; /* run command or send PID to signal */
192 char sw_fname[1]; /* file the PID was read from or shell cmd */
195 struct zipwork_entry {
196 SLIST_ENTRY(zipwork_entry) zw_nextp;
197 const struct conf_entry *zw_conf; /* for chown/perm/flag info */
198 const struct sigwork_entry *zw_swork; /* to know success of signal */
199 int zw_fsize; /* size of the file to compress */
200 char zw_fname[1]; /* the file to compress */
203 struct include_entry {
204 STAILQ_ENTRY(include_entry) inc_nextp;
205 const char *file; /* Name of file to process */
208 struct oldlog_entry {
209 char *fname; /* Filename of the log file */
210 time_t t; /* Parsed timestamp of the logfile */
217 STAILQ_HEAD(cflist, conf_entry);
218 static SLIST_HEAD(swlisthead, sigwork_entry) swhead =
219 SLIST_HEAD_INITIALIZER(swhead);
220 static SLIST_HEAD(zwlisthead, zipwork_entry) zwhead =
221 SLIST_HEAD_INITIALIZER(zwhead);
222 STAILQ_HEAD(ilist, include_entry);
224 int dbg_at_times; /* -D Show details of 'trim_at' code */
226 static int archtodir = 0; /* Archive old logfiles to other directory */
227 static int createlogs; /* Create (non-GLOB) logfiles which do not */
228 /* already exist. 1=='for entries with */
229 /* C flag', 2=='for all entries'. */
230 int verbose = 0; /* Print out what's going on */
231 static int needroot = 1; /* Root privs are necessary */
232 int noaction = 0; /* Don't do anything, just show it */
233 static int norotate = 0; /* Don't rotate */
234 static int nosignal; /* Do not send any signals */
235 static int enforcepid = 0; /* If PID file does not exist or empty, do nothing */
236 static int force = 0; /* Force the trim no matter what */
237 static int rotatereq = 0; /* -R = Always rotate the file(s) as given */
238 /* on the command (this also requires */
239 /* that a list of files *are* given on */
240 /* the run command). */
241 static char *requestor; /* The name given on a -R request */
242 static char *timefnamefmt = NULL;/* Use time based filenames instead of .0 */
243 static char *archdirname; /* Directory path to old logfiles archive */
244 static char *destdir = NULL; /* Directory to treat at root for logs */
245 static const char *conf; /* Configuration file to use */
247 struct ptime_data *dbg_timenow; /* A "timenow" value set via -D option */
248 static struct ptime_data *timenow; /* The time to use for checking at-fields */
250 #define DAYTIME_LEN 16
251 static char daytime[DAYTIME_LEN];/* The current time in human readable form,
252 * used for rotation-tracking messages. */
254 /* Another buffer to hold the current time in RFC5424 format. Fractional
255 * seconds are allowed by the RFC, but are not included in the
256 * rotation-tracking messages written by newsyslog and so are not accounted for
257 * in the length below.
259 #define DAYTIME_RFC5424_LEN sizeof("YYYY-MM-DDTHH:MM:SS+00:00")
260 static char daytime_rfc5424[DAYTIME_RFC5424_LEN];
262 static char hostname[MAXHOSTNAMELEN]; /* hostname */
264 static const char *path_syslogpid = _PATH_SYSLOGPID;
266 static struct cflist *get_worklist(char **files);
267 static void parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
268 struct conf_entry *defconf_p, struct ilist *inclist);
269 static void add_to_queue(const char *fname, struct ilist *inclist);
270 static char *sob(char *p);
271 static char *son(char *p);
272 static int isnumberstr(const char *);
273 static int isglobstr(const char *);
274 static char *missing_field(char *p, char *errline);
275 static void change_attrs(const char *, const struct conf_entry *);
276 static const char *get_logfile_suffix(const char *logfile);
277 static fk_entry do_entry(struct conf_entry *);
278 static fk_entry do_rotate(const struct conf_entry *);
279 static void do_sigwork(struct sigwork_entry *);
280 static void do_zipwork(struct zipwork_entry *);
281 static struct sigwork_entry *
282 save_sigwork(const struct conf_entry *);
283 static struct zipwork_entry *
284 save_zipwork(const struct conf_entry *, const struct
285 sigwork_entry *, int, const char *);
286 static void set_swpid(struct sigwork_entry *, const struct conf_entry *);
287 static int sizefile(const char *);
288 static void expand_globs(struct cflist *work_p, struct cflist *glob_p);
289 static void free_clist(struct cflist *list);
290 static void free_entry(struct conf_entry *ent);
291 static struct conf_entry *init_entry(const char *fname,
292 struct conf_entry *src_entry);
293 static void parse_args(int argc, char **argv);
294 static int parse_doption(const char *doption);
295 static void usage(void);
296 static int log_trim(const char *logname, const struct conf_entry *log_ent);
297 static int age_old_log(const char *file);
298 static void savelog(char *from, char *to);
299 static void createdir(const struct conf_entry *ent, char *dirpart);
300 static void createlog(const struct conf_entry *ent);
301 static int parse_signal(const char *str);
304 * All the following take a parameter of 'int', but expect values in the
305 * range of unsigned char. Define wrappers which take values of type 'char',
306 * whether signed or unsigned, and ensure they end up in the right range.
308 #define isdigitch(Anychar) isdigit((u_char)(Anychar))
309 #define isprintch(Anychar) isprint((u_char)(Anychar))
310 #define isspacech(Anychar) isspace((u_char)(Anychar))
311 #define tolowerch(Anychar) tolower((u_char)(Anychar))
314 main(int argc, char **argv)
316 struct cflist *worklist;
317 struct conf_entry *p;
318 struct sigwork_entry *stmp;
319 struct zipwork_entry *ztmp;
324 parse_args(argc, argv);
328 if (needroot && getuid() && geteuid())
329 errx(1, "must have root privs");
330 worklist = get_worklist(argv);
333 * Rotate all the files which need to be rotated. Note that
334 * some users have *hundreds* of entries in newsyslog.conf!
336 while (!STAILQ_EMPTY(worklist)) {
337 p = STAILQ_FIRST(worklist);
338 STAILQ_REMOVE_HEAD(worklist, cf_nextp);
339 if (do_entry(p) == FREE_ENT)
344 * Send signals to any processes which need a signal to tell
345 * them to close and re-open the log file(s) we have rotated.
346 * Note that zipwork_entries include pointers to these
347 * sigwork_entry's, so we can not free the entries here.
349 if (!SLIST_EMPTY(&swhead)) {
350 if (noaction || verbose)
351 printf("Signal all daemon process(es)...\n");
352 SLIST_FOREACH(stmp, &swhead, sw_nextp)
354 if (!(rotatereq && nosignal)) {
356 printf("\tsleep 10\n");
359 printf("Pause 10 seconds to allow "
360 "daemon(s) to close log file(s)\n");
366 * Compress all files that we're expected to compress, now
367 * that all processes should have closed the files which
370 if (!SLIST_EMPTY(&zwhead)) {
371 if (noaction || verbose)
372 printf("Compress all rotated log file(s)...\n");
373 while (!SLIST_EMPTY(&zwhead)) {
374 ztmp = SLIST_FIRST(&zwhead);
376 SLIST_REMOVE_HEAD(&zwhead, zw_nextp);
380 /* Now free all the sigwork entries. */
381 while (!SLIST_EMPTY(&swhead)) {
382 stmp = SLIST_FIRST(&swhead);
383 SLIST_REMOVE_HEAD(&swhead, sw_nextp);
387 while (wait(NULL) > 0 || errno == EINTR)
392 static struct conf_entry *
393 init_entry(const char *fname, struct conf_entry *src_entry)
395 struct conf_entry *tempwork;
398 printf("\t--> [creating entry for %s]\n", fname);
400 tempwork = malloc(sizeof(struct conf_entry));
401 if (tempwork == NULL)
402 err(1, "malloc of conf_entry for %s", fname);
404 if (destdir == NULL || fname[0] != '/')
405 tempwork->log = strdup(fname);
407 asprintf(&tempwork->log, "%s%s", destdir, fname);
408 if (tempwork->log == NULL)
409 err(1, "strdup for %s", fname);
411 if (src_entry != NULL) {
412 tempwork->pid_cmd_file = NULL;
413 if (src_entry->pid_cmd_file)
414 tempwork->pid_cmd_file = strdup(src_entry->pid_cmd_file);
415 tempwork->r_reason = NULL;
416 tempwork->firstcreate = 0;
417 tempwork->rotate = 0;
418 tempwork->fsize = -1;
419 tempwork->uid = src_entry->uid;
420 tempwork->gid = src_entry->gid;
421 tempwork->numlogs = src_entry->numlogs;
422 tempwork->trsize = src_entry->trsize;
423 tempwork->hours = src_entry->hours;
424 tempwork->trim_at = NULL;
425 if (src_entry->trim_at != NULL)
426 tempwork->trim_at = ptime_init(src_entry->trim_at);
427 tempwork->permissions = src_entry->permissions;
428 tempwork->flags = src_entry->flags;
429 tempwork->compress = src_entry->compress;
430 tempwork->sig = src_entry->sig;
431 tempwork->def_cfg = src_entry->def_cfg;
433 /* Initialize as a "do-nothing" entry */
434 tempwork->pid_cmd_file = NULL;
435 tempwork->r_reason = NULL;
436 tempwork->firstcreate = 0;
437 tempwork->rotate = 0;
438 tempwork->fsize = -1;
439 tempwork->uid = (uid_t)-1;
440 tempwork->gid = (gid_t)-1;
441 tempwork->numlogs = 1;
442 tempwork->trsize = -1;
443 tempwork->hours = -1;
444 tempwork->trim_at = NULL;
445 tempwork->permissions = 0;
447 tempwork->compress = COMPRESS_NONE;
448 tempwork->sig = SIGHUP;
449 tempwork->def_cfg = 0;
456 free_entry(struct conf_entry *ent)
462 if (ent->log != NULL) {
464 printf("\t--> [freeing entry for %s]\n", ent->log);
469 if (ent->pid_cmd_file != NULL) {
470 free(ent->pid_cmd_file);
471 ent->pid_cmd_file = NULL;
474 if (ent->r_reason != NULL) {
476 ent->r_reason = NULL;
479 if (ent->trim_at != NULL) {
480 ptime_free(ent->trim_at);
488 free_clist(struct cflist *list)
490 struct conf_entry *ent;
492 while (!STAILQ_EMPTY(list)) {
493 ent = STAILQ_FIRST(list);
494 STAILQ_REMOVE_HEAD(list, cf_nextp);
503 do_entry(struct conf_entry * ent)
505 #define REASON_MAX 80
507 fk_entry free_or_keep;
509 char temp_reason[REASON_MAX];
512 free_or_keep = FREE_ENT;
514 printf("%s <%d%s>: ", ent->log, ent->numlogs,
515 compress_type[ent->compress].flag);
516 ent->fsize = sizefile(ent->log);
517 oversized = ((ent->trsize > 0) && (ent->fsize >= ent->trsize));
518 modtime = age_old_log(ent->log);
520 ent->firstcreate = 0;
521 if (ent->fsize < 0) {
523 * If either the C flag or the -C option was specified,
524 * and if we won't be creating the file, then have the
525 * verbose message include a hint as to why the file
526 * will not be created.
528 temp_reason[0] = '\0';
530 ent->firstcreate = 1;
531 else if ((ent->flags & CE_CREATE) && createlogs)
532 ent->firstcreate = 1;
533 else if (ent->flags & CE_CREATE)
534 strlcpy(temp_reason, " (no -C option)", REASON_MAX);
536 strlcpy(temp_reason, " (no C flag)", REASON_MAX);
538 if (ent->firstcreate) {
540 printf("does not exist -> will create.\n");
542 } else if (verbose) {
543 printf("does not exist, skipped%s.\n", temp_reason);
546 if (ent->flags & CE_TRIMAT && !force && !rotatereq &&
548 diffsecs = ptimeget_diff(timenow, ent->trim_at);
549 if (diffsecs < 0.0) {
550 /* trim_at is some time in the future. */
552 ptime_adjust4dst(ent->trim_at,
554 printf("--> will trim at %s",
555 ptimeget_ctime(ent->trim_at));
557 return (free_or_keep);
558 } else if (diffsecs >= 3600.0) {
560 * trim_at is more than an hour in the past,
561 * so find the next valid trim_at time, and
562 * tell the user what that will be.
564 if (verbose && dbg_at_times)
565 printf("\n\t--> prev trim at %s\t",
566 ptimeget_ctime(ent->trim_at));
568 ptimeset_nxtime(ent->trim_at);
569 printf("--> will trim at %s",
570 ptimeget_ctime(ent->trim_at));
572 return (free_or_keep);
573 } else if (verbose && noaction && dbg_at_times) {
575 * If we are just debugging at-times, then
576 * a detailed message is helpful. Also
577 * skip "doing" any commands, since they
578 * would all be turned off by no-action.
580 printf("\n\t--> timematch at %s",
581 ptimeget_ctime(ent->trim_at));
582 return (free_or_keep);
583 } else if (verbose && ent->hours <= 0) {
584 printf("--> time is up\n");
587 if (verbose && (ent->trsize > 0))
588 printf("size (Kb): %d [%d] ", ent->fsize, ent->trsize);
589 if (verbose && (ent->hours > 0))
590 printf(" age (hr): %d [%d] ", modtime, ent->hours);
593 * Figure out if this logfile needs to be rotated.
595 temp_reason[0] = '\0';
598 snprintf(temp_reason, REASON_MAX, " due to -R from %s",
602 snprintf(temp_reason, REASON_MAX, " due to -F request");
603 } else if (oversized) {
605 snprintf(temp_reason, REASON_MAX, " due to size>%dK",
607 } else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) {
609 } else if ((ent->hours > 0) && ((modtime >= ent->hours) ||
615 * If the file needs to be rotated, then rotate it.
617 if (ent->rotate && !norotate) {
618 if (temp_reason[0] != '\0')
619 ent->r_reason = strdup(temp_reason);
621 printf("--> trimming log....\n");
622 if (noaction && !verbose)
623 printf("%s <%d%s>: trimming\n", ent->log,
625 compress_type[ent->compress].flag);
626 free_or_keep = do_rotate(ent);
629 printf("--> skipping\n");
632 return (free_or_keep);
637 parse_args(int argc, char **argv)
642 timenow = ptime_init(NULL);
643 ptimeset_time(timenow, time(NULL));
644 strlcpy(daytime, ptimeget_ctime(timenow) + 4, DAYTIME_LEN);
645 ptimeget_ctime_rfc5424(timenow, daytime_rfc5424, DAYTIME_RFC5424_LEN);
647 /* Let's get our hostname */
648 (void)gethostname(hostname, sizeof(hostname));
650 /* Truncate domain */
651 if ((p = strchr(hostname, '.')) != NULL)
654 /* Parse command line options. */
655 while ((ch = getopt(argc, argv, "a:d:f:nrst:vCD:FNPR:S:")) != -1)
659 archdirname = optarg;
677 if (optarg[0] == '\0' ||
678 strcmp(optarg, "DEFAULT") == 0)
679 timefnamefmt = strdup(DEFAULT_TIMEFNAME_FMT);
681 timefnamefmt = strdup(optarg);
687 /* Useful for things like rc.diskless... */
692 * Set some debugging option. The specific option
693 * depends on the value of optarg. These options
694 * may come and go without notice or documentation.
696 if (parse_doption(optarg))
711 requestor = strdup(optarg);
714 path_syslogpid = optarg;
716 case 'm': /* Used by OpenBSD for "monitor mode" */
722 if (force && norotate) {
723 warnx("Only one of -F and -N may be specified.");
729 if (optind == argc) {
730 warnx("At least one filename must be given when -R is specified.");
734 /* Make sure "requestor" value is safe for a syslog message. */
735 for (p = requestor; *p != '\0'; p++) {
736 if (!isprintch(*p) && (*p != '\t'))
743 * Note that the 'daytime' variable is not changed.
744 * That is only used in messages that track when a
745 * logfile is rotated, and if a file *is* rotated,
746 * then it will still rotated at the "real now" time.
749 timenow = dbg_timenow;
750 fprintf(stderr, "Debug: Running as if TimeNow is %s",
751 ptimeget_ctime(dbg_timenow));
757 * These debugging options are mainly meant for developer use, such
758 * as writing regression-tests. They would not be needed by users
759 * during normal operation of newsyslog...
762 parse_doption(const char *doption)
764 const char TN[] = "TN=";
767 if (strncmp(doption, TN, sizeof(TN) - 1) == 0) {
769 * The "TimeNow" debugging option. This might be off
770 * by an hour when crossing a timezone change.
772 dbg_timenow = ptime_init(NULL);
773 res = ptime_relparse(dbg_timenow, PTM_PARSE_ISO8601,
774 time(NULL), doption + sizeof(TN) - 1);
776 warnx("Non-existent time specified on -D %s", doption);
777 return (0); /* failure */
778 } else if (res < 0) {
779 warnx("Malformed time given on -D %s", doption);
780 return (0); /* failure */
782 return (1); /* successfully parsed */
786 if (strcmp(doption, "ats") == 0) {
788 return (1); /* successfully parsed */
791 /* XXX - This check could probably be dropped. */
792 if ((strcmp(doption, "neworder") == 0) || (strcmp(doption, "oldorder")
794 warnx("NOTE: newsyslog always uses 'neworder'.");
795 return (1); /* successfully parsed */
798 warnx("Unknown -D (debug) option: '%s'", doption);
799 return (0); /* failure */
807 "usage: newsyslog [-CFNPnrsv] [-a directory] [-d directory] [-f config_file]\n"
808 " [-S pidfile] [-t timefmt] [[-R tagname] file ...]\n");
813 * Parse a configuration file and return a linked list of all the logs
814 * which should be processed.
816 static struct cflist *
817 get_worklist(char **files)
821 struct cflist *cmdlist, *filelist, *globlist;
822 struct conf_entry *defconf, *dupent, *ent;
823 struct ilist inclist;
824 struct include_entry *inc;
828 STAILQ_INIT(&inclist);
830 filelist = malloc(sizeof(struct cflist));
831 if (filelist == NULL)
832 err(1, "malloc of filelist");
833 STAILQ_INIT(filelist);
834 globlist = malloc(sizeof(struct cflist));
835 if (globlist == NULL)
836 err(1, "malloc of globlist");
837 STAILQ_INIT(globlist);
839 inc = malloc(sizeof(struct include_entry));
841 err(1, "malloc of inc");
843 if (inc->file == NULL)
844 inc->file = _PATH_CONF;
845 STAILQ_INSERT_TAIL(&inclist, inc, inc_nextp);
847 STAILQ_FOREACH(inc, &inclist, inc_nextp) {
848 if (strcmp(inc->file, "-") != 0)
849 f = fopen(inc->file, "r");
852 inc->file = "<stdin>";
855 err(1, "%s", inc->file);
858 printf("Processing %s\n", inc->file);
859 parse_file(f, filelist, globlist, defconf, &inclist);
864 * All config-file information has been read in and turned into
865 * a filelist and a globlist. If there were no specific files
866 * given on the run command, then the only thing left to do is to
867 * call a routine which finds all files matched by the globlist
868 * and adds them to the filelist. Then return the worklist.
870 if (*files == NULL) {
871 expand_globs(filelist, globlist);
872 free_clist(globlist);
880 * If newsyslog was given a specific list of files to process,
881 * it may be that some of those files were not listed in any
882 * config file. Those unlisted files should get the default
883 * rotation action. First, create the default-rotation action
884 * if none was found in a system config file.
886 if (defconf == NULL) {
887 defconf = init_entry(DEFAULT_MARKER, NULL);
888 defconf->numlogs = 3;
889 defconf->trsize = 50;
890 defconf->permissions = S_IRUSR|S_IWUSR;
894 * If newsyslog was run with a list of specific filenames,
895 * then create a new worklist which has only those files in
896 * it, picking up the rotation-rules for those files from
897 * the original filelist.
899 * XXX - Note that this will copy multiple rules for a single
900 * logfile, if multiple entries are an exact match for
901 * that file. That matches the historic behavior, but do
902 * we want to continue to allow it? If so, it should
903 * probably be handled more intelligently.
905 cmdlist = malloc(sizeof(struct cflist));
907 err(1, "malloc of cmdlist");
908 STAILQ_INIT(cmdlist);
910 for (given = files; *given; ++given) {
912 * First try to find exact-matches for this given file.
915 STAILQ_FOREACH(ent, filelist, cf_nextp) {
916 if (strcmp(ent->log, *given) == 0) {
918 dupent = init_entry(*given, ent);
919 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
924 printf("\t+ Matched entry %s\n", *given);
929 * There was no exact-match for this given file, so look
930 * for a "glob" entry which does match.
933 if (verbose > 2 && globlist != NULL)
934 printf("\t+ Checking globs for %s\n", *given);
935 STAILQ_FOREACH(ent, globlist, cf_nextp) {
936 fnres = fnmatch(ent->log, *given, FNM_PATHNAME);
938 printf("\t+ = %d for pattern %s\n", fnres,
942 dupent = init_entry(*given, ent);
943 /* This new entry is not a glob! */
944 dupent->flags &= ~CE_GLOB;
945 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
946 /* Only allow a match to one glob-entry */
952 printf("\t+ Matched %s via %s\n", *given,
958 * This given file was not found in any config file, so
959 * add a worklist item based on the default entry.
962 printf("\t+ No entry matched %s (will use %s)\n",
963 *given, DEFAULT_MARKER);
964 dupent = init_entry(*given, defconf);
965 /* Mark that it was *not* found in a config file */
967 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
971 * Free all the entries in the original work list, the list of
972 * glob entries, and the default entry.
974 free_clist(filelist);
975 free_clist(globlist);
978 /* And finally, return a worklist which matches the given files. */
983 * Expand the list of entries with filename patterns, and add all files
984 * which match those glob-entries onto the worklist.
987 expand_globs(struct cflist *work_p, struct cflist *glob_p)
992 struct conf_entry *dupent, *ent, *globent;
997 * The worklist contains all fully-specified (non-GLOB) names.
999 * Now expand the list of filename-pattern (GLOB) entries into
1000 * a second list, which (by definition) will only match files
1001 * that already exist. Do not add a glob-related entry for any
1002 * file which already exists in the fully-specified list.
1004 STAILQ_FOREACH(globent, glob_p, cf_nextp) {
1005 gres = glob(globent->log, GLOB_NOCHECK, NULL, &pglob);
1007 warn("cannot expand pattern (%d): %s", gres,
1013 printf("\t+ Expanding pattern %s\n", globent->log);
1014 for (i = 0; i < pglob.gl_matchc; i++) {
1015 mfname = pglob.gl_pathv[i];
1017 /* See if this file already has a specific entry. */
1019 STAILQ_FOREACH(ent, work_p, cf_nextp) {
1020 if (strcmp(mfname, ent->log) == 0) {
1028 /* Make sure the named matched is a file. */
1029 gres = lstat(mfname, &st_fm);
1031 /* Error on a file that glob() matched?!? */
1032 warn("Skipping %s - lstat() error", mfname);
1035 if (!S_ISREG(st_fm.st_mode)) {
1036 /* We only rotate files! */
1038 printf("\t+ . skipping %s (!file)\n",
1044 printf("\t+ . add file %s\n", mfname);
1045 dupent = init_entry(mfname, globent);
1046 /* This new entry is not a glob! */
1047 dupent->flags &= ~CE_GLOB;
1049 /* Add to the worklist. */
1050 STAILQ_INSERT_TAIL(work_p, dupent, cf_nextp);
1054 printf("\t+ Done with pattern %s\n", globent->log);
1059 * Parse a configuration file and update a linked list of all the logs to
1063 parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
1064 struct conf_entry *defconf_p, struct ilist *inclist)
1066 char line[BUFSIZ], *parse, *q;
1067 char *cp, *errline, *group;
1068 struct conf_entry *working;
1072 int eol, ptm_opts, res, special;
1076 while (fgets(line, BUFSIZ, cf)) {
1077 if ((line[0] == '\n') || (line[0] == '#') ||
1078 (strlen(line) == 0))
1080 if (errline != NULL)
1082 errline = strdup(line);
1083 for (cp = line + 1; *cp != '\0'; cp++) {
1086 if (*(cp - 1) == '\\') {
1095 q = parse = missing_field(sob(line), errline);
1098 errx(1, "malformed line (missing fields):\n%s",
1103 * Allow people to set debug options via the config file.
1104 * (NOTE: debug options are undocumented, and may disappear
1105 * at any time, etc).
1107 if (strcasecmp(DEBUG_MARKER, q) == 0) {
1108 q = parse = missing_field(sob(parse + 1), errline);
1111 warnx("debug line specifies no option:\n%s",
1118 } else if (strcasecmp(INCLUDE_MARKER, q) == 0) {
1120 printf("Found: %s", errline);
1121 q = parse = missing_field(sob(parse + 1), errline);
1124 warnx("include line missing argument:\n%s",
1132 res = glob(q, GLOB_NOCHECK, NULL, &pglob);
1134 warn("cannot expand pattern (%d): %s",
1140 printf("\t+ Expanding pattern %s\n", q);
1142 for (i = 0; i < pglob.gl_matchc; i++)
1143 add_to_queue(pglob.gl_pathv[i],
1147 add_to_queue(q, inclist);
1152 working = init_entry(q, NULL);
1153 if (strcasecmp(DEFAULT_MARKER, q) == 0) {
1155 if (defconf_p != NULL) {
1156 warnx("Ignoring duplicate entry for %s!", q);
1157 free_entry(working);
1160 defconf_p = working;
1163 q = parse = missing_field(sob(parse + 1), errline);
1166 errx(1, "malformed line (missing fields):\n%s",
1169 if ((group = strchr(q, ':')) != NULL ||
1170 (group = strrchr(q, '.')) != NULL) {
1173 if (!(isnumberstr(q))) {
1174 if ((pwd = getpwnam(q)) == NULL)
1176 "error in config file; unknown user:\n%s",
1178 working->uid = pwd->pw_uid;
1180 working->uid = atoi(q);
1182 working->uid = (uid_t)-1;
1186 if (!(isnumberstr(q))) {
1187 if ((grp = getgrnam(q)) == NULL)
1189 "error in config file; unknown group:\n%s",
1191 working->gid = grp->gr_gid;
1193 working->gid = atoi(q);
1195 working->gid = (gid_t)-1;
1197 q = parse = missing_field(sob(parse + 1), errline);
1200 errx(1, "malformed line (missing fields):\n%s",
1204 working->uid = (uid_t)-1;
1205 working->gid = (gid_t)-1;
1208 if (!sscanf(q, "%o", &working->permissions))
1209 errx(1, "error in config file; bad permissions:\n%s",
1212 q = parse = missing_field(sob(parse + 1), errline);
1215 errx(1, "malformed line (missing fields):\n%s",
1218 if (!sscanf(q, "%d", &working->numlogs) || working->numlogs < 0)
1219 errx(1, "error in config file; bad value for count of logs to save:\n%s",
1222 q = parse = missing_field(sob(parse + 1), errline);
1225 errx(1, "malformed line (missing fields):\n%s",
1229 working->trsize = atoi(q);
1230 else if (strcmp(q, "*") == 0)
1231 working->trsize = -1;
1233 warnx("Invalid value of '%s' for 'size' in line:\n%s",
1235 working->trsize = -1;
1239 working->compress = COMPRESS_NONE;
1240 q = parse = missing_field(sob(parse + 1), errline);
1248 ul = strtoul(q, &ep, 10);
1251 else if (*ep == '*')
1252 working->hours = -1;
1253 else if (ul > INT_MAX)
1254 errx(1, "interval is too large:\n%s", errline);
1256 working->hours = ul;
1258 if (*ep == '\0' || strcmp(ep, "*") == 0)
1260 if (*ep != '@' && *ep != '$')
1261 errx(1, "malformed interval/at:\n%s", errline);
1263 working->flags |= CE_TRIMAT;
1264 working->trim_at = ptime_init(NULL);
1265 ptm_opts = PTM_PARSE_ISO8601;
1267 ptm_opts = PTM_PARSE_DWM;
1268 ptm_opts |= PTM_PARSE_MATCHDOM;
1269 res = ptime_relparse(working->trim_at, ptm_opts,
1270 ptimeget_secs(timenow), ep + 1);
1272 errx(1, "nonexistent time for 'at' value:\n%s",
1275 errx(1, "malformed 'at' value:\n%s", errline);
1282 q = parse = sob(parse + 1); /* Optional field */
1289 for (; q && *q && !isspacech(*q); q++) {
1290 switch (tolowerch(*q)) {
1292 working->flags |= CE_BINARY;
1295 working->flags |= CE_CREATE;
1298 working->flags |= CE_NODUMP;
1301 working->flags |= CE_GLOB;
1304 working->compress = COMPRESS_BZIP2;
1307 working->flags |= CE_NOSIGNAL;
1310 working->flags |= CE_PID2CMD;
1313 working->flags |= CE_RFC5424;
1316 working->flags |= CE_SIGNALGROUP;
1319 /* Deprecated flag - keep for compatibility purposes */
1322 working->compress = COMPRESS_XZ;
1325 working->compress = COMPRESS_ZSTD;
1328 working->compress = COMPRESS_GZIP;
1332 case 'f': /* Used by OpenBSD for "CE_FOLLOW" */
1333 case 'm': /* Used by OpenBSD for "CE_MONITOR" */
1334 case 'p': /* Used by NetBSD for "CE_PLAIN0" */
1336 errx(1, "illegal flag in config file -- %c",
1344 q = parse = sob(parse + 1); /* Optional field */
1351 working->pid_cmd_file = NULL;
1354 working->pid_cmd_file = strdup(q);
1355 else if (isalnum(*q))
1359 "illegal pid file or signal in config file:\n%s",
1366 q = parse = sob(parse + 1); /* Optional field */
1367 *(parse = son(parse)) = '\0';
1370 working->sig = SIGHUP;
1373 working->sig = parse_signal(q);
1374 if (working->sig < 1 || working->sig >= sys_nsig) {
1376 "illegal signal in config file:\n%s",
1382 * Finish figuring out what pid-file to use (if any) in
1383 * later processing if this logfile needs to be rotated.
1385 if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) {
1387 * This config-entry specified 'n' for nosignal,
1388 * see if it also specified an explicit pid_cmd_file.
1389 * This would be a pretty pointless combination.
1391 if (working->pid_cmd_file != NULL) {
1392 warnx("Ignoring '%s' because flag 'n' was specified in line:\n%s",
1393 working->pid_cmd_file, errline);
1394 free(working->pid_cmd_file);
1395 working->pid_cmd_file = NULL;
1397 } else if (working->pid_cmd_file == NULL) {
1399 * This entry did not specify the 'n' flag, which
1400 * means it should signal syslogd unless it had
1401 * specified some other pid-file (and obviously the
1402 * syslog pid-file will not be for a process-group).
1403 * Also, we should only try to notify syslog if we
1406 if (working->flags & CE_SIGNALGROUP) {
1407 warnx("Ignoring flag 'U' in line:\n%s",
1409 working->flags &= ~CE_SIGNALGROUP;
1412 working->pid_cmd_file = strdup(path_syslogpid);
1416 * Add this entry to the appropriate list of entries, unless
1417 * it was some kind of special entry (eg: <default>).
1420 ; /* Do not add to any list */
1421 } else if (working->flags & CE_GLOB) {
1422 STAILQ_INSERT_TAIL(glob_p, working, cf_nextp);
1424 STAILQ_INSERT_TAIL(work_p, working, cf_nextp);
1427 if (errline != NULL)
1432 missing_field(char *p, char *errline)
1436 errx(1, "missing field in config file:\n%s", errline);
1441 * In our sort we return it in the reverse of what qsort normally
1442 * would do, as we want the newest files first. If we have two
1443 * entries with the same time we don't really care about order.
1445 * Support function for qsort() in delete_oldest_timelog().
1448 oldlog_entry_compare(const void *a, const void *b)
1450 const struct oldlog_entry *ola = a, *olb = b;
1452 if (ola->t > olb->t)
1454 else if (ola->t < olb->t)
1461 * Check whether the file corresponding to dp is an archive of the logfile
1462 * logfname, based on the timefnamefmt format string. Return true and fill out
1463 * tm if this is the case; otherwise return false.
1466 validate_old_timelog(int fd, const struct dirent *dp, const char *logfname,
1470 size_t logfname_len;
1474 logfname_len = strlen(logfname);
1476 if (dp->d_type != DT_REG) {
1478 * Some filesystems (e.g. NFS) don't fill out the d_type field
1479 * and leave it set to DT_UNKNOWN; in this case we must obtain
1480 * the file type ourselves.
1482 if (dp->d_type != DT_UNKNOWN ||
1483 fstatat(fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) != 0 ||
1484 !S_ISREG(sb.st_mode))
1487 /* Ignore everything but files with our logfile prefix. */
1488 if (strncmp(dp->d_name, logfname, logfname_len) != 0)
1490 /* Ignore the actual non-rotated logfile. */
1491 if (dp->d_namlen == logfname_len)
1495 * Make sure we created have found a logfile, so the
1496 * postfix is valid, IE format is: '.<time>(.[bgx]z)?'.
1498 if (dp->d_name[logfname_len] != '.') {
1500 printf("Ignoring %s which has unexpected "
1501 "extension '%s'\n", dp->d_name,
1502 &dp->d_name[logfname_len]);
1505 memset(tm, 0, sizeof(*tm));
1506 if ((s = strptime(&dp->d_name[logfname_len + 1],
1507 timefnamefmt, tm)) == NULL) {
1509 * We could special case "old" sequentially named logfiles here,
1510 * but we do not as that would require special handling to
1511 * decide which one was the oldest compared to "new" time based
1515 printf("Ignoring %s which does not "
1516 "match time format\n", dp->d_name);
1520 for (c = 0; c < COMPRESS_TYPES; c++)
1521 if (strcmp(s, compress_type[c].suffix) == 0)
1526 printf("Ignoring %s which has unexpected extension '%s'\n",
1533 * Delete the oldest logfiles, when using time based filenames.
1536 delete_oldest_timelog(const struct conf_entry *ent, const char *archive_dir)
1538 char *basebuf, *dirbuf, errbuf[80];
1539 const char *base, *dir;
1540 int dir_fd, i, logcnt, max_logcnt;
1541 struct oldlog_entry *oldlogs;
1546 oldlogs = malloc(MAX_OLDLOGS * sizeof(struct oldlog_entry));
1547 max_logcnt = MAX_OLDLOGS;
1550 if (archive_dir != NULL && archive_dir[0] != '\0') {
1554 if ((dirbuf = strdup(ent->log)) == NULL)
1556 dir = dirname(dirbuf);
1559 if ((basebuf = strdup(ent->log)) == NULL)
1561 base = basename(basebuf);
1562 if (strcmp(base, "/") == 0)
1563 errx(1, "Invalid log filename - became '/'");
1566 printf("Searching for old logs in %s\n", dir);
1568 /* First we create a 'list' of all archived logfiles */
1569 if ((dirp = opendir(dir)) == NULL)
1570 err(1, "Cannot open log directory '%s'", dir);
1571 dir_fd = dirfd(dirp);
1572 while ((dp = readdir(dirp)) != NULL) {
1573 if (validate_old_timelog(dir_fd, dp, base, &tm) == 0)
1577 * We should now have old an old rotated logfile, so
1578 * add it to the 'list'.
1580 if ((oldlogs[logcnt].t = timegm(&tm)) == -1)
1581 err(1, "Could not convert time string to time value");
1582 if ((oldlogs[logcnt].fname = strdup(dp->d_name)) == NULL)
1587 * It is very unlikely we ever run out of space in the
1588 * logfile array from the default size, but lets
1589 * handle it anyway...
1591 if (logcnt >= max_logcnt) {
1593 /* Detect integer overflow */
1594 if (max_logcnt < logcnt)
1595 errx(1, "Too many old logfiles found");
1596 oldlogs = realloc(oldlogs,
1597 max_logcnt * sizeof(struct oldlog_entry));
1598 if (oldlogs == NULL)
1599 err(1, "realloc()");
1603 /* Second, if needed we delete oldest archived logfiles */
1604 if (logcnt > 0 && logcnt >= ent->numlogs && ent->numlogs > 1) {
1605 oldlogs = realloc(oldlogs, logcnt *
1606 sizeof(struct oldlog_entry));
1607 if (oldlogs == NULL)
1608 err(1, "realloc()");
1611 * We now sort the logs in the order of newest to
1612 * oldest. That way we can simply skip over the
1613 * number of records we want to keep.
1615 qsort(oldlogs, logcnt, sizeof(struct oldlog_entry),
1616 oldlog_entry_compare);
1617 for (i = ent->numlogs - 1; i < logcnt; i++) {
1619 printf("\trm -f %s/%s\n", dir,
1621 else if (unlinkat(dir_fd, oldlogs[i].fname, 0) != 0) {
1622 snprintf(errbuf, sizeof(errbuf),
1623 "Could not delete old logfile '%s'",
1628 } else if (verbose > 1)
1629 printf("No old logs to delete for logfile %s\n", ent->log);
1631 /* Third, cleanup */
1633 for (i = 0; i < logcnt; i++) {
1634 assert(oldlogs[i].fname != NULL);
1635 free(oldlogs[i].fname);
1643 * Generate a log filename, when using classic filenames.
1646 gen_classiclog_fname(char *fname, size_t fname_sz, const char *archive_dir,
1647 const char *namepart, int numlogs_c)
1650 if (archive_dir[0] != '\0')
1651 (void) snprintf(fname, fname_sz, "%s/%s.%d", archive_dir,
1652 namepart, numlogs_c);
1654 (void) snprintf(fname, fname_sz, "%s.%d", namepart, numlogs_c);
1658 * Delete a rotated logfile, when using classic filenames.
1661 delete_classiclog(const char *archive_dir, const char *namepart, int numlog_c)
1663 char file1[MAXPATHLEN], zfile1[MAXPATHLEN];
1666 gen_classiclog_fname(file1, sizeof(file1), archive_dir, namepart,
1669 for (c = 0; c < COMPRESS_TYPES; c++) {
1670 (void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1671 compress_type[c].suffix);
1673 printf("\trm -f %s\n", zfile1);
1675 (void) unlink(zfile1);
1680 * Only add to the queue if the file hasn't already been added. This is
1681 * done to prevent circular include loops.
1684 add_to_queue(const char *fname, struct ilist *inclist)
1686 struct include_entry *inc;
1688 STAILQ_FOREACH(inc, inclist, inc_nextp) {
1689 if (strcmp(fname, inc->file) == 0) {
1690 warnx("duplicate include detected: %s", fname);
1695 inc = malloc(sizeof(struct include_entry));
1697 err(1, "malloc of inc");
1698 inc->file = strdup(fname);
1701 printf("\t+ Adding %s to the processing queue.\n", fname);
1703 STAILQ_INSERT_TAIL(inclist, inc, inc_nextp);
1707 * Search for logfile and return its compression suffix (if supported)
1708 * The suffix detection is first-match in the order of compress_types
1710 * Note: if logfile without suffix exists (uncompressed, COMPRESS_NONE)
1711 * a zero-length string is returned
1714 get_logfile_suffix(const char *logfile)
1717 char zfile[MAXPATHLEN];
1720 for (c = 0; c < COMPRESS_TYPES; c++) {
1721 (void) strlcpy(zfile, logfile, MAXPATHLEN);
1722 (void) strlcat(zfile, compress_type[c].suffix, MAXPATHLEN);
1723 if (lstat(zfile, &st) == 0)
1724 return (compress_type[c].suffix);
1730 do_rotate(const struct conf_entry *ent)
1732 char dirpart[MAXPATHLEN], namepart[MAXPATHLEN];
1733 char file1[MAXPATHLEN], file2[MAXPATHLEN];
1734 char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN];
1735 const char *logfile_suffix;
1736 char datetimestr[30];
1737 int flags, numlogs_c;
1738 fk_entry free_or_keep;
1739 struct sigwork_entry *swork;
1745 free_or_keep = FREE_ENT;
1750 /* build complete name of archive directory into dirpart */
1751 if (*archdirname == '/') { /* absolute */
1752 strlcpy(dirpart, archdirname, sizeof(dirpart));
1753 } else { /* relative */
1754 /* get directory part of logfile */
1755 strlcpy(dirpart, ent->log, sizeof(dirpart));
1756 if ((p = strrchr(dirpart, '/')) == NULL)
1760 strlcat(dirpart, archdirname, sizeof(dirpart));
1763 /* check if archive directory exists, if not, create it */
1764 if (lstat(dirpart, &st))
1765 createdir(ent, dirpart);
1767 /* get filename part of logfile */
1768 if ((p = strrchr(ent->log, '/')) == NULL)
1769 strlcpy(namepart, ent->log, sizeof(namepart));
1771 strlcpy(namepart, p + 1, sizeof(namepart));
1774 * Tell utility functions we are not using an archive
1778 strlcpy(namepart, ent->log, sizeof(namepart));
1781 /* Delete old logs */
1782 if (timefnamefmt != NULL)
1783 delete_oldest_timelog(ent, dirpart);
1786 * Handle cleaning up after legacy newsyslog where we
1787 * kept ent->numlogs + 1 files. This code can go away
1788 * at some point in the future.
1790 delete_classiclog(dirpart, namepart, ent->numlogs);
1792 if (ent->numlogs > 0)
1793 delete_classiclog(dirpart, namepart, ent->numlogs - 1);
1797 if (timefnamefmt != NULL) {
1798 /* If time functions fails we can't really do any sensible */
1799 if (time(&now) == (time_t)-1 ||
1800 localtime_r(&now, &tm) == NULL)
1801 bzero(&tm, sizeof(tm));
1803 strftime(datetimestr, sizeof(datetimestr), timefnamefmt, &tm);
1805 (void) snprintf(file1, sizeof(file1), "%s/%s.%s",
1806 dirpart, namepart, datetimestr);
1808 (void) snprintf(file1, sizeof(file1), "%s.%s",
1809 ent->log, datetimestr);
1811 /* Don't run the code to move down logs */
1814 gen_classiclog_fname(file1, sizeof(file1), dirpart, namepart,
1816 numlogs_c = ent->numlogs - 2; /* copy for countdown */
1819 /* Move down log files */
1820 for (; numlogs_c >= 0; numlogs_c--) {
1821 (void) strlcpy(file2, file1, sizeof(file2));
1823 gen_classiclog_fname(file1, sizeof(file1), dirpart, namepart,
1826 logfile_suffix = get_logfile_suffix(file1);
1827 if (logfile_suffix == NULL)
1829 (void) strlcpy(zfile1, file1, MAXPATHLEN);
1830 (void) strlcpy(zfile2, file2, MAXPATHLEN);
1831 (void) strlcat(zfile1, logfile_suffix, MAXPATHLEN);
1832 (void) strlcat(zfile2, logfile_suffix, MAXPATHLEN);
1835 printf("\tmv %s %s\n", zfile1, zfile2);
1837 /* XXX - Ought to be checking for failure! */
1838 (void)rename(zfile1, zfile2);
1840 change_attrs(zfile2, ent);
1843 if (ent->numlogs > 0) {
1846 * Note that savelog() may succeed with using link()
1847 * for the archtodir case, but there is no good way
1848 * of knowing if it will when doing "noaction", so
1849 * here we claim that it will have to do a copy...
1852 printf("\tcp %s %s\n", ent->log, file1);
1854 printf("\tln %s %s\n", ent->log, file1);
1855 printf("\ttouch %s\t\t"
1856 "# Update mtime for 'when'-interval processing\n",
1859 if (!(flags & CE_BINARY)) {
1860 /* Report the trimming to the old log */
1861 log_trim(ent->log, ent);
1863 savelog(ent->log, file1);
1865 * Interval-based rotations are done using the mtime of
1866 * the most recently archived log, so make sure it gets
1867 * updated during a rotation.
1869 utimes(file1, NULL);
1871 change_attrs(file1, ent);
1874 /* Create the new log file and move it into place */
1876 printf("Start new log...\n");
1880 * Save all signalling and file-compression to be done after log
1881 * files from all entries have been rotated. This way any one
1882 * process will not be sent the same signal multiple times when
1883 * multiple log files had to be rotated.
1886 if (ent->pid_cmd_file != NULL)
1887 swork = save_sigwork(ent);
1888 if (ent->numlogs > 0 && ent->compress > COMPRESS_NONE) {
1890 * The zipwork_entry will include a pointer to this
1891 * conf_entry, so the conf_entry should not be freed.
1893 free_or_keep = KEEP_ENT;
1894 save_zipwork(ent, swork, ent->fsize, file1);
1897 return (free_or_keep);
1901 do_sigwork(struct sigwork_entry *swork)
1903 struct sigwork_entry *nextsig;
1907 if (swork->sw_runcmd == 0 && (!(swork->sw_pidok) || swork->sw_pid == 0))
1908 return; /* no work to do... */
1911 * If nosignal (-s) was specified, then do not signal any process.
1912 * Note that a nosignal request triggers a warning message if the
1913 * rotated logfile needs to be compressed, *unless* -R was also
1914 * specified. We assume that an `-sR' request came from a process
1915 * which writes to the logfile, and as such, we assume that process
1916 * has already made sure the logfile is not presently in use. This
1917 * just sets swork->sw_pidok to a special value, and do_zipwork
1918 * will print any necessary warning(s).
1922 swork->sw_pidok = -1;
1927 * Compute the pause between consecutive signals. Use a longer
1928 * sleep time if we will be sending two signals to the same
1929 * daemon or process-group.
1932 nextsig = SLIST_NEXT(swork, sw_nextp);
1933 if (nextsig != NULL) {
1934 if (swork->sw_pid == nextsig->sw_pid)
1941 if (swork->sw_runcmd)
1942 printf("\tsh -c '%s %d'\n", swork->sw_fname,
1945 printf("\tkill -%d %d \t\t# %s\n", swork->sw_signum,
1946 (int)swork->sw_pid, swork->sw_fname);
1948 printf("\tsleep %d\n", secs);
1953 if (swork->sw_runcmd) {
1954 asprintf(&tmp, "%s %d", swork->sw_fname, swork->sw_signum);
1956 warn("can't allocate memory to run %s",
1961 printf("Run command: %s\n", tmp);
1964 warnx("%s: returned non-zero exit code: %d",
1971 kres = kill(swork->sw_pid, swork->sw_signum);
1974 * Assume that "no such process" (ESRCH) is something
1975 * to warn about, but is not an error. Presumably the
1976 * process which writes to the rotated log file(s) is
1977 * gone, in which case we should have no problem with
1978 * compressing the rotated log file(s).
1981 swork->sw_pidok = 0;
1982 warn("can't notify %s, pid %d = %s", swork->sw_pidtype,
1983 (int)swork->sw_pid, swork->sw_fname);
1986 printf("Notified %s pid %d = %s\n", swork->sw_pidtype,
1987 (int)swork->sw_pid, swork->sw_fname);
1990 printf("Pause %d second(s) between signals\n",
1998 do_zipwork(struct zipwork_entry *zwork)
2000 const char *pgm_name, *pgm_path;
2001 int errsav, fcount, zstatus;
2003 char zresult[MAXPATHLEN];
2006 assert(zwork != NULL);
2008 strlcpy(zresult, zwork->zw_fname, sizeof(zresult));
2009 if (zwork->zw_conf != NULL &&
2010 zwork->zw_conf->compress > COMPRESS_NONE)
2011 for (c = 1; c < COMPRESS_TYPES; c++) {
2012 if (zwork->zw_conf->compress == c) {
2013 pgm_path = compress_type[c].path;
2014 (void) strlcat(zresult,
2015 compress_type[c].suffix, sizeof(zresult));
2019 if (pgm_path == NULL) {
2020 warnx("invalid entry for %s in do_zipwork", zwork->zw_fname);
2023 pgm_name = strrchr(pgm_path, '/');
2024 if (pgm_name == NULL)
2025 pgm_name = pgm_path;
2029 if (zwork->zw_swork != NULL && zwork->zw_swork->sw_runcmd == 0 &&
2030 zwork->zw_swork->sw_pidok <= 0) {
2032 "log %s not compressed because daemon(s) not notified",
2034 change_attrs(zwork->zw_fname, zwork->zw_conf);
2039 printf("\t%s %s\n", pgm_name, zwork->zw_fname);
2040 change_attrs(zresult, zwork->zw_conf);
2046 while (pidzip < 0) {
2048 * The fork failed. If the failure was due to a temporary
2049 * problem, then wait a short time and try it again.
2052 warn("fork() for `%s %s'", pgm_name, zwork->zw_fname);
2053 if (errsav != EAGAIN || fcount > 5)
2054 errx(1, "Exiting...");
2060 /* The child process executes the compression command */
2061 execl(pgm_path, pgm_path, "-f", zwork->zw_fname, (char *)0);
2062 err(1, "execl(`%s -f %s')", pgm_path, zwork->zw_fname);
2065 wpid = waitpid(pidzip, &zstatus, 0);
2067 /* XXX - should this be a fatal error? */
2068 warn("%s: waitpid(%d)", pgm_path, pidzip);
2071 if (!WIFEXITED(zstatus)) {
2072 warnx("`%s -f %s' did not terminate normally", pgm_name,
2076 if (WEXITSTATUS(zstatus)) {
2077 warnx("`%s -f %s' terminated with a non-zero status (%d)",
2078 pgm_name, zwork->zw_fname, WEXITSTATUS(zstatus));
2082 /* Compression was successful, set file attributes on the result. */
2083 change_attrs(zresult, zwork->zw_conf);
2087 * Save information on any process we need to signal. Any single
2088 * process may need to be sent different signal-values for different
2089 * log files, but usually a single signal-value will cause the process
2090 * to close and re-open all of its log files.
2092 static struct sigwork_entry *
2093 save_sigwork(const struct conf_entry *ent)
2095 struct sigwork_entry *sprev, *stmp;
2101 SLIST_FOREACH(stmp, &swhead, sw_nextp) {
2102 ndiff = strcmp(ent->pid_cmd_file, stmp->sw_fname);
2106 if (ent->sig == stmp->sw_signum)
2108 if (ent->sig > stmp->sw_signum) {
2115 if (stmp != NULL && ndiff == 0)
2118 tmpsiz = sizeof(struct sigwork_entry) + strlen(ent->pid_cmd_file) + 1;
2119 stmp = malloc(tmpsiz);
2121 stmp->sw_runcmd = 0;
2122 /* If this is a command to run we just set the flag and run command */
2123 if (ent->flags & CE_PID2CMD) {
2126 stmp->sw_runcmd = 1;
2128 set_swpid(stmp, ent);
2130 stmp->sw_signum = ent->sig;
2131 strcpy(stmp->sw_fname, ent->pid_cmd_file);
2133 SLIST_INSERT_HEAD(&swhead, stmp, sw_nextp);
2135 SLIST_INSERT_AFTER(sprev, stmp, sw_nextp);
2140 * Save information on any file we need to compress. We may see the same
2141 * file multiple times, so check the full list to avoid duplicates. The
2142 * list itself is sorted smallest-to-largest, because that's the order we
2143 * want to compress the files. If the partition is very low on disk space,
2144 * then the smallest files are the most likely to compress, and compressing
2145 * them first will free up more space for the larger files.
2147 static struct zipwork_entry *
2148 save_zipwork(const struct conf_entry *ent, const struct sigwork_entry *swork,
2149 int zsize, const char *zipfname)
2151 struct zipwork_entry *zprev, *ztmp;
2155 /* Compute the size if the caller did not know it. */
2157 zsize = sizefile(zipfname);
2161 SLIST_FOREACH(ztmp, &zwhead, zw_nextp) {
2162 ndiff = strcmp(zipfname, ztmp->zw_fname);
2165 if (zsize > ztmp->zw_fsize)
2168 if (ztmp != NULL && ndiff == 0)
2171 tmpsiz = sizeof(struct zipwork_entry) + strlen(zipfname) + 1;
2172 ztmp = malloc(tmpsiz);
2173 ztmp->zw_conf = ent;
2174 ztmp->zw_swork = swork;
2175 ztmp->zw_fsize = zsize;
2176 strcpy(ztmp->zw_fname, zipfname);
2178 SLIST_INSERT_HEAD(&zwhead, ztmp, zw_nextp);
2180 SLIST_INSERT_AFTER(zprev, ztmp, zw_nextp);
2184 /* Send a signal to the pid specified by pidfile */
2186 set_swpid(struct sigwork_entry *swork, const struct conf_entry *ent)
2189 long minok, maxok, rval;
2190 char *endp, *linep, line[BUFSIZ];
2194 swork->sw_pidok = 0;
2196 swork->sw_pidtype = "daemon";
2197 if (ent->flags & CE_SIGNALGROUP) {
2199 * If we are expected to signal a process-group when
2200 * rotating this logfile, then the value read in should
2201 * be the negative of a valid process ID.
2205 swork->sw_pidtype = "process-group";
2208 f = fopen(ent->pid_cmd_file, "r");
2210 if (errno == ENOENT && enforcepid == 0) {
2212 * Warn if the PID file doesn't exist, but do
2213 * not consider it an error. Most likely it
2214 * means the process has been terminated,
2215 * so it should be safe to rotate any log
2216 * files that the process would have been using.
2218 swork->sw_pidok = 1;
2219 warnx("pid file doesn't exist: %s", ent->pid_cmd_file);
2221 warn("can't open pid file: %s", ent->pid_cmd_file);
2225 if (fgets(line, BUFSIZ, f) == NULL) {
2227 * Warn if the PID file is empty, but do not consider
2228 * it an error. Most likely it means the process has
2229 * has terminated, so it should be safe to rotate any
2230 * log files that the process would have been using.
2232 if (feof(f) && enforcepid == 0) {
2233 swork->sw_pidok = 1;
2234 warnx("pid/cmd file is empty: %s", ent->pid_cmd_file);
2236 warn("can't read from pid file: %s", ent->pid_cmd_file);
2244 while (*linep == ' ')
2246 rval = strtol(linep, &endp, 10);
2247 if (*endp != '\0' && !isspacech(*endp)) {
2248 warnx("pid file does not start with a valid number: %s",
2250 } else if (rval < minok || rval > maxok) {
2251 warnx("bad value '%ld' for process number in %s",
2252 rval, ent->pid_cmd_file);
2254 warnx("\t(expecting value between %ld and %ld)",
2257 swork->sw_pidok = 1;
2258 swork->sw_pid = rval;
2264 /* Log the fact that the logs were turned over */
2266 log_trim(const char *logname, const struct conf_entry *log_ent)
2271 if ((f = fopen(logname, "a")) == NULL)
2274 if (log_ent->def_cfg)
2275 xtra = " using <default> rule";
2276 if (log_ent->flags & CE_RFC5424) {
2277 if (log_ent->firstcreate) {
2278 fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s\n",
2279 LOG_MAKEPRI(LOG_USER, LOG_INFO),
2280 daytime_rfc5424, hostname, getpid(),
2281 "logfile first created", xtra);
2282 } else if (log_ent->r_reason != NULL) {
2283 fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s%s\n",
2284 LOG_MAKEPRI(LOG_USER, LOG_INFO),
2285 daytime_rfc5424, hostname, getpid(),
2286 "logfile turned over", log_ent->r_reason, xtra);
2288 fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s\n",
2289 LOG_MAKEPRI(LOG_USER, LOG_INFO),
2290 daytime_rfc5424, hostname, getpid(),
2291 "logfile turned over", xtra);
2294 if (log_ent->firstcreate)
2295 fprintf(f, "%s %s newsyslog[%d]: logfile first created%s\n",
2296 daytime, hostname, getpid(), xtra);
2297 else if (log_ent->r_reason != NULL)
2298 fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s%s\n",
2299 daytime, hostname, getpid(), log_ent->r_reason, xtra);
2301 fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s\n",
2302 daytime, hostname, getpid(), xtra);
2304 if (fclose(f) == EOF)
2305 err(1, "log_trim: fclose");
2309 /* Return size in kilobytes of a file */
2311 sizefile(const char *file)
2315 if (stat(file, &sb) < 0)
2317 return (kbytes(sb.st_size));
2321 * Return the mtime of the most recent archive of the logfile, using timestamp
2325 mtime_old_timelog(const char *file)
2333 char *logfname, *logfnamebuf, *dir, *dirbuf;
2337 if ((dirbuf = strdup(file)) == NULL) {
2338 warn("strdup() of '%s'", file);
2341 dir = dirname(dirbuf);
2342 if ((logfnamebuf = strdup(file)) == NULL) {
2343 warn("strdup() of '%s'", file);
2347 logfname = basename(logfnamebuf);
2348 if (logfname[0] == '/') {
2349 warnx("Invalid log filename '%s'", logfname);
2353 if ((dirp = opendir(dir)) == NULL) {
2354 warn("Cannot open log directory '%s'", dir);
2357 dir_fd = dirfd(dirp);
2358 /* Open the archive dir and find the most recent archive of logfname. */
2359 while ((dp = readdir(dirp)) != NULL) {
2360 if (validate_old_timelog(dir_fd, dp, logfname, &tm) == 0)
2363 if (fstatat(dir_fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
2364 warn("Cannot stat '%s'", file);
2367 if (t < sb.st_mtime)
2378 /* Return the age in hours of the most recent archive of the logfile. */
2380 age_old_log(const char *file)
2383 const char *logfile_suffix;
2384 char tmp[MAXPATHLEN + sizeof(".0") + COMPRESS_SUFFIX_MAXLEN + 1];
2390 /* build name of archive directory into tmp */
2391 if (*archdirname == '/') { /* absolute */
2392 strlcpy(tmp, archdirname, sizeof(tmp));
2393 } else { /* relative */
2394 /* get directory part of logfile */
2395 strlcpy(tmp, file, sizeof(tmp));
2396 if ((p = strrchr(tmp, '/')) == NULL)
2400 strlcat(tmp, archdirname, sizeof(tmp));
2403 strlcat(tmp, "/", sizeof(tmp));
2405 /* get filename part of logfile */
2406 if ((p = strrchr(file, '/')) == NULL)
2407 strlcat(tmp, file, sizeof(tmp));
2409 strlcat(tmp, p + 1, sizeof(tmp));
2411 (void) strlcpy(tmp, file, sizeof(tmp));
2414 if (timefnamefmt != NULL) {
2415 mtime = mtime_old_timelog(tmp);
2419 strlcat(tmp, ".0", sizeof(tmp));
2420 logfile_suffix = get_logfile_suffix(tmp);
2421 if (logfile_suffix == NULL)
2423 (void) strlcat(tmp, logfile_suffix, sizeof(tmp));
2424 if (stat(tmp, &sb) < 0)
2426 mtime = sb.st_mtime;
2429 return ((int)(ptimeget_secs(timenow) - mtime + 1800) / 3600);
2432 /* Skip Over Blanks */
2436 while (p && *p && isspace(*p))
2441 /* Skip Over Non-Blanks */
2445 while (p && *p && !isspace(*p))
2450 /* Check if string is actually a number */
2452 isnumberstr(const char *string)
2455 if (!isdigitch(*string++))
2461 /* Check if string contains a glob */
2463 isglobstr(const char *string)
2467 while ((chr = *string++)) {
2468 if (chr == '*' || chr == '?' || chr == '[')
2475 * Save the active log file under a new name. A link to the new name
2476 * is the quick-and-easy way to do this. If that fails (which it will
2477 * if the destination is on another partition), then make a copy of
2478 * the file to the new location.
2481 savelog(char *from, char *to)
2486 res = link(from, to);
2490 if ((src = fopen(from, "r")) == NULL)
2491 err(1, "can't fopen %s for reading", from);
2492 if ((dst = fopen(to, "w")) == NULL)
2493 err(1, "can't fopen %s for writing", to);
2495 while ((c = getc(src)) != EOF) {
2496 if ((putc(c, dst)) == EOF)
2497 err(1, "error writing to %s", to);
2501 err(1, "error reading from %s", from);
2502 if ((fclose(src)) != 0)
2503 err(1, "can't fclose %s", to);
2504 if ((fclose(dst)) != 0)
2505 err(1, "can't fclose %s", from);
2508 /* create one or more directory components of a path */
2510 createdir(const struct conf_entry *ent, char *dirpart)
2514 char mkdirpath[MAXPATHLEN];
2522 if (*s != '/' && *s != '\0')
2525 res = lstat(mkdirpath, &st);
2528 printf("\tmkdir %s\n", mkdirpath);
2530 res = mkdir(mkdirpath, 0755);
2532 err(1, "Error on mkdir(\"%s\") for -a",
2540 if (ent->firstcreate)
2541 printf("Created directory '%s' for new %s\n",
2544 printf("Created directory '%s' for -a\n", dirpart);
2549 * Create a new log file, destroying any currently-existing version
2550 * of the log file in the process. If the caller wants a backup copy
2551 * of the file to exist, they should call 'link(logfile,logbackup)'
2552 * before calling this routine.
2555 createlog(const struct conf_entry *ent)
2559 char *realfile, *slash, tempfile[MAXPATHLEN];
2562 realfile = ent->log;
2565 * If this log file is being created for the first time (-C option),
2566 * then it may also be true that the parent directory does not exist
2567 * yet. Check, and create that directory if it is missing.
2569 if (ent->firstcreate) {
2570 strlcpy(tempfile, realfile, sizeof(tempfile));
2571 slash = strrchr(tempfile, '/');
2572 if (slash != NULL) {
2574 failed = stat(tempfile, &st);
2575 if (failed && errno != ENOENT)
2576 err(1, "Error on stat(%s)", tempfile);
2578 createdir(ent, tempfile);
2579 else if (!S_ISDIR(st.st_mode))
2580 errx(1, "%s exists but is not a directory",
2586 * First create an unused filename, so it can be chown'ed and
2587 * chmod'ed before it is moved into the real location. mkstemp
2588 * will create the file mode=600 & owned by us. Note that all
2589 * temp files will have a suffix of '.z<something>'.
2591 strlcpy(tempfile, realfile, sizeof(tempfile));
2592 strlcat(tempfile, ".zXXXXXX", sizeof(tempfile));
2594 printf("\tmktemp %s\n", tempfile);
2596 fd = mkstemp(tempfile);
2598 err(1, "can't mkstemp logfile %s", tempfile);
2601 * Add status message to what will become the new log file.
2603 if (!(ent->flags & CE_BINARY)) {
2604 if (log_trim(tempfile, ent))
2605 err(1, "can't add status message to log");
2609 /* Change the owner/group, if we are supposed to */
2610 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2612 printf("\tchown %u:%u %s\n", ent->uid, ent->gid,
2615 failed = fchown(fd, ent->uid, ent->gid);
2617 err(1, "can't fchown temp file %s", tempfile);
2621 /* Turn on NODUMP if it was requested in the config-file. */
2622 if (ent->flags & CE_NODUMP) {
2624 printf("\tchflags nodump %s\n", tempfile);
2626 failed = fchflags(fd, UF_NODUMP);
2628 warn("log_trim: fchflags(NODUMP)");
2634 * Note that if the real logfile still exists, and if the call
2635 * to rename() fails, then "neither the old file nor the new
2636 * file shall be changed or created" (to quote the standard).
2637 * If the call succeeds, then the file will be replaced without
2638 * any window where some other process might find that the file
2640 * XXX - ? It may be that for some error conditions, we could
2641 * retry by first removing the realfile and then renaming.
2644 printf("\tchmod %o %s\n", ent->permissions, tempfile);
2645 printf("\tmv %s %s\n", tempfile, realfile);
2647 failed = fchmod(fd, ent->permissions);
2649 err(1, "can't fchmod temp file '%s'", tempfile);
2650 failed = rename(tempfile, realfile);
2652 err(1, "can't mv %s to %s", tempfile, realfile);
2660 * Change the attributes of a given filename to what was specified in
2661 * the newsyslog.conf entry. This routine is only called for files
2662 * that newsyslog expects that it has created, and thus it is a fatal
2663 * error if this routine finds that the file does not exist.
2666 change_attrs(const char *fname, const struct conf_entry *ent)
2671 printf("\tchmod %o %s\n", ent->permissions, fname);
2673 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
2674 printf("\tchown %u:%u %s\n",
2675 ent->uid, ent->gid, fname);
2677 if (ent->flags & CE_NODUMP)
2678 printf("\tchflags nodump %s\n", fname);
2682 failed = chmod(fname, ent->permissions);
2685 err(1, "chmod(%s) in change_attrs", fname);
2686 warn("change_attrs couldn't chmod(%s)", fname);
2689 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2690 failed = chown(fname, ent->uid, ent->gid);
2692 warn("can't chown %s", fname);
2695 if (ent->flags & CE_NODUMP) {
2696 failed = chflags(fname, UF_NODUMP);
2698 warn("can't chflags %s NODUMP", fname);
2703 * Parse a signal number or signal name. Returns the signal number parsed or -1
2707 parse_signal(const char *str)
2712 sig = strtonum(str, 1, sys_nsig - 1, &errstr);
2716 if (strncasecmp(str, "SIG", 3) == 0)
2719 for (i = 1; i < sys_nsig; i++) {
2720 if (strcasecmp(str, sys_signame[i]) == 0)