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>
85 #include "pathnames.h"
89 * Compression suffixes
91 #ifndef COMPRESS_SUFFIX_GZ
92 #define COMPRESS_SUFFIX_GZ ".gz"
95 #ifndef COMPRESS_SUFFIX_BZ2
96 #define COMPRESS_SUFFIX_BZ2 ".bz2"
99 #ifndef COMPRESS_SUFFIX_XZ
100 #define COMPRESS_SUFFIX_XZ ".xz"
103 #define COMPRESS_SUFFIX_MAXLEN MAX(MAX(sizeof(COMPRESS_SUFFIX_GZ),sizeof(COMPRESS_SUFFIX_BZ2)),sizeof(COMPRESS_SUFFIX_XZ))
108 #define COMPRESS_TYPES 4 /* Number of supported compression types */
110 #define COMPRESS_NONE 0
111 #define COMPRESS_GZIP 1
112 #define COMPRESS_BZIP2 2
113 #define COMPRESS_XZ 3
116 * Bit-values for the 'flags' parsed from a config-file entry.
118 #define CE_BINARY 0x0008 /* Logfile is in binary, do not add status */
119 /* messages to logfile(s) when rotating. */
120 #define CE_NOSIGNAL 0x0010 /* There is no process to signal when */
121 /* trimming this file. */
122 #define CE_TRIMAT 0x0020 /* trim file at a specific time. */
123 #define CE_GLOB 0x0040 /* name of the log is file name pattern. */
124 #define CE_SIGNALGROUP 0x0080 /* Signal a process-group instead of a single */
125 /* process when trimming this file. */
126 #define CE_CREATE 0x0100 /* Create the log file if it does not exist. */
127 #define CE_NODUMP 0x0200 /* Set 'nodump' on newly created log file. */
129 #define MIN_PID 5 /* Don't touch pids lower than this */
130 #define MAX_PID 99999 /* was lower, see /usr/include/sys/proc.h */
132 #define kbytes(size) (((size) + 1023) >> 10)
134 #define DEFAULT_MARKER "<default>"
135 #define DEBUG_MARKER "<debug>"
136 #define INCLUDE_MARKER "<include>"
137 #define DEFAULT_TIMEFNAME_FMT "%Y%m%dT%H%M%S"
139 #define MAX_OLDLOGS 65536 /* Default maximum number of old logfiles */
141 struct compress_types {
142 const char *flag; /* Flag in configuration file */
143 const char *suffix; /* Compression suffix */
144 const char *path; /* Path to compression program */
147 const struct compress_types compress_type[COMPRESS_TYPES] = {
148 { "", "", "" }, /* no compression */
149 { "Z", COMPRESS_SUFFIX_GZ, _PATH_GZIP }, /* gzip compression */
150 { "J", COMPRESS_SUFFIX_BZ2, _PATH_BZIP2 }, /* bzip2 compression */
151 { "X", COMPRESS_SUFFIX_XZ, _PATH_XZ } /* xz compression */
155 STAILQ_ENTRY(conf_entry) cf_nextp;
156 char *log; /* Name of the log */
157 char *pid_file; /* PID file */
158 char *r_reason; /* The reason this file is being rotated */
159 int firstcreate; /* Creating log for the first time (-C). */
160 int rotate; /* Non-zero if this file should be rotated */
161 int fsize; /* size found for the log file */
162 uid_t uid; /* Owner of log */
163 gid_t gid; /* Group of log */
164 int numlogs; /* Number of logs to keep */
165 int trsize; /* Size cutoff to trigger trimming the log */
166 int hours; /* Hours between log trimming */
167 struct ptime_data *trim_at; /* Specific time to do trimming */
168 unsigned int permissions; /* File permissions on the log */
169 int flags; /* CE_BINARY */
170 int compress; /* Compression */
171 int sig; /* Signal to send */
172 int def_cfg; /* Using the <default> rule for this file */
175 struct sigwork_entry {
176 SLIST_ENTRY(sigwork_entry) sw_nextp;
177 int sw_signum; /* the signal to send */
178 int sw_pidok; /* true if pid value is valid */
179 pid_t sw_pid; /* the process id from the PID file */
180 const char *sw_pidtype; /* "daemon" or "process group" */
181 char sw_fname[1]; /* file the PID was read from */
184 struct zipwork_entry {
185 SLIST_ENTRY(zipwork_entry) zw_nextp;
186 const struct conf_entry *zw_conf; /* for chown/perm/flag info */
187 const struct sigwork_entry *zw_swork; /* to know success of signal */
188 int zw_fsize; /* size of the file to compress */
189 char zw_fname[1]; /* the file to compress */
192 struct include_entry {
193 STAILQ_ENTRY(include_entry) inc_nextp;
194 const char *file; /* Name of file to process */
197 struct oldlog_entry {
198 char *fname; /* Filename of the log file */
199 time_t t; /* Parses timestamp of the logfile */
206 STAILQ_HEAD(cflist, conf_entry);
207 SLIST_HEAD(swlisthead, sigwork_entry) swhead = SLIST_HEAD_INITIALIZER(swhead);
208 SLIST_HEAD(zwlisthead, zipwork_entry) zwhead = SLIST_HEAD_INITIALIZER(zwhead);
209 STAILQ_HEAD(ilist, include_entry);
211 int dbg_at_times; /* -D Show details of 'trim_at' code */
213 int archtodir = 0; /* Archive old logfiles to other directory */
214 int createlogs; /* Create (non-GLOB) logfiles which do not */
215 /* already exist. 1=='for entries with */
216 /* C flag', 2=='for all entries'. */
217 int verbose = 0; /* Print out what's going on */
218 int needroot = 1; /* Root privs are necessary */
219 int noaction = 0; /* Don't do anything, just show it */
220 int norotate = 0; /* Don't rotate */
221 int nosignal; /* Do not send any signals */
222 int enforcepid = 0; /* If PID file does not exist or empty, do nothing */
223 int force = 0; /* Force the trim no matter what */
224 int rotatereq = 0; /* -R = Always rotate the file(s) as given */
225 /* on the command (this also requires */
226 /* that a list of files *are* given on */
227 /* the run command). */
228 char *requestor; /* The name given on a -R request */
229 char *timefnamefmt = NULL; /* Use time based filenames instead of .0 etc */
230 char *archdirname; /* Directory path to old logfiles archive */
231 char *destdir = NULL; /* Directory to treat at root for logs */
232 const char *conf; /* Configuration file to use */
234 struct ptime_data *dbg_timenow; /* A "timenow" value set via -D option */
235 struct ptime_data *timenow; /* The time to use for checking at-fields */
237 #define DAYTIME_LEN 16
238 char daytime[DAYTIME_LEN]; /* The current time in human readable form,
239 * used for rotation-tracking messages. */
240 char hostname[MAXHOSTNAMELEN]; /* hostname */
242 const char *path_syslogpid = _PATH_SYSLOGPID;
244 static struct cflist *get_worklist(char **files);
245 static void parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
246 struct conf_entry *defconf_p, struct ilist *inclist);
247 static void add_to_queue(const char *fname, struct ilist *inclist);
248 static char *sob(char *p);
249 static char *son(char *p);
250 static int isnumberstr(const char *);
251 static int isglobstr(const char *);
252 static char *missing_field(char *p, char *errline);
253 static void change_attrs(const char *, const struct conf_entry *);
254 static const char *get_logfile_suffix(const char *logfile);
255 static fk_entry do_entry(struct conf_entry *);
256 static fk_entry do_rotate(const struct conf_entry *);
257 static void do_sigwork(struct sigwork_entry *);
258 static void do_zipwork(struct zipwork_entry *);
259 static struct sigwork_entry *
260 save_sigwork(const struct conf_entry *);
261 static struct zipwork_entry *
262 save_zipwork(const struct conf_entry *, const struct
263 sigwork_entry *, int, const char *);
264 static void set_swpid(struct sigwork_entry *, const struct conf_entry *);
265 static int sizefile(const char *);
266 static void expand_globs(struct cflist *work_p, struct cflist *glob_p);
267 static void free_clist(struct cflist *list);
268 static void free_entry(struct conf_entry *ent);
269 static struct conf_entry *init_entry(const char *fname,
270 struct conf_entry *src_entry);
271 static void parse_args(int argc, char **argv);
272 static int parse_doption(const char *doption);
273 static void usage(void);
274 static int log_trim(const char *logname, const struct conf_entry *log_ent);
275 static int age_old_log(char *file);
276 static void savelog(char *from, char *to);
277 static void createdir(const struct conf_entry *ent, char *dirpart);
278 static void createlog(const struct conf_entry *ent);
281 * All the following take a parameter of 'int', but expect values in the
282 * range of unsigned char. Define wrappers which take values of type 'char',
283 * whether signed or unsigned, and ensure they end up in the right range.
285 #define isdigitch(Anychar) isdigit((u_char)(Anychar))
286 #define isprintch(Anychar) isprint((u_char)(Anychar))
287 #define isspacech(Anychar) isspace((u_char)(Anychar))
288 #define tolowerch(Anychar) tolower((u_char)(Anychar))
291 main(int argc, char **argv)
293 struct cflist *worklist;
294 struct conf_entry *p;
295 struct sigwork_entry *stmp;
296 struct zipwork_entry *ztmp;
301 parse_args(argc, argv);
305 if (needroot && getuid() && geteuid())
306 errx(1, "must have root privs");
307 worklist = get_worklist(argv);
310 * Rotate all the files which need to be rotated. Note that
311 * some users have *hundreds* of entries in newsyslog.conf!
313 while (!STAILQ_EMPTY(worklist)) {
314 p = STAILQ_FIRST(worklist);
315 STAILQ_REMOVE_HEAD(worklist, cf_nextp);
316 if (do_entry(p) == FREE_ENT)
321 * Send signals to any processes which need a signal to tell
322 * them to close and re-open the log file(s) we have rotated.
323 * Note that zipwork_entries include pointers to these
324 * sigwork_entry's, so we can not free the entries here.
326 if (!SLIST_EMPTY(&swhead)) {
327 if (noaction || verbose)
328 printf("Signal all daemon process(es)...\n");
329 SLIST_FOREACH(stmp, &swhead, sw_nextp)
332 printf("\tsleep 10\n");
335 printf("Pause 10 seconds to allow daemon(s)"
336 " to close log file(s)\n");
341 * Compress all files that we're expected to compress, now
342 * that all processes should have closed the files which
345 if (!SLIST_EMPTY(&zwhead)) {
346 if (noaction || verbose)
347 printf("Compress all rotated log file(s)...\n");
348 while (!SLIST_EMPTY(&zwhead)) {
349 ztmp = SLIST_FIRST(&zwhead);
351 SLIST_REMOVE_HEAD(&zwhead, zw_nextp);
355 /* Now free all the sigwork entries. */
356 while (!SLIST_EMPTY(&swhead)) {
357 stmp = SLIST_FIRST(&swhead);
358 SLIST_REMOVE_HEAD(&swhead, sw_nextp);
362 while (wait(NULL) > 0 || errno == EINTR)
367 static struct conf_entry *
368 init_entry(const char *fname, struct conf_entry *src_entry)
370 struct conf_entry *tempwork;
373 printf("\t--> [creating entry for %s]\n", fname);
375 tempwork = malloc(sizeof(struct conf_entry));
376 if (tempwork == NULL)
377 err(1, "malloc of conf_entry for %s", fname);
379 if (destdir == NULL || fname[0] != '/')
380 tempwork->log = strdup(fname);
382 asprintf(&tempwork->log, "%s%s", destdir, fname);
383 if (tempwork->log == NULL)
384 err(1, "strdup for %s", fname);
386 if (src_entry != NULL) {
387 tempwork->pid_file = NULL;
388 if (src_entry->pid_file)
389 tempwork->pid_file = strdup(src_entry->pid_file);
390 tempwork->r_reason = NULL;
391 tempwork->firstcreate = 0;
392 tempwork->rotate = 0;
393 tempwork->fsize = -1;
394 tempwork->uid = src_entry->uid;
395 tempwork->gid = src_entry->gid;
396 tempwork->numlogs = src_entry->numlogs;
397 tempwork->trsize = src_entry->trsize;
398 tempwork->hours = src_entry->hours;
399 tempwork->trim_at = NULL;
400 if (src_entry->trim_at != NULL)
401 tempwork->trim_at = ptime_init(src_entry->trim_at);
402 tempwork->permissions = src_entry->permissions;
403 tempwork->flags = src_entry->flags;
404 tempwork->compress = src_entry->compress;
405 tempwork->sig = src_entry->sig;
406 tempwork->def_cfg = src_entry->def_cfg;
408 /* Initialize as a "do-nothing" entry */
409 tempwork->pid_file = NULL;
410 tempwork->r_reason = NULL;
411 tempwork->firstcreate = 0;
412 tempwork->rotate = 0;
413 tempwork->fsize = -1;
414 tempwork->uid = (uid_t)-1;
415 tempwork->gid = (gid_t)-1;
416 tempwork->numlogs = 1;
417 tempwork->trsize = -1;
418 tempwork->hours = -1;
419 tempwork->trim_at = NULL;
420 tempwork->permissions = 0;
422 tempwork->compress = COMPRESS_NONE;
423 tempwork->sig = SIGHUP;
424 tempwork->def_cfg = 0;
431 free_entry(struct conf_entry *ent)
437 if (ent->log != NULL) {
439 printf("\t--> [freeing entry for %s]\n", ent->log);
444 if (ent->pid_file != NULL) {
446 ent->pid_file = NULL;
449 if (ent->r_reason != NULL) {
451 ent->r_reason = NULL;
454 if (ent->trim_at != NULL) {
455 ptime_free(ent->trim_at);
463 free_clist(struct cflist *list)
465 struct conf_entry *ent;
467 while (!STAILQ_EMPTY(list)) {
468 ent = STAILQ_FIRST(list);
469 STAILQ_REMOVE_HEAD(list, cf_nextp);
478 do_entry(struct conf_entry * ent)
480 #define REASON_MAX 80
482 fk_entry free_or_keep;
484 char temp_reason[REASON_MAX];
486 free_or_keep = FREE_ENT;
488 printf("%s <%d%s>: ", ent->log, ent->numlogs,
489 compress_type[ent->compress].flag);
490 ent->fsize = sizefile(ent->log);
491 modtime = age_old_log(ent->log);
493 ent->firstcreate = 0;
494 if (ent->fsize < 0) {
496 * If either the C flag or the -C option was specified,
497 * and if we won't be creating the file, then have the
498 * verbose message include a hint as to why the file
499 * will not be created.
501 temp_reason[0] = '\0';
503 ent->firstcreate = 1;
504 else if ((ent->flags & CE_CREATE) && createlogs)
505 ent->firstcreate = 1;
506 else if (ent->flags & CE_CREATE)
507 strlcpy(temp_reason, " (no -C option)", REASON_MAX);
509 strlcpy(temp_reason, " (no C flag)", REASON_MAX);
511 if (ent->firstcreate) {
513 printf("does not exist -> will create.\n");
515 } else if (verbose) {
516 printf("does not exist, skipped%s.\n", temp_reason);
519 if (ent->flags & CE_TRIMAT && !force && !rotatereq) {
520 diffsecs = ptimeget_diff(timenow, ent->trim_at);
521 if (diffsecs < 0.0) {
522 /* trim_at is some time in the future. */
524 ptime_adjust4dst(ent->trim_at,
526 printf("--> will trim at %s",
527 ptimeget_ctime(ent->trim_at));
529 return (free_or_keep);
530 } else if (diffsecs >= 3600.0) {
532 * trim_at is more than an hour in the past,
533 * so find the next valid trim_at time, and
534 * tell the user what that will be.
536 if (verbose && dbg_at_times)
537 printf("\n\t--> prev trim at %s\t",
538 ptimeget_ctime(ent->trim_at));
540 ptimeset_nxtime(ent->trim_at);
541 printf("--> will trim at %s",
542 ptimeget_ctime(ent->trim_at));
544 return (free_or_keep);
545 } else if (verbose && noaction && dbg_at_times) {
547 * If we are just debugging at-times, then
548 * a detailed message is helpful. Also
549 * skip "doing" any commands, since they
550 * would all be turned off by no-action.
552 printf("\n\t--> timematch at %s",
553 ptimeget_ctime(ent->trim_at));
554 return (free_or_keep);
555 } else if (verbose && ent->hours <= 0) {
556 printf("--> time is up\n");
559 if (verbose && (ent->trsize > 0))
560 printf("size (Kb): %d [%d] ", ent->fsize, ent->trsize);
561 if (verbose && (ent->hours > 0))
562 printf(" age (hr): %d [%d] ", modtime, ent->hours);
565 * Figure out if this logfile needs to be rotated.
567 temp_reason[0] = '\0';
570 snprintf(temp_reason, REASON_MAX, " due to -R from %s",
574 snprintf(temp_reason, REASON_MAX, " due to -F request");
575 } else if ((ent->trsize > 0) && (ent->fsize >= ent->trsize)) {
577 snprintf(temp_reason, REASON_MAX, " due to size>%dK",
579 } else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) {
581 } else if ((ent->hours > 0) && ((modtime >= ent->hours) ||
587 * If the file needs to be rotated, then rotate it.
589 if (ent->rotate && !norotate) {
590 if (temp_reason[0] != '\0')
591 ent->r_reason = strdup(temp_reason);
593 printf("--> trimming log....\n");
594 if (noaction && !verbose)
595 printf("%s <%d%s>: trimming\n", ent->log,
597 compress_type[ent->compress].flag);
598 free_or_keep = do_rotate(ent);
601 printf("--> skipping\n");
604 return (free_or_keep);
609 parse_args(int argc, char **argv)
614 timenow = ptime_init(NULL);
615 ptimeset_time(timenow, time(NULL));
616 strlcpy(daytime, ptimeget_ctime(timenow) + 4, DAYTIME_LEN);
618 /* Let's get our hostname */
619 (void)gethostname(hostname, sizeof(hostname));
621 /* Truncate domain */
622 if ((p = strchr(hostname, '.')) != NULL)
625 /* Parse command line options. */
626 while ((ch = getopt(argc, argv, "a:d:f:nrst:vCD:FNPR:S:")) != -1)
630 archdirname = optarg;
648 if (optarg[0] == '\0' ||
649 strcmp(optarg, "DEFAULT") == 0)
650 timefnamefmt = strdup(DEFAULT_TIMEFNAME_FMT);
652 timefnamefmt = strdup(optarg);
658 /* Useful for things like rc.diskless... */
663 * Set some debugging option. The specific option
664 * depends on the value of optarg. These options
665 * may come and go without notice or documentation.
667 if (parse_doption(optarg))
682 requestor = strdup(optarg);
685 path_syslogpid = optarg;
687 case 'm': /* Used by OpenBSD for "monitor mode" */
693 if (force && norotate) {
694 warnx("Only one of -F and -N may be specified.");
700 if (optind == argc) {
701 warnx("At least one filename must be given when -R is specified.");
705 /* Make sure "requestor" value is safe for a syslog message. */
706 for (p = requestor; *p != '\0'; p++) {
707 if (!isprintch(*p) && (*p != '\t'))
714 * Note that the 'daytime' variable is not changed.
715 * That is only used in messages that track when a
716 * logfile is rotated, and if a file *is* rotated,
717 * then it will still rotated at the "real now" time.
720 timenow = dbg_timenow;
721 fprintf(stderr, "Debug: Running as if TimeNow is %s",
722 ptimeget_ctime(dbg_timenow));
728 * These debugging options are mainly meant for developer use, such
729 * as writing regression-tests. They would not be needed by users
730 * during normal operation of newsyslog...
733 parse_doption(const char *doption)
735 const char TN[] = "TN=";
738 if (strncmp(doption, TN, sizeof(TN) - 1) == 0) {
740 * The "TimeNow" debugging option. This might be off
741 * by an hour when crossing a timezone change.
743 dbg_timenow = ptime_init(NULL);
744 res = ptime_relparse(dbg_timenow, PTM_PARSE_ISO8601,
745 time(NULL), doption + sizeof(TN) - 1);
747 warnx("Non-existent time specified on -D %s", doption);
748 return (0); /* failure */
749 } else if (res < 0) {
750 warnx("Malformed time given on -D %s", doption);
751 return (0); /* failure */
753 return (1); /* successfully parsed */
757 if (strcmp(doption, "ats") == 0) {
759 return (1); /* successfully parsed */
762 /* XXX - This check could probably be dropped. */
763 if ((strcmp(doption, "neworder") == 0) || (strcmp(doption, "oldorder")
765 warnx("NOTE: newsyslog always uses 'neworder'.");
766 return (1); /* successfully parsed */
769 warnx("Unknown -D (debug) option: '%s'", doption);
770 return (0); /* failure */
778 "usage: newsyslog [-CFNnrsv] [-a directory] [-d directory] [-f config-file]\n"
779 " [-S pidfile] [-t timefmt ] [ [-R requestor] filename ... ]\n");
784 * Parse a configuration file and return a linked list of all the logs
785 * which should be processed.
787 static struct cflist *
788 get_worklist(char **files)
792 struct cflist *cmdlist, *filelist, *globlist;
793 struct conf_entry *defconf, *dupent, *ent;
794 struct ilist inclist;
795 struct include_entry *inc;
799 STAILQ_INIT(&inclist);
801 filelist = malloc(sizeof(struct cflist));
802 if (filelist == NULL)
803 err(1, "malloc of filelist");
804 STAILQ_INIT(filelist);
805 globlist = malloc(sizeof(struct cflist));
806 if (globlist == NULL)
807 err(1, "malloc of globlist");
808 STAILQ_INIT(globlist);
810 inc = malloc(sizeof(struct include_entry));
812 err(1, "malloc of inc");
814 if (inc->file == NULL)
815 inc->file = _PATH_CONF;
816 STAILQ_INSERT_TAIL(&inclist, inc, inc_nextp);
818 STAILQ_FOREACH(inc, &inclist, inc_nextp) {
819 if (strcmp(inc->file, "-") != 0)
820 f = fopen(inc->file, "r");
823 inc->file = "<stdin>";
826 err(1, "%s", inc->file);
829 printf("Processing %s\n", inc->file);
830 parse_file(f, filelist, globlist, defconf, &inclist);
835 * All config-file information has been read in and turned into
836 * a filelist and a globlist. If there were no specific files
837 * given on the run command, then the only thing left to do is to
838 * call a routine which finds all files matched by the globlist
839 * and adds them to the filelist. Then return the worklist.
841 if (*files == NULL) {
842 expand_globs(filelist, globlist);
843 free_clist(globlist);
851 * If newsyslog was given a specific list of files to process,
852 * it may be that some of those files were not listed in any
853 * config file. Those unlisted files should get the default
854 * rotation action. First, create the default-rotation action
855 * if none was found in a system config file.
857 if (defconf == NULL) {
858 defconf = init_entry(DEFAULT_MARKER, NULL);
859 defconf->numlogs = 3;
860 defconf->trsize = 50;
861 defconf->permissions = S_IRUSR|S_IWUSR;
865 * If newsyslog was run with a list of specific filenames,
866 * then create a new worklist which has only those files in
867 * it, picking up the rotation-rules for those files from
868 * the original filelist.
870 * XXX - Note that this will copy multiple rules for a single
871 * logfile, if multiple entries are an exact match for
872 * that file. That matches the historic behavior, but do
873 * we want to continue to allow it? If so, it should
874 * probably be handled more intelligently.
876 cmdlist = malloc(sizeof(struct cflist));
878 err(1, "malloc of cmdlist");
879 STAILQ_INIT(cmdlist);
881 for (given = files; *given; ++given) {
883 * First try to find exact-matches for this given file.
886 STAILQ_FOREACH(ent, filelist, cf_nextp) {
887 if (strcmp(ent->log, *given) == 0) {
889 dupent = init_entry(*given, ent);
890 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
895 printf("\t+ Matched entry %s\n", *given);
900 * There was no exact-match for this given file, so look
901 * for a "glob" entry which does match.
904 if (verbose > 2 && globlist != NULL)
905 printf("\t+ Checking globs for %s\n", *given);
906 STAILQ_FOREACH(ent, globlist, cf_nextp) {
907 fnres = fnmatch(ent->log, *given, FNM_PATHNAME);
909 printf("\t+ = %d for pattern %s\n", fnres,
913 dupent = init_entry(*given, ent);
914 /* This new entry is not a glob! */
915 dupent->flags &= ~CE_GLOB;
916 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
917 /* Only allow a match to one glob-entry */
923 printf("\t+ Matched %s via %s\n", *given,
929 * This given file was not found in any config file, so
930 * add a worklist item based on the default entry.
933 printf("\t+ No entry matched %s (will use %s)\n",
934 *given, DEFAULT_MARKER);
935 dupent = init_entry(*given, defconf);
936 /* Mark that it was *not* found in a config file */
938 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
942 * Free all the entries in the original work list, the list of
943 * glob entries, and the default entry.
945 free_clist(filelist);
946 free_clist(globlist);
949 /* And finally, return a worklist which matches the given files. */
954 * Expand the list of entries with filename patterns, and add all files
955 * which match those glob-entries onto the worklist.
958 expand_globs(struct cflist *work_p, struct cflist *glob_p)
963 struct conf_entry *dupent, *ent, *globent;
968 * The worklist contains all fully-specified (non-GLOB) names.
970 * Now expand the list of filename-pattern (GLOB) entries into
971 * a second list, which (by definition) will only match files
972 * that already exist. Do not add a glob-related entry for any
973 * file which already exists in the fully-specified list.
975 STAILQ_FOREACH(globent, glob_p, cf_nextp) {
976 gres = glob(globent->log, GLOB_NOCHECK, NULL, &pglob);
978 warn("cannot expand pattern (%d): %s", gres,
984 printf("\t+ Expanding pattern %s\n", globent->log);
985 for (i = 0; i < pglob.gl_matchc; i++) {
986 mfname = pglob.gl_pathv[i];
988 /* See if this file already has a specific entry. */
990 STAILQ_FOREACH(ent, work_p, cf_nextp) {
991 if (strcmp(mfname, ent->log) == 0) {
999 /* Make sure the named matched is a file. */
1000 gres = lstat(mfname, &st_fm);
1002 /* Error on a file that glob() matched?!? */
1003 warn("Skipping %s - lstat() error", mfname);
1006 if (!S_ISREG(st_fm.st_mode)) {
1007 /* We only rotate files! */
1009 printf("\t+ . skipping %s (!file)\n",
1015 printf("\t+ . add file %s\n", mfname);
1016 dupent = init_entry(mfname, globent);
1017 /* This new entry is not a glob! */
1018 dupent->flags &= ~CE_GLOB;
1020 /* Add to the worklist. */
1021 STAILQ_INSERT_TAIL(work_p, dupent, cf_nextp);
1025 printf("\t+ Done with pattern %s\n", globent->log);
1030 * Parse a configuration file and update a linked list of all the logs to
1034 parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
1035 struct conf_entry *defconf_p, struct ilist *inclist)
1037 char line[BUFSIZ], *parse, *q;
1038 char *cp, *errline, *group;
1039 struct conf_entry *working;
1043 int eol, ptm_opts, res, special;
1047 while (fgets(line, BUFSIZ, cf)) {
1048 if ((line[0] == '\n') || (line[0] == '#') ||
1049 (strlen(line) == 0))
1051 if (errline != NULL)
1053 errline = strdup(line);
1054 for (cp = line + 1; *cp != '\0'; cp++) {
1057 if (*(cp - 1) == '\\') {
1066 q = parse = missing_field(sob(line), errline);
1069 errx(1, "malformed line (missing fields):\n%s",
1074 * Allow people to set debug options via the config file.
1075 * (NOTE: debug options are undocumented, and may disappear
1076 * at any time, etc).
1078 if (strcasecmp(DEBUG_MARKER, q) == 0) {
1079 q = parse = missing_field(sob(++parse), errline);
1082 warnx("debug line specifies no option:\n%s",
1089 } else if (strcasecmp(INCLUDE_MARKER, q) == 0) {
1091 printf("Found: %s", errline);
1092 q = parse = missing_field(sob(++parse), errline);
1095 warnx("include line missing argument:\n%s",
1103 res = glob(q, GLOB_NOCHECK, NULL, &pglob);
1105 warn("cannot expand pattern (%d): %s",
1111 printf("\t+ Expanding pattern %s\n", q);
1113 for (i = 0; i < pglob.gl_matchc; i++)
1114 add_to_queue(pglob.gl_pathv[i],
1118 add_to_queue(q, inclist);
1123 working = init_entry(q, NULL);
1124 if (strcasecmp(DEFAULT_MARKER, q) == 0) {
1126 if (defconf_p != NULL) {
1127 warnx("Ignoring duplicate entry for %s!", q);
1128 free_entry(working);
1131 defconf_p = working;
1134 q = parse = missing_field(sob(++parse), errline);
1137 errx(1, "malformed line (missing fields):\n%s",
1140 if ((group = strchr(q, ':')) != NULL ||
1141 (group = strrchr(q, '.')) != NULL) {
1144 if (!(isnumberstr(q))) {
1145 if ((pwd = getpwnam(q)) == NULL)
1147 "error in config file; unknown user:\n%s",
1149 working->uid = pwd->pw_uid;
1151 working->uid = atoi(q);
1153 working->uid = (uid_t)-1;
1157 if (!(isnumberstr(q))) {
1158 if ((grp = getgrnam(q)) == NULL)
1160 "error in config file; unknown group:\n%s",
1162 working->gid = grp->gr_gid;
1164 working->gid = atoi(q);
1166 working->gid = (gid_t)-1;
1168 q = parse = missing_field(sob(++parse), errline);
1171 errx(1, "malformed line (missing fields):\n%s",
1175 working->uid = (uid_t)-1;
1176 working->gid = (gid_t)-1;
1179 if (!sscanf(q, "%o", &working->permissions))
1180 errx(1, "error in config file; bad permissions:\n%s",
1183 q = parse = missing_field(sob(++parse), errline);
1186 errx(1, "malformed line (missing fields):\n%s",
1189 if (!sscanf(q, "%d", &working->numlogs) || working->numlogs < 0)
1190 errx(1, "error in config file; bad value for count of logs to save:\n%s",
1193 q = parse = missing_field(sob(++parse), errline);
1196 errx(1, "malformed line (missing fields):\n%s",
1200 working->trsize = atoi(q);
1201 else if (strcmp(q, "*") == 0)
1202 working->trsize = -1;
1204 warnx("Invalid value of '%s' for 'size' in line:\n%s",
1206 working->trsize = -1;
1210 working->compress = COMPRESS_NONE;
1211 q = parse = missing_field(sob(++parse), errline);
1219 ul = strtoul(q, &ep, 10);
1222 else if (*ep == '*')
1223 working->hours = -1;
1224 else if (ul > INT_MAX)
1225 errx(1, "interval is too large:\n%s", errline);
1227 working->hours = ul;
1229 if (*ep == '\0' || strcmp(ep, "*") == 0)
1231 if (*ep != '@' && *ep != '$')
1232 errx(1, "malformed interval/at:\n%s", errline);
1234 working->flags |= CE_TRIMAT;
1235 working->trim_at = ptime_init(NULL);
1236 ptm_opts = PTM_PARSE_ISO8601;
1238 ptm_opts = PTM_PARSE_DWM;
1239 ptm_opts |= PTM_PARSE_MATCHDOM;
1240 res = ptime_relparse(working->trim_at, ptm_opts,
1241 ptimeget_secs(timenow), ep + 1);
1243 errx(1, "nonexistent time for 'at' value:\n%s",
1246 errx(1, "malformed 'at' value:\n%s", errline);
1253 q = parse = sob(++parse); /* Optional field */
1260 for (; q && *q && !isspacech(*q); q++) {
1261 switch (tolowerch(*q)) {
1263 working->flags |= CE_BINARY;
1267 * XXX - Ick! Ugly! Remove ASAP!
1268 * We want `c' and `C' for "create". But we
1269 * will temporarily treat `c' as `g', because
1270 * FreeBSD releases <= 4.8 have a typo of
1271 * checking ('G' || 'c') for CE_GLOB.
1274 warnx("Assuming 'g' for 'c' in flags for line:\n%s",
1276 warnx("The 'c' flag will eventually mean 'CREATE'");
1277 working->flags |= CE_GLOB;
1280 working->flags |= CE_CREATE;
1283 working->flags |= CE_NODUMP;
1286 working->flags |= CE_GLOB;
1289 working->compress = COMPRESS_BZIP2;
1292 working->flags |= CE_NOSIGNAL;
1295 working->flags |= CE_SIGNALGROUP;
1298 /* Depreciated flag - keep for compatibility purposes */
1301 working->compress = COMPRESS_XZ;
1304 working->compress = COMPRESS_GZIP;
1308 case 'f': /* Used by OpenBSD for "CE_FOLLOW" */
1309 case 'm': /* Used by OpenBSD for "CE_MONITOR" */
1310 case 'p': /* Used by NetBSD for "CE_PLAIN0" */
1312 errx(1, "illegal flag in config file -- %c",
1320 q = parse = sob(++parse); /* Optional field */
1327 working->pid_file = NULL;
1330 working->pid_file = strdup(q);
1331 else if (isdigit(*q))
1335 "illegal pid file or signal number in config file:\n%s",
1341 q = parse = sob(++parse); /* Optional field */
1342 *(parse = son(parse)) = '\0';
1345 working->sig = SIGHUP;
1349 working->sig = atoi(q);
1353 "illegal signal number in config file:\n%s",
1356 if (working->sig < 1 || working->sig >= NSIG)
1361 * Finish figuring out what pid-file to use (if any) in
1362 * later processing if this logfile needs to be rotated.
1364 if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) {
1366 * This config-entry specified 'n' for nosignal,
1367 * see if it also specified an explicit pid_file.
1368 * This would be a pretty pointless combination.
1370 if (working->pid_file != NULL) {
1371 warnx("Ignoring '%s' because flag 'n' was specified in line:\n%s",
1372 working->pid_file, errline);
1373 free(working->pid_file);
1374 working->pid_file = NULL;
1376 } else if (working->pid_file == NULL) {
1378 * This entry did not specify the 'n' flag, which
1379 * means it should signal syslogd unless it had
1380 * specified some other pid-file (and obviously the
1381 * syslog pid-file will not be for a process-group).
1382 * Also, we should only try to notify syslog if we
1385 if (working->flags & CE_SIGNALGROUP) {
1386 warnx("Ignoring flag 'U' in line:\n%s",
1388 working->flags &= ~CE_SIGNALGROUP;
1391 working->pid_file = strdup(path_syslogpid);
1395 * Add this entry to the appropriate list of entries, unless
1396 * it was some kind of special entry (eg: <default>).
1399 ; /* Do not add to any list */
1400 } else if (working->flags & CE_GLOB) {
1401 STAILQ_INSERT_TAIL(glob_p, working, cf_nextp);
1403 STAILQ_INSERT_TAIL(work_p, working, cf_nextp);
1406 if (errline != NULL)
1411 missing_field(char *p, char *errline)
1415 errx(1, "missing field in config file:\n%s", errline);
1420 * In our sort we return it in the reverse of what qsort normally
1421 * would do, as we want the newest files first. If we have two
1422 * entries with the same time we don't really care about order.
1424 * Support function for qsort() in delete_oldest_timelog().
1427 oldlog_entry_compare(const void *a, const void *b)
1429 const struct oldlog_entry *ola = a, *olb = b;
1431 if (ola->t > olb->t)
1433 else if (ola->t < olb->t)
1440 * Delete the oldest logfiles, when using time based filenames.
1443 delete_oldest_timelog(const struct conf_entry *ent, const char *archive_dir)
1445 char *logfname, *s, *dir, errbuf[80];
1446 int dirfd, i, logcnt, max_logcnt, valid;
1447 struct oldlog_entry *oldlogs;
1448 size_t logfname_len;
1454 oldlogs = malloc(MAX_OLDLOGS * sizeof(struct oldlog_entry));
1455 max_logcnt = MAX_OLDLOGS;
1458 if (archive_dir != NULL && archive_dir[0] != '\0')
1461 if ((cdir = dirname(ent->log)) == NULL)
1462 err(1, "dirname()");
1463 if ((dir = strdup(cdir)) == NULL)
1466 if ((s = basename(ent->log)) == NULL)
1467 err(1, "basename()");
1468 if ((logfname = strdup(s)) == NULL)
1470 logfname_len = strlen(logfname);
1471 if (strcmp(logfname, "/") == 0)
1472 errx(1, "Invalid log filename - became '/'");
1475 printf("Searching for old logs in %s\n", dir);
1477 /* First we create a 'list' of all archived logfiles */
1478 if ((dirp = opendir(dir)) == NULL)
1479 err(1, "Cannot open log directory '%s'", dir);
1480 dirfd = dirfd(dirp);
1481 while ((dp = readdir(dirp)) != NULL) {
1482 if (dp->d_type != DT_REG)
1485 /* Ignore everything but files with our logfile prefix */
1486 if (strncmp(dp->d_name, logfname, logfname_len) != 0)
1488 /* Ignore the actual non-rotated logfile */
1489 if (dp->d_namlen == logfname_len)
1492 * Make sure we created have found a logfile, so the
1493 * postfix is valid, IE format is: '.<time>(.[bg]z)?'.
1495 if (dp->d_name[logfname_len] != '.') {
1497 printf("Ignoring %s which has unexpected "
1498 "extension '%s'\n", dp->d_name,
1499 &dp->d_name[logfname_len]);
1502 if ((s = strptime(&dp->d_name[logfname_len + 1],
1503 timefnamefmt, &tm)) == NULL) {
1505 * We could special case "old" sequentially
1506 * named logfiles here, but we do not as that
1507 * would require special handling to decide
1508 * which one was the oldest compared to "new"
1509 * time based logfiles.
1512 printf("Ignoring %s which does not "
1513 "match time format\n", dp->d_name);
1517 for (int c = 0; c < COMPRESS_TYPES; c++)
1518 if (strcmp(s, compress_type[c].suffix) == 0)
1522 printf("Ignoring %s which has unexpected "
1523 "extension '%s'\n", dp->d_name, s);
1528 * We should now have old an old rotated logfile, so
1529 * add it to the 'list'.
1531 if ((oldlogs[logcnt].t = timegm(&tm)) == -1)
1532 err(1, "Could not convert time string to time value");
1533 if ((oldlogs[logcnt].fname = strdup(dp->d_name)) == NULL)
1538 * It is very unlikely we ever run out of space in the
1539 * logfile array from the default size, but lets
1540 * handle it anyway...
1542 if (logcnt >= max_logcnt) {
1544 /* Detect integer overflow */
1545 if (max_logcnt < logcnt)
1546 errx(1, "Too many old logfiles found");
1547 oldlogs = realloc(oldlogs,
1548 max_logcnt * sizeof(struct oldlog_entry));
1549 if (oldlogs == NULL)
1550 err(1, "realloc()");
1554 /* Second, if needed we delete oldest archived logfiles */
1555 if (logcnt > 0 && logcnt >= ent->numlogs && ent->numlogs > 1) {
1556 oldlogs = realloc(oldlogs, logcnt *
1557 sizeof(struct oldlog_entry));
1558 if (oldlogs == NULL)
1559 err(1, "realloc()");
1562 * We now sort the logs in the order of newest to
1563 * oldest. That way we can simply skip over the
1564 * number of records we want to keep.
1566 qsort(oldlogs, logcnt, sizeof(struct oldlog_entry),
1567 oldlog_entry_compare);
1568 for (i = ent->numlogs - 1; i < logcnt; i++) {
1570 printf("\trm -f %s/%s\n", dir,
1572 else if (unlinkat(dirfd, oldlogs[i].fname, 0) != 0) {
1573 snprintf(errbuf, sizeof(errbuf),
1574 "Could not delet old logfile '%s'",
1579 } else if (verbose > 1)
1580 printf("No old logs to delete for logfile %s\n", ent->log);
1582 /* Third, cleanup */
1584 for (i = 0; i < logcnt; i++) {
1585 assert(oldlogs[i].fname != NULL);
1586 free(oldlogs[i].fname);
1594 * Only add to the queue if the file hasn't already been added. This is
1595 * done to prevent circular include loops.
1598 add_to_queue(const char *fname, struct ilist *inclist)
1600 struct include_entry *inc;
1602 STAILQ_FOREACH(inc, inclist, inc_nextp) {
1603 if (strcmp(fname, inc->file) == 0) {
1604 warnx("duplicate include detected: %s", fname);
1609 inc = malloc(sizeof(struct include_entry));
1611 err(1, "malloc of inc");
1612 inc->file = strdup(fname);
1615 printf("\t+ Adding %s to the processing queue.\n", fname);
1617 STAILQ_INSERT_TAIL(inclist, inc, inc_nextp);
1621 * Search for logfile and return its compression suffix (if supported)
1622 * The suffix detection is first-match in the order of compress_types
1624 * Note: if logfile without suffix exists (uncompressed, COMPRESS_NONE)
1625 * a zero-length string is returned
1628 get_logfile_suffix(const char *logfile)
1631 char zfile[MAXPATHLEN];
1633 for (int c = 0; c < COMPRESS_TYPES; c++) {
1634 (void) strlcpy(zfile, logfile, MAXPATHLEN);
1635 (void) strlcat(zfile, compress_type[c].suffix, MAXPATHLEN);
1636 if (lstat(zfile, &st) == 0)
1637 return (compress_type[c].suffix);
1643 do_rotate(const struct conf_entry *ent)
1645 char dirpart[MAXPATHLEN], namepart[MAXPATHLEN];
1646 char file1[MAXPATHLEN], file2[MAXPATHLEN];
1647 char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN];
1648 const char *logfile_suffix;
1649 char datetimestr[30];
1650 int flags, numlogs_c;
1651 fk_entry free_or_keep;
1652 struct sigwork_entry *swork;
1658 free_or_keep = FREE_ENT;
1663 /* build complete name of archive directory into dirpart */
1664 if (*archdirname == '/') { /* absolute */
1665 strlcpy(dirpart, archdirname, sizeof(dirpart));
1666 } else { /* relative */
1667 /* get directory part of logfile */
1668 strlcpy(dirpart, ent->log, sizeof(dirpart));
1669 if ((p = rindex(dirpart, '/')) == NULL)
1673 strlcat(dirpart, archdirname, sizeof(dirpart));
1676 /* check if archive directory exists, if not, create it */
1677 if (lstat(dirpart, &st))
1678 createdir(ent, dirpart);
1680 /* get filename part of logfile */
1681 if ((p = rindex(ent->log, '/')) == NULL)
1682 strlcpy(namepart, ent->log, sizeof(namepart));
1684 strlcpy(namepart, p + 1, sizeof(namepart));
1686 /* name of oldest log */
1687 (void) snprintf(file1, sizeof(file1), "%s/%s.%d", dirpart,
1688 namepart, ent->numlogs);
1691 * Tell delete_oldest_timelog() we are not using an
1696 /* name of oldest log */
1697 (void) snprintf(file1, sizeof(file1), "%s.%d", ent->log,
1701 /* Delete old logs */
1702 if (timefnamefmt != NULL)
1703 delete_oldest_timelog(ent, dirpart);
1705 /* name of oldest log */
1706 for (int c = 0; c < COMPRESS_TYPES; c++) {
1707 (void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1708 compress_type[c].suffix);
1710 printf("\trm -f %s\n", zfile1);
1712 (void) unlink(zfile1);
1716 if (timefnamefmt != NULL) {
1717 /* If time functions fails we can't really do any sensible */
1718 if (time(&now) == (time_t)-1 ||
1719 localtime_r(&now, &tm) == NULL)
1720 bzero(&tm, sizeof(tm));
1722 strftime(datetimestr, sizeof(datetimestr), timefnamefmt, &tm);
1724 (void) snprintf(file1, sizeof(file1), "%s/%s.%s",
1725 dirpart, namepart, datetimestr);
1727 (void) snprintf(file1, sizeof(file1), "%s.%s",
1728 ent->log, datetimestr);
1730 /* Don't run the code to move down logs */
1733 numlogs_c = ent->numlogs; /* copy for countdown */
1735 /* Move down log files */
1736 while (numlogs_c--) {
1738 (void) strlcpy(file2, file1, sizeof(file2));
1741 (void) snprintf(file1, sizeof(file1), "%s/%s.%d",
1742 dirpart, namepart, numlogs_c);
1744 (void) snprintf(file1, sizeof(file1), "%s.%d",
1745 ent->log, numlogs_c);
1747 logfile_suffix = get_logfile_suffix(file1);
1748 if (logfile_suffix == NULL)
1750 (void) strlcpy(zfile1, file1, MAXPATHLEN);
1751 (void) strlcpy(zfile2, file2, MAXPATHLEN);
1752 (void) strlcat(zfile1, logfile_suffix, MAXPATHLEN);
1753 (void) strlcat(zfile2, logfile_suffix, MAXPATHLEN);
1756 printf("\tmv %s %s\n", zfile1, zfile2);
1758 /* XXX - Ought to be checking for failure! */
1759 (void)rename(zfile1, zfile2);
1761 change_attrs(zfile2, ent);
1764 if (ent->numlogs > 0) {
1767 * Note that savelog() may succeed with using link()
1768 * for the archtodir case, but there is no good way
1769 * of knowing if it will when doing "noaction", so
1770 * here we claim that it will have to do a copy...
1773 printf("\tcp %s %s\n", ent->log, file1);
1775 printf("\tln %s %s\n", ent->log, file1);
1777 if (!(flags & CE_BINARY)) {
1778 /* Report the trimming to the old log */
1779 log_trim(ent->log, ent);
1781 savelog(ent->log, file1);
1783 change_attrs(file1, ent);
1786 /* Create the new log file and move it into place */
1788 printf("Start new log...\n");
1792 * Save all signalling and file-compression to be done after log
1793 * files from all entries have been rotated. This way any one
1794 * process will not be sent the same signal multiple times when
1795 * multiple log files had to be rotated.
1798 if (ent->pid_file != NULL)
1799 swork = save_sigwork(ent);
1800 if (ent->numlogs > 0 && ent->compress > COMPRESS_NONE) {
1802 * The zipwork_entry will include a pointer to this
1803 * conf_entry, so the conf_entry should not be freed.
1805 free_or_keep = KEEP_ENT;
1806 save_zipwork(ent, swork, ent->fsize, file1);
1809 return (free_or_keep);
1813 do_sigwork(struct sigwork_entry *swork)
1815 struct sigwork_entry *nextsig;
1818 if (!(swork->sw_pidok) || swork->sw_pid == 0)
1819 return; /* no work to do... */
1822 * If nosignal (-s) was specified, then do not signal any process.
1823 * Note that a nosignal request triggers a warning message if the
1824 * rotated logfile needs to be compressed, *unless* -R was also
1825 * specified. We assume that an `-sR' request came from a process
1826 * which writes to the logfile, and as such, we assume that process
1827 * has already made sure the logfile is not presently in use. This
1828 * just sets swork->sw_pidok to a special value, and do_zipwork
1829 * will print any necessary warning(s).
1833 swork->sw_pidok = -1;
1838 * Compute the pause between consecutive signals. Use a longer
1839 * sleep time if we will be sending two signals to the same
1840 * deamon or process-group.
1843 nextsig = SLIST_NEXT(swork, sw_nextp);
1844 if (nextsig != NULL) {
1845 if (swork->sw_pid == nextsig->sw_pid)
1852 printf("\tkill -%d %d \t\t# %s\n", swork->sw_signum,
1853 (int)swork->sw_pid, swork->sw_fname);
1855 printf("\tsleep %d\n", secs);
1859 kres = kill(swork->sw_pid, swork->sw_signum);
1862 * Assume that "no such process" (ESRCH) is something
1863 * to warn about, but is not an error. Presumably the
1864 * process which writes to the rotated log file(s) is
1865 * gone, in which case we should have no problem with
1866 * compressing the rotated log file(s).
1869 swork->sw_pidok = 0;
1870 warn("can't notify %s, pid %d", swork->sw_pidtype,
1871 (int)swork->sw_pid);
1874 printf("Notified %s pid %d = %s\n", swork->sw_pidtype,
1875 (int)swork->sw_pid, swork->sw_fname);
1878 printf("Pause %d second(s) between signals\n",
1886 do_zipwork(struct zipwork_entry *zwork)
1888 const char *pgm_name, *pgm_path;
1889 int errsav, fcount, zstatus;
1891 char zresult[MAXPATHLEN];
1894 strlcpy(zresult, zwork->zw_fname, sizeof(zresult));
1895 if (zwork != NULL && zwork->zw_conf != NULL &&
1896 zwork->zw_conf->compress > COMPRESS_NONE)
1897 for (int c = 1; c < COMPRESS_TYPES; c++) {
1898 if (zwork->zw_conf->compress == c) {
1899 pgm_path = compress_type[c].path;
1900 (void) strlcat(zresult,
1901 compress_type[c].suffix, sizeof(zresult));
1905 if (pgm_path == NULL) {
1906 warnx("invalid entry for %s in do_zipwork", zwork->zw_fname);
1909 pgm_name = strrchr(pgm_path, '/');
1910 if (pgm_name == NULL)
1911 pgm_name = pgm_path;
1915 if (zwork->zw_swork != NULL && zwork->zw_swork->sw_pidok <= 0) {
1917 "log %s not compressed because daemon(s) not notified",
1919 change_attrs(zwork->zw_fname, zwork->zw_conf);
1924 printf("\t%s %s\n", pgm_name, zwork->zw_fname);
1925 change_attrs(zresult, zwork->zw_conf);
1931 while (pidzip < 0) {
1933 * The fork failed. If the failure was due to a temporary
1934 * problem, then wait a short time and try it again.
1937 warn("fork() for `%s %s'", pgm_name, zwork->zw_fname);
1938 if (errsav != EAGAIN || fcount > 5)
1939 errx(1, "Exiting...");
1945 /* The child process executes the compression command */
1946 execl(pgm_path, pgm_path, "-f", zwork->zw_fname, (char *)0);
1947 err(1, "execl(`%s -f %s')", pgm_path, zwork->zw_fname);
1950 wpid = waitpid(pidzip, &zstatus, 0);
1952 /* XXX - should this be a fatal error? */
1953 warn("%s: waitpid(%d)", pgm_path, pidzip);
1956 if (!WIFEXITED(zstatus)) {
1957 warnx("`%s -f %s' did not terminate normally", pgm_name,
1961 if (WEXITSTATUS(zstatus)) {
1962 warnx("`%s -f %s' terminated with a non-zero status (%d)",
1963 pgm_name, zwork->zw_fname, WEXITSTATUS(zstatus));
1967 /* Compression was successful, set file attributes on the result. */
1968 change_attrs(zresult, zwork->zw_conf);
1972 * Save information on any process we need to signal. Any single
1973 * process may need to be sent different signal-values for different
1974 * log files, but usually a single signal-value will cause the process
1975 * to close and re-open all of it's log files.
1977 static struct sigwork_entry *
1978 save_sigwork(const struct conf_entry *ent)
1980 struct sigwork_entry *sprev, *stmp;
1986 SLIST_FOREACH(stmp, &swhead, sw_nextp) {
1987 ndiff = strcmp(ent->pid_file, stmp->sw_fname);
1991 if (ent->sig == stmp->sw_signum)
1993 if (ent->sig > stmp->sw_signum) {
2000 if (stmp != NULL && ndiff == 0)
2003 tmpsiz = sizeof(struct sigwork_entry) + strlen(ent->pid_file) + 1;
2004 stmp = malloc(tmpsiz);
2005 set_swpid(stmp, ent);
2006 stmp->sw_signum = ent->sig;
2007 strcpy(stmp->sw_fname, ent->pid_file);
2009 SLIST_INSERT_HEAD(&swhead, stmp, sw_nextp);
2011 SLIST_INSERT_AFTER(sprev, stmp, sw_nextp);
2016 * Save information on any file we need to compress. We may see the same
2017 * file multiple times, so check the full list to avoid duplicates. The
2018 * list itself is sorted smallest-to-largest, because that's the order we
2019 * want to compress the files. If the partition is very low on disk space,
2020 * then the smallest files are the most likely to compress, and compressing
2021 * them first will free up more space for the larger files.
2023 static struct zipwork_entry *
2024 save_zipwork(const struct conf_entry *ent, const struct sigwork_entry *swork,
2025 int zsize, const char *zipfname)
2027 struct zipwork_entry *zprev, *ztmp;
2031 /* Compute the size if the caller did not know it. */
2033 zsize = sizefile(zipfname);
2037 SLIST_FOREACH(ztmp, &zwhead, zw_nextp) {
2038 ndiff = strcmp(zipfname, ztmp->zw_fname);
2041 if (zsize > ztmp->zw_fsize)
2044 if (ztmp != NULL && ndiff == 0)
2047 tmpsiz = sizeof(struct zipwork_entry) + strlen(zipfname) + 1;
2048 ztmp = malloc(tmpsiz);
2049 ztmp->zw_conf = ent;
2050 ztmp->zw_swork = swork;
2051 ztmp->zw_fsize = zsize;
2052 strcpy(ztmp->zw_fname, zipfname);
2054 SLIST_INSERT_HEAD(&zwhead, ztmp, zw_nextp);
2056 SLIST_INSERT_AFTER(zprev, ztmp, zw_nextp);
2060 /* Send a signal to the pid specified by pidfile */
2062 set_swpid(struct sigwork_entry *swork, const struct conf_entry *ent)
2065 long minok, maxok, rval;
2066 char *endp, *linep, line[BUFSIZ];
2070 swork->sw_pidok = 0;
2072 swork->sw_pidtype = "daemon";
2073 if (ent->flags & CE_SIGNALGROUP) {
2075 * If we are expected to signal a process-group when
2076 * rotating this logfile, then the value read in should
2077 * be the negative of a valid process ID.
2081 swork->sw_pidtype = "process-group";
2084 f = fopen(ent->pid_file, "r");
2086 if (errno == ENOENT && enforcepid == 0) {
2088 * Warn if the PID file doesn't exist, but do
2089 * not consider it an error. Most likely it
2090 * means the process has been terminated,
2091 * so it should be safe to rotate any log
2092 * files that the process would have been using.
2094 swork->sw_pidok = 1;
2095 warnx("pid file doesn't exist: %s", ent->pid_file);
2097 warn("can't open pid file: %s", ent->pid_file);
2101 if (fgets(line, BUFSIZ, f) == NULL) {
2103 * Warn if the PID file is empty, but do not consider
2104 * it an error. Most likely it means the process has
2105 * has terminated, so it should be safe to rotate any
2106 * log files that the process would have been using.
2108 if (feof(f) && enforcepid == 0) {
2109 swork->sw_pidok = 1;
2110 warnx("pid file is empty: %s", ent->pid_file);
2112 warn("can't read from pid file: %s", ent->pid_file);
2120 while (*linep == ' ')
2122 rval = strtol(linep, &endp, 10);
2123 if (*endp != '\0' && !isspacech(*endp)) {
2124 warnx("pid file does not start with a valid number: %s",
2126 } else if (rval < minok || rval > maxok) {
2127 warnx("bad value '%ld' for process number in %s",
2128 rval, ent->pid_file);
2130 warnx("\t(expecting value between %ld and %ld)",
2133 swork->sw_pidok = 1;
2134 swork->sw_pid = rval;
2140 /* Log the fact that the logs were turned over */
2142 log_trim(const char *logname, const struct conf_entry *log_ent)
2147 if ((f = fopen(logname, "a")) == NULL)
2150 if (log_ent->def_cfg)
2151 xtra = " using <default> rule";
2152 if (log_ent->firstcreate)
2153 fprintf(f, "%s %s newsyslog[%d]: logfile first created%s\n",
2154 daytime, hostname, (int) getpid(), xtra);
2155 else if (log_ent->r_reason != NULL)
2156 fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s%s\n",
2157 daytime, hostname, (int) getpid(), log_ent->r_reason, xtra);
2159 fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s\n",
2160 daytime, hostname, (int) getpid(), xtra);
2161 if (fclose(f) == EOF)
2162 err(1, "log_trim: fclose");
2166 /* Return size in kilobytes of a file */
2168 sizefile(const char *file)
2172 if (stat(file, &sb) < 0)
2174 return (kbytes(dbtob(sb.st_blocks)));
2177 /* Return the age of old log file (file.0) */
2179 age_old_log(char *file)
2182 const char *logfile_suffix;
2183 char tmp[MAXPATHLEN + sizeof(".0") + COMPRESS_SUFFIX_MAXLEN + 1];
2188 /* build name of archive directory into tmp */
2189 if (*archdirname == '/') { /* absolute */
2190 strlcpy(tmp, archdirname, sizeof(tmp));
2191 } else { /* relative */
2192 /* get directory part of logfile */
2193 strlcpy(tmp, file, sizeof(tmp));
2194 if ((p = rindex(tmp, '/')) == NULL)
2198 strlcat(tmp, archdirname, sizeof(tmp));
2201 strlcat(tmp, "/", sizeof(tmp));
2203 /* get filename part of logfile */
2204 if ((p = rindex(file, '/')) == NULL)
2205 strlcat(tmp, file, sizeof(tmp));
2207 strlcat(tmp, p + 1, sizeof(tmp));
2209 (void) strlcpy(tmp, file, sizeof(tmp));
2212 strlcat(tmp, ".0", sizeof(tmp));
2213 logfile_suffix = get_logfile_suffix(tmp);
2214 if (logfile_suffix == NULL)
2216 (void) strlcat(tmp, logfile_suffix, sizeof(tmp));
2217 if (stat(tmp, &sb) < 0)
2219 return ((int)(ptimeget_secs(timenow) - sb.st_mtime + 1800) / 3600);
2222 /* Skip Over Blanks */
2226 while (p && *p && isspace(*p))
2231 /* Skip Over Non-Blanks */
2235 while (p && *p && !isspace(*p))
2240 /* Check if string is actually a number */
2242 isnumberstr(const char *string)
2245 if (!isdigitch(*string++))
2251 /* Check if string contains a glob */
2253 isglobstr(const char *string)
2257 while ((chr = *string++)) {
2258 if (chr == '*' || chr == '?' || chr == '[')
2265 * Save the active log file under a new name. A link to the new name
2266 * is the quick-and-easy way to do this. If that fails (which it will
2267 * if the destination is on another partition), then make a copy of
2268 * the file to the new location.
2271 savelog(char *from, char *to)
2276 res = link(from, to);
2280 if ((src = fopen(from, "r")) == NULL)
2281 err(1, "can't fopen %s for reading", from);
2282 if ((dst = fopen(to, "w")) == NULL)
2283 err(1, "can't fopen %s for writing", to);
2285 while ((c = getc(src)) != EOF) {
2286 if ((putc(c, dst)) == EOF)
2287 err(1, "error writing to %s", to);
2291 err(1, "error reading from %s", from);
2292 if ((fclose(src)) != 0)
2293 err(1, "can't fclose %s", to);
2294 if ((fclose(dst)) != 0)
2295 err(1, "can't fclose %s", from);
2298 /* create one or more directory components of a path */
2300 createdir(const struct conf_entry *ent, char *dirpart)
2304 char mkdirpath[MAXPATHLEN];
2312 if (*s != '/' && *s != '\0')
2315 res = lstat(mkdirpath, &st);
2318 printf("\tmkdir %s\n", mkdirpath);
2320 res = mkdir(mkdirpath, 0755);
2322 err(1, "Error on mkdir(\"%s\") for -a",
2330 if (ent->firstcreate)
2331 printf("Created directory '%s' for new %s\n",
2334 printf("Created directory '%s' for -a\n", dirpart);
2339 * Create a new log file, destroying any currently-existing version
2340 * of the log file in the process. If the caller wants a backup copy
2341 * of the file to exist, they should call 'link(logfile,logbackup)'
2342 * before calling this routine.
2345 createlog(const struct conf_entry *ent)
2349 char *realfile, *slash, tempfile[MAXPATHLEN];
2352 realfile = ent->log;
2355 * If this log file is being created for the first time (-C option),
2356 * then it may also be true that the parent directory does not exist
2357 * yet. Check, and create that directory if it is missing.
2359 if (ent->firstcreate) {
2360 strlcpy(tempfile, realfile, sizeof(tempfile));
2361 slash = strrchr(tempfile, '/');
2362 if (slash != NULL) {
2364 failed = stat(tempfile, &st);
2365 if (failed && errno != ENOENT)
2366 err(1, "Error on stat(%s)", tempfile);
2368 createdir(ent, tempfile);
2369 else if (!S_ISDIR(st.st_mode))
2370 errx(1, "%s exists but is not a directory",
2376 * First create an unused filename, so it can be chown'ed and
2377 * chmod'ed before it is moved into the real location. mkstemp
2378 * will create the file mode=600 & owned by us. Note that all
2379 * temp files will have a suffix of '.z<something>'.
2381 strlcpy(tempfile, realfile, sizeof(tempfile));
2382 strlcat(tempfile, ".zXXXXXX", sizeof(tempfile));
2384 printf("\tmktemp %s\n", tempfile);
2386 fd = mkstemp(tempfile);
2388 err(1, "can't mkstemp logfile %s", tempfile);
2391 * Add status message to what will become the new log file.
2393 if (!(ent->flags & CE_BINARY)) {
2394 if (log_trim(tempfile, ent))
2395 err(1, "can't add status message to log");
2399 /* Change the owner/group, if we are supposed to */
2400 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2402 printf("\tchown %u:%u %s\n", ent->uid, ent->gid,
2405 failed = fchown(fd, ent->uid, ent->gid);
2407 err(1, "can't fchown temp file %s", tempfile);
2411 /* Turn on NODUMP if it was requested in the config-file. */
2412 if (ent->flags & CE_NODUMP) {
2414 printf("\tchflags nodump %s\n", tempfile);
2416 failed = fchflags(fd, UF_NODUMP);
2418 warn("log_trim: fchflags(NODUMP)");
2424 * Note that if the real logfile still exists, and if the call
2425 * to rename() fails, then "neither the old file nor the new
2426 * file shall be changed or created" (to quote the standard).
2427 * If the call succeeds, then the file will be replaced without
2428 * any window where some other process might find that the file
2430 * XXX - ? It may be that for some error conditions, we could
2431 * retry by first removing the realfile and then renaming.
2434 printf("\tchmod %o %s\n", ent->permissions, tempfile);
2435 printf("\tmv %s %s\n", tempfile, realfile);
2437 failed = fchmod(fd, ent->permissions);
2439 err(1, "can't fchmod temp file '%s'", tempfile);
2440 failed = rename(tempfile, realfile);
2442 err(1, "can't mv %s to %s", tempfile, realfile);
2450 * Change the attributes of a given filename to what was specified in
2451 * the newsyslog.conf entry. This routine is only called for files
2452 * that newsyslog expects that it has created, and thus it is a fatal
2453 * error if this routine finds that the file does not exist.
2456 change_attrs(const char *fname, const struct conf_entry *ent)
2461 printf("\tchmod %o %s\n", ent->permissions, fname);
2463 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
2464 printf("\tchown %u:%u %s\n",
2465 ent->uid, ent->gid, fname);
2467 if (ent->flags & CE_NODUMP)
2468 printf("\tchflags nodump %s\n", fname);
2472 failed = chmod(fname, ent->permissions);
2475 err(1, "chmod(%s) in change_attrs", fname);
2476 warn("change_attrs couldn't chmod(%s)", fname);
2479 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2480 failed = chown(fname, ent->uid, ent->gid);
2482 warn("can't chown %s", fname);
2485 if (ent->flags & CE_NODUMP) {
2486 failed = chflags(fname, UF_NODUMP);
2488 warn("can't chflags %s NODUMP", fname);