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$");
60 #ifndef COMPRESS_POSTFIX
61 #define COMPRESS_POSTFIX ".gz"
63 #ifndef BZCOMPRESS_POSTFIX
64 #define BZCOMPRESS_POSTFIX ".bz2"
67 #include <sys/param.h>
68 #include <sys/queue.h>
88 #include "pathnames.h"
92 * Bit-values for the 'flags' parsed from a config-file entry.
94 #define CE_COMPACT 0x0001 /* Compact the archived log files with gzip. */
95 #define CE_BZCOMPACT 0x0002 /* Compact the archived log files with bzip2. */
96 #define CE_BINARY 0x0008 /* Logfile is in binary, do not add status */
97 /* messages to logfile(s) when rotating. */
98 #define CE_NOSIGNAL 0x0010 /* There is no process to signal when */
99 /* trimming this file. */
100 #define CE_TRIMAT 0x0020 /* trim file at a specific time. */
101 #define CE_GLOB 0x0040 /* name of the log is file name pattern. */
102 #define CE_SIGNALGROUP 0x0080 /* Signal a process-group instead of a single */
103 /* process when trimming this file. */
104 #define CE_CREATE 0x0100 /* Create the log file if it does not exist. */
105 #define CE_NODUMP 0x0200 /* Set 'nodump' on newly created log file. */
107 #define MIN_PID 5 /* Don't touch pids lower than this */
108 #define MAX_PID 99999 /* was lower, see /usr/include/sys/proc.h */
110 #define kbytes(size) (((size) + 1023) >> 10)
112 #define DEFAULT_MARKER "<default>"
113 #define DEBUG_MARKER "<debug>"
114 #define INCLUDE_MARKER "<include>"
117 STAILQ_ENTRY(conf_entry) cf_nextp;
118 char *log; /* Name of the log */
119 char *pid_file; /* PID file */
120 char *r_reason; /* The reason this file is being rotated */
121 int firstcreate; /* Creating log for the first time (-C). */
122 int rotate; /* Non-zero if this file should be rotated */
123 int fsize; /* size found for the log file */
124 uid_t uid; /* Owner of log */
125 gid_t gid; /* Group of log */
126 int numlogs; /* Number of logs to keep */
127 int trsize; /* Size cutoff to trigger trimming the log */
128 int hours; /* Hours between log trimming */
129 struct ptime_data *trim_at; /* Specific time to do trimming */
130 unsigned int permissions; /* File permissions on the log */
131 int flags; /* CE_COMPACT, CE_BZCOMPACT, CE_BINARY */
132 int sig; /* Signal to send */
133 int def_cfg; /* Using the <default> rule for this file */
136 struct sigwork_entry {
137 SLIST_ENTRY(sigwork_entry) sw_nextp;
138 int sw_signum; /* the signal to send */
139 int sw_pidok; /* true if pid value is valid */
140 pid_t sw_pid; /* the process id from the PID file */
141 const char *sw_pidtype; /* "daemon" or "process group" */
142 char sw_fname[1]; /* file the PID was read from */
145 struct zipwork_entry {
146 SLIST_ENTRY(zipwork_entry) zw_nextp;
147 const struct conf_entry *zw_conf; /* for chown/perm/flag info */
148 const struct sigwork_entry *zw_swork; /* to know success of signal */
149 int zw_fsize; /* size of the file to compress */
150 char zw_fname[1]; /* the file to compress */
153 struct include_entry {
154 STAILQ_ENTRY(include_entry) inc_nextp;
155 const char *file; /* Name of file to process */
162 STAILQ_HEAD(cflist, conf_entry);
163 SLIST_HEAD(swlisthead, sigwork_entry) swhead = SLIST_HEAD_INITIALIZER(swhead);
164 SLIST_HEAD(zwlisthead, zipwork_entry) zwhead = SLIST_HEAD_INITIALIZER(zwhead);
165 STAILQ_HEAD(ilist, include_entry);
167 int dbg_at_times; /* -D Show details of 'trim_at' code */
169 int archtodir = 0; /* Archive old logfiles to other directory */
170 int createlogs; /* Create (non-GLOB) logfiles which do not */
171 /* already exist. 1=='for entries with */
172 /* C flag', 2=='for all entries'. */
173 int verbose = 0; /* Print out what's going on */
174 int needroot = 1; /* Root privs are necessary */
175 int noaction = 0; /* Don't do anything, just show it */
176 int norotate = 0; /* Don't rotate */
177 int nosignal; /* Do not send any signals */
178 int enforcepid = 0; /* If PID file does not exist or empty, do nothing */
179 int force = 0; /* Force the trim no matter what */
180 int rotatereq = 0; /* -R = Always rotate the file(s) as given */
181 /* on the command (this also requires */
182 /* that a list of files *are* given on */
183 /* the run command). */
184 char *requestor; /* The name given on a -R request */
185 char *archdirname; /* Directory path to old logfiles archive */
186 char *destdir = NULL; /* Directory to treat at root for logs */
187 const char *conf; /* Configuration file to use */
189 struct ptime_data *dbg_timenow; /* A "timenow" value set via -D option */
190 struct ptime_data *timenow; /* The time to use for checking at-fields */
192 #define DAYTIME_LEN 16
193 char daytime[DAYTIME_LEN]; /* The current time in human readable form,
194 * used for rotation-tracking messages. */
195 char hostname[MAXHOSTNAMELEN]; /* hostname */
197 const char *path_syslogpid = _PATH_SYSLOGPID;
199 static struct cflist *get_worklist(char **files);
200 static void parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
201 struct conf_entry *defconf_p, struct ilist *inclist);
202 static void add_to_queue(const char *fname, struct ilist *inclist);
203 static char *sob(char *p);
204 static char *son(char *p);
205 static int isnumberstr(const char *);
206 static int isglobstr(const char *);
207 static char *missing_field(char *p, char *errline);
208 static void change_attrs(const char *, const struct conf_entry *);
209 static fk_entry do_entry(struct conf_entry *);
210 static fk_entry do_rotate(const struct conf_entry *);
211 static void do_sigwork(struct sigwork_entry *);
212 static void do_zipwork(struct zipwork_entry *);
213 static struct sigwork_entry *
214 save_sigwork(const struct conf_entry *);
215 static struct zipwork_entry *
216 save_zipwork(const struct conf_entry *, const struct
217 sigwork_entry *, int, const char *);
218 static void set_swpid(struct sigwork_entry *, const struct conf_entry *);
219 static int sizefile(const char *);
220 static void expand_globs(struct cflist *work_p, struct cflist *glob_p);
221 static void free_clist(struct cflist *list);
222 static void free_entry(struct conf_entry *ent);
223 static struct conf_entry *init_entry(const char *fname,
224 struct conf_entry *src_entry);
225 static void parse_args(int argc, char **argv);
226 static int parse_doption(const char *doption);
227 static void usage(void);
228 static int log_trim(const char *logname, const struct conf_entry *log_ent);
229 static int age_old_log(char *file);
230 static void savelog(char *from, char *to);
231 static void createdir(const struct conf_entry *ent, char *dirpart);
232 static void createlog(const struct conf_entry *ent);
235 * All the following take a parameter of 'int', but expect values in the
236 * range of unsigned char. Define wrappers which take values of type 'char',
237 * whether signed or unsigned, and ensure they end up in the right range.
239 #define isdigitch(Anychar) isdigit((u_char)(Anychar))
240 #define isprintch(Anychar) isprint((u_char)(Anychar))
241 #define isspacech(Anychar) isspace((u_char)(Anychar))
242 #define tolowerch(Anychar) tolower((u_char)(Anychar))
245 main(int argc, char **argv)
247 struct cflist *worklist;
248 struct conf_entry *p;
249 struct sigwork_entry *stmp;
250 struct zipwork_entry *ztmp;
255 parse_args(argc, argv);
259 if (needroot && getuid() && geteuid())
260 errx(1, "must have root privs");
261 worklist = get_worklist(argv);
264 * Rotate all the files which need to be rotated. Note that
265 * some users have *hundreds* of entries in newsyslog.conf!
267 while (!STAILQ_EMPTY(worklist)) {
268 p = STAILQ_FIRST(worklist);
269 STAILQ_REMOVE_HEAD(worklist, cf_nextp);
270 if (do_entry(p) == FREE_ENT)
275 * Send signals to any processes which need a signal to tell
276 * them to close and re-open the log file(s) we have rotated.
277 * Note that zipwork_entries include pointers to these
278 * sigwork_entry's, so we can not free the entries here.
280 if (!SLIST_EMPTY(&swhead)) {
281 if (noaction || verbose)
282 printf("Signal all daemon process(es)...\n");
283 SLIST_FOREACH(stmp, &swhead, sw_nextp)
286 printf("\tsleep 10\n");
289 printf("Pause 10 seconds to allow daemon(s)"
290 " to close log file(s)\n");
295 * Compress all files that we're expected to compress, now
296 * that all processes should have closed the files which
299 if (!SLIST_EMPTY(&zwhead)) {
300 if (noaction || verbose)
301 printf("Compress all rotated log file(s)...\n");
302 while (!SLIST_EMPTY(&zwhead)) {
303 ztmp = SLIST_FIRST(&zwhead);
305 SLIST_REMOVE_HEAD(&zwhead, zw_nextp);
309 /* Now free all the sigwork entries. */
310 while (!SLIST_EMPTY(&swhead)) {
311 stmp = SLIST_FIRST(&swhead);
312 SLIST_REMOVE_HEAD(&swhead, sw_nextp);
316 while (wait(NULL) > 0 || errno == EINTR)
321 static struct conf_entry *
322 init_entry(const char *fname, struct conf_entry *src_entry)
324 struct conf_entry *tempwork;
327 printf("\t--> [creating entry for %s]\n", fname);
329 tempwork = malloc(sizeof(struct conf_entry));
330 if (tempwork == NULL)
331 err(1, "malloc of conf_entry for %s", fname);
333 if (destdir == NULL || fname[0] != '/')
334 tempwork->log = strdup(fname);
336 asprintf(&tempwork->log, "%s%s", destdir, fname);
337 if (tempwork->log == NULL)
338 err(1, "strdup for %s", fname);
340 if (src_entry != NULL) {
341 tempwork->pid_file = NULL;
342 if (src_entry->pid_file)
343 tempwork->pid_file = strdup(src_entry->pid_file);
344 tempwork->r_reason = NULL;
345 tempwork->firstcreate = 0;
346 tempwork->rotate = 0;
347 tempwork->fsize = -1;
348 tempwork->uid = src_entry->uid;
349 tempwork->gid = src_entry->gid;
350 tempwork->numlogs = src_entry->numlogs;
351 tempwork->trsize = src_entry->trsize;
352 tempwork->hours = src_entry->hours;
353 tempwork->trim_at = NULL;
354 if (src_entry->trim_at != NULL)
355 tempwork->trim_at = ptime_init(src_entry->trim_at);
356 tempwork->permissions = src_entry->permissions;
357 tempwork->flags = src_entry->flags;
358 tempwork->sig = src_entry->sig;
359 tempwork->def_cfg = src_entry->def_cfg;
361 /* Initialize as a "do-nothing" entry */
362 tempwork->pid_file = NULL;
363 tempwork->r_reason = NULL;
364 tempwork->firstcreate = 0;
365 tempwork->rotate = 0;
366 tempwork->fsize = -1;
367 tempwork->uid = (uid_t)-1;
368 tempwork->gid = (gid_t)-1;
369 tempwork->numlogs = 1;
370 tempwork->trsize = -1;
371 tempwork->hours = -1;
372 tempwork->trim_at = NULL;
373 tempwork->permissions = 0;
375 tempwork->sig = SIGHUP;
376 tempwork->def_cfg = 0;
383 free_entry(struct conf_entry *ent)
389 if (ent->log != NULL) {
391 printf("\t--> [freeing entry for %s]\n", ent->log);
396 if (ent->pid_file != NULL) {
398 ent->pid_file = NULL;
401 if (ent->r_reason != NULL) {
403 ent->r_reason = NULL;
406 if (ent->trim_at != NULL) {
407 ptime_free(ent->trim_at);
415 free_clist(struct cflist *list)
417 struct conf_entry *ent;
419 while (!STAILQ_EMPTY(list)) {
420 ent = STAILQ_FIRST(list);
421 STAILQ_REMOVE_HEAD(list, cf_nextp);
430 do_entry(struct conf_entry * ent)
432 #define REASON_MAX 80
434 fk_entry free_or_keep;
436 char temp_reason[REASON_MAX];
438 free_or_keep = FREE_ENT;
440 if (ent->flags & CE_COMPACT)
441 printf("%s <%dZ>: ", ent->log, ent->numlogs);
442 else if (ent->flags & CE_BZCOMPACT)
443 printf("%s <%dJ>: ", ent->log, ent->numlogs);
445 printf("%s <%d>: ", ent->log, ent->numlogs);
447 ent->fsize = sizefile(ent->log);
448 modtime = age_old_log(ent->log);
450 ent->firstcreate = 0;
451 if (ent->fsize < 0) {
453 * If either the C flag or the -C option was specified,
454 * and if we won't be creating the file, then have the
455 * verbose message include a hint as to why the file
456 * will not be created.
458 temp_reason[0] = '\0';
460 ent->firstcreate = 1;
461 else if ((ent->flags & CE_CREATE) && createlogs)
462 ent->firstcreate = 1;
463 else if (ent->flags & CE_CREATE)
464 strlcpy(temp_reason, " (no -C option)", REASON_MAX);
466 strlcpy(temp_reason, " (no C flag)", REASON_MAX);
468 if (ent->firstcreate) {
470 printf("does not exist -> will create.\n");
472 } else if (verbose) {
473 printf("does not exist, skipped%s.\n", temp_reason);
476 if (ent->flags & CE_TRIMAT && !force && !rotatereq) {
477 diffsecs = ptimeget_diff(timenow, ent->trim_at);
478 if (diffsecs < 0.0) {
479 /* trim_at is some time in the future. */
481 ptime_adjust4dst(ent->trim_at,
483 printf("--> will trim at %s",
484 ptimeget_ctime(ent->trim_at));
486 return (free_or_keep);
487 } else if (diffsecs >= 3600.0) {
489 * trim_at is more than an hour in the past,
490 * so find the next valid trim_at time, and
491 * tell the user what that will be.
493 if (verbose && dbg_at_times)
494 printf("\n\t--> prev trim at %s\t",
495 ptimeget_ctime(ent->trim_at));
497 ptimeset_nxtime(ent->trim_at);
498 printf("--> will trim at %s",
499 ptimeget_ctime(ent->trim_at));
501 return (free_or_keep);
502 } else if (verbose && noaction && dbg_at_times) {
504 * If we are just debugging at-times, then
505 * a detailed message is helpful. Also
506 * skip "doing" any commands, since they
507 * would all be turned off by no-action.
509 printf("\n\t--> timematch at %s",
510 ptimeget_ctime(ent->trim_at));
511 return (free_or_keep);
512 } else if (verbose && ent->hours <= 0) {
513 printf("--> time is up\n");
516 if (verbose && (ent->trsize > 0))
517 printf("size (Kb): %d [%d] ", ent->fsize, ent->trsize);
518 if (verbose && (ent->hours > 0))
519 printf(" age (hr): %d [%d] ", modtime, ent->hours);
522 * Figure out if this logfile needs to be rotated.
524 temp_reason[0] = '\0';
527 snprintf(temp_reason, REASON_MAX, " due to -R from %s",
531 snprintf(temp_reason, REASON_MAX, " due to -F request");
532 } else if ((ent->trsize > 0) && (ent->fsize >= ent->trsize)) {
534 snprintf(temp_reason, REASON_MAX, " due to size>%dK",
536 } else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) {
538 } else if ((ent->hours > 0) && ((modtime >= ent->hours) ||
544 * If the file needs to be rotated, then rotate it.
546 if (ent->rotate && !norotate) {
547 if (temp_reason[0] != '\0')
548 ent->r_reason = strdup(temp_reason);
550 printf("--> trimming log....\n");
551 if (noaction && !verbose) {
552 if (ent->flags & CE_COMPACT)
553 printf("%s <%dZ>: trimming\n",
554 ent->log, ent->numlogs);
555 else if (ent->flags & CE_BZCOMPACT)
556 printf("%s <%dJ>: trimming\n",
557 ent->log, ent->numlogs);
559 printf("%s <%d>: trimming\n",
560 ent->log, ent->numlogs);
562 free_or_keep = do_rotate(ent);
565 printf("--> skipping\n");
568 return (free_or_keep);
573 parse_args(int argc, char **argv)
578 timenow = ptime_init(NULL);
579 ptimeset_time(timenow, time(NULL));
580 strlcpy(daytime, ptimeget_ctime(timenow) + 4, DAYTIME_LEN);
582 /* Let's get our hostname */
583 (void)gethostname(hostname, sizeof(hostname));
585 /* Truncate domain */
586 if ((p = strchr(hostname, '.')) != NULL)
589 /* Parse command line options. */
590 while ((ch = getopt(argc, argv, "a:d:f:nrsvCD:FNPR:")) != -1)
594 archdirname = optarg;
615 /* Useful for things like rc.diskless... */
620 * Set some debugging option. The specific option
621 * depends on the value of optarg. These options
622 * may come and go without notice or documentation.
624 if (parse_doption(optarg))
639 requestor = strdup(optarg);
642 path_syslogpid = optarg;
644 case 'm': /* Used by OpenBSD for "monitor mode" */
650 if (force && norotate) {
651 warnx("Only one of -F and -N may be specified.");
657 if (optind == argc) {
658 warnx("At least one filename must be given when -R is specified.");
662 /* Make sure "requestor" value is safe for a syslog message. */
663 for (p = requestor; *p != '\0'; p++) {
664 if (!isprintch(*p) && (*p != '\t'))
671 * Note that the 'daytime' variable is not changed.
672 * That is only used in messages that track when a
673 * logfile is rotated, and if a file *is* rotated,
674 * then it will still rotated at the "real now" time.
677 timenow = dbg_timenow;
678 fprintf(stderr, "Debug: Running as if TimeNow is %s",
679 ptimeget_ctime(dbg_timenow));
685 * These debugging options are mainly meant for developer use, such
686 * as writing regression-tests. They would not be needed by users
687 * during normal operation of newsyslog...
690 parse_doption(const char *doption)
692 const char TN[] = "TN=";
695 if (strncmp(doption, TN, sizeof(TN) - 1) == 0) {
697 * The "TimeNow" debugging option. This might be off
698 * by an hour when crossing a timezone change.
700 dbg_timenow = ptime_init(NULL);
701 res = ptime_relparse(dbg_timenow, PTM_PARSE_ISO8601,
702 time(NULL), doption + sizeof(TN) - 1);
704 warnx("Non-existent time specified on -D %s", doption);
705 return (0); /* failure */
706 } else if (res < 0) {
707 warnx("Malformed time given on -D %s", doption);
708 return (0); /* failure */
710 return (1); /* successfully parsed */
714 if (strcmp(doption, "ats") == 0) {
716 return (1); /* successfully parsed */
719 /* XXX - This check could probably be dropped. */
720 if ((strcmp(doption, "neworder") == 0) || (strcmp(doption, "oldorder")
722 warnx("NOTE: newsyslog always uses 'neworder'.");
723 return (1); /* successfully parsed */
726 warnx("Unknown -D (debug) option: '%s'", doption);
727 return (0); /* failure */
735 "usage: newsyslog [-CFNnrsv] [-a directory] [-d directory] [-f config-file]\n"
736 " [-S pidfile] [ [-R requestor] filename ... ]\n");
741 * Parse a configuration file and return a linked list of all the logs
742 * which should be processed.
744 static struct cflist *
745 get_worklist(char **files)
749 struct cflist *cmdlist, *filelist, *globlist;
750 struct conf_entry *defconf, *dupent, *ent;
751 struct ilist inclist;
752 struct include_entry *inc;
756 STAILQ_INIT(&inclist);
758 filelist = malloc(sizeof(struct cflist));
759 if (filelist == NULL)
760 err(1, "malloc of filelist");
761 STAILQ_INIT(filelist);
762 globlist = malloc(sizeof(struct cflist));
763 if (globlist == NULL)
764 err(1, "malloc of globlist");
765 STAILQ_INIT(globlist);
767 inc = malloc(sizeof(struct include_entry));
769 err(1, "malloc of inc");
771 if (inc->file == NULL)
772 inc->file = _PATH_CONF;
773 STAILQ_INSERT_TAIL(&inclist, inc, inc_nextp);
775 STAILQ_FOREACH(inc, &inclist, inc_nextp) {
776 if (strcmp(inc->file, "-") != 0)
777 f = fopen(inc->file, "r");
780 inc->file = "<stdin>";
783 err(1, "%s", inc->file);
786 printf("Processing %s\n", inc->file);
787 parse_file(f, filelist, globlist, defconf, &inclist);
792 * All config-file information has been read in and turned into
793 * a filelist and a globlist. If there were no specific files
794 * given on the run command, then the only thing left to do is to
795 * call a routine which finds all files matched by the globlist
796 * and adds them to the filelist. Then return the worklist.
798 if (*files == NULL) {
799 expand_globs(filelist, globlist);
800 free_clist(globlist);
808 * If newsyslog was given a specific list of files to process,
809 * it may be that some of those files were not listed in any
810 * config file. Those unlisted files should get the default
811 * rotation action. First, create the default-rotation action
812 * if none was found in a system config file.
814 if (defconf == NULL) {
815 defconf = init_entry(DEFAULT_MARKER, NULL);
816 defconf->numlogs = 3;
817 defconf->trsize = 50;
818 defconf->permissions = S_IRUSR|S_IWUSR;
822 * If newsyslog was run with a list of specific filenames,
823 * then create a new worklist which has only those files in
824 * it, picking up the rotation-rules for those files from
825 * the original filelist.
827 * XXX - Note that this will copy multiple rules for a single
828 * logfile, if multiple entries are an exact match for
829 * that file. That matches the historic behavior, but do
830 * we want to continue to allow it? If so, it should
831 * probably be handled more intelligently.
833 cmdlist = malloc(sizeof(struct cflist));
835 err(1, "malloc of cmdlist");
836 STAILQ_INIT(cmdlist);
838 for (given = files; *given; ++given) {
840 * First try to find exact-matches for this given file.
843 STAILQ_FOREACH(ent, filelist, cf_nextp) {
844 if (strcmp(ent->log, *given) == 0) {
846 dupent = init_entry(*given, ent);
847 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
852 printf("\t+ Matched entry %s\n", *given);
857 * There was no exact-match for this given file, so look
858 * for a "glob" entry which does match.
861 if (verbose > 2 && globlist != NULL)
862 printf("\t+ Checking globs for %s\n", *given);
863 STAILQ_FOREACH(ent, globlist, cf_nextp) {
864 fnres = fnmatch(ent->log, *given, FNM_PATHNAME);
866 printf("\t+ = %d for pattern %s\n", fnres,
870 dupent = init_entry(*given, ent);
871 /* This new entry is not a glob! */
872 dupent->flags &= ~CE_GLOB;
873 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
874 /* Only allow a match to one glob-entry */
880 printf("\t+ Matched %s via %s\n", *given,
886 * This given file was not found in any config file, so
887 * add a worklist item based on the default entry.
890 printf("\t+ No entry matched %s (will use %s)\n",
891 *given, DEFAULT_MARKER);
892 dupent = init_entry(*given, defconf);
893 /* Mark that it was *not* found in a config file */
895 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
899 * Free all the entries in the original work list, the list of
900 * glob entries, and the default entry.
902 free_clist(filelist);
903 free_clist(globlist);
906 /* And finally, return a worklist which matches the given files. */
911 * Expand the list of entries with filename patterns, and add all files
912 * which match those glob-entries onto the worklist.
915 expand_globs(struct cflist *work_p, struct cflist *glob_p)
920 struct conf_entry *dupent, *ent, *globent;
925 * The worklist contains all fully-specified (non-GLOB) names.
927 * Now expand the list of filename-pattern (GLOB) entries into
928 * a second list, which (by definition) will only match files
929 * that already exist. Do not add a glob-related entry for any
930 * file which already exists in the fully-specified list.
932 STAILQ_FOREACH(globent, glob_p, cf_nextp) {
933 gres = glob(globent->log, GLOB_NOCHECK, NULL, &pglob);
935 warn("cannot expand pattern (%d): %s", gres,
941 printf("\t+ Expanding pattern %s\n", globent->log);
942 for (i = 0; i < pglob.gl_matchc; i++) {
943 mfname = pglob.gl_pathv[i];
945 /* See if this file already has a specific entry. */
947 STAILQ_FOREACH(ent, work_p, cf_nextp) {
948 if (strcmp(mfname, ent->log) == 0) {
956 /* Make sure the named matched is a file. */
957 gres = lstat(mfname, &st_fm);
959 /* Error on a file that glob() matched?!? */
960 warn("Skipping %s - lstat() error", mfname);
963 if (!S_ISREG(st_fm.st_mode)) {
964 /* We only rotate files! */
966 printf("\t+ . skipping %s (!file)\n",
972 printf("\t+ . add file %s\n", mfname);
973 dupent = init_entry(mfname, globent);
974 /* This new entry is not a glob! */
975 dupent->flags &= ~CE_GLOB;
977 /* Add to the worklist. */
978 STAILQ_INSERT_TAIL(work_p, dupent, cf_nextp);
982 printf("\t+ Done with pattern %s\n", globent->log);
987 * Parse a configuration file and update a linked list of all the logs to
991 parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
992 struct conf_entry *defconf_p, struct ilist *inclist)
994 char line[BUFSIZ], *parse, *q;
995 char *cp, *errline, *group;
996 struct conf_entry *working;
1000 int eol, ptm_opts, res, special;
1004 while (fgets(line, BUFSIZ, cf)) {
1005 if ((line[0] == '\n') || (line[0] == '#') ||
1006 (strlen(line) == 0))
1008 if (errline != NULL)
1010 errline = strdup(line);
1011 for (cp = line + 1; *cp != '\0'; cp++) {
1014 if (*(cp - 1) == '\\') {
1023 q = parse = missing_field(sob(line), errline);
1026 errx(1, "malformed line (missing fields):\n%s",
1031 * Allow people to set debug options via the config file.
1032 * (NOTE: debug options are undocumented, and may disappear
1033 * at any time, etc).
1035 if (strcasecmp(DEBUG_MARKER, q) == 0) {
1036 q = parse = missing_field(sob(++parse), errline);
1039 warnx("debug line specifies no option:\n%s",
1046 } else if (strcasecmp(INCLUDE_MARKER, q) == 0) {
1048 printf("Found: %s", errline);
1049 q = parse = missing_field(sob(++parse), errline);
1052 warnx("include line missing argument:\n%s",
1060 res = glob(q, GLOB_NOCHECK, NULL, &pglob);
1062 warn("cannot expand pattern (%d): %s",
1068 printf("\t+ Expanding pattern %s\n", q);
1070 for (i = 0; i < pglob.gl_matchc; i++)
1071 add_to_queue(pglob.gl_pathv[i],
1075 add_to_queue(q, inclist);
1080 working = init_entry(q, NULL);
1081 if (strcasecmp(DEFAULT_MARKER, q) == 0) {
1083 if (defconf_p != NULL) {
1084 warnx("Ignoring duplicate entry for %s!", q);
1085 free_entry(working);
1088 defconf_p = working;
1091 q = parse = missing_field(sob(++parse), errline);
1094 errx(1, "malformed line (missing fields):\n%s",
1097 if ((group = strchr(q, ':')) != NULL ||
1098 (group = strrchr(q, '.')) != NULL) {
1101 if (!(isnumberstr(q))) {
1102 if ((pwd = getpwnam(q)) == NULL)
1104 "error in config file; unknown user:\n%s",
1106 working->uid = pwd->pw_uid;
1108 working->uid = atoi(q);
1110 working->uid = (uid_t)-1;
1114 if (!(isnumberstr(q))) {
1115 if ((grp = getgrnam(q)) == NULL)
1117 "error in config file; unknown group:\n%s",
1119 working->gid = grp->gr_gid;
1121 working->gid = atoi(q);
1123 working->gid = (gid_t)-1;
1125 q = parse = missing_field(sob(++parse), errline);
1128 errx(1, "malformed line (missing fields):\n%s",
1132 working->uid = (uid_t)-1;
1133 working->gid = (gid_t)-1;
1136 if (!sscanf(q, "%o", &working->permissions))
1137 errx(1, "error in config file; bad permissions:\n%s",
1140 q = parse = missing_field(sob(++parse), errline);
1143 errx(1, "malformed line (missing fields):\n%s",
1146 if (!sscanf(q, "%d", &working->numlogs) || working->numlogs < 0)
1147 errx(1, "error in config file; bad value for count of logs to save:\n%s",
1150 q = parse = missing_field(sob(++parse), errline);
1153 errx(1, "malformed line (missing fields):\n%s",
1157 working->trsize = atoi(q);
1158 else if (strcmp(q, "*") == 0)
1159 working->trsize = -1;
1161 warnx("Invalid value of '%s' for 'size' in line:\n%s",
1163 working->trsize = -1;
1167 q = parse = missing_field(sob(++parse), errline);
1175 ul = strtoul(q, &ep, 10);
1178 else if (*ep == '*')
1179 working->hours = -1;
1180 else if (ul > INT_MAX)
1181 errx(1, "interval is too large:\n%s", errline);
1183 working->hours = ul;
1185 if (*ep == '\0' || strcmp(ep, "*") == 0)
1187 if (*ep != '@' && *ep != '$')
1188 errx(1, "malformed interval/at:\n%s", errline);
1190 working->flags |= CE_TRIMAT;
1191 working->trim_at = ptime_init(NULL);
1192 ptm_opts = PTM_PARSE_ISO8601;
1194 ptm_opts = PTM_PARSE_DWM;
1195 ptm_opts |= PTM_PARSE_MATCHDOM;
1196 res = ptime_relparse(working->trim_at, ptm_opts,
1197 ptimeget_secs(timenow), ep + 1);
1199 errx(1, "nonexistent time for 'at' value:\n%s",
1202 errx(1, "malformed 'at' value:\n%s", errline);
1209 q = parse = sob(++parse); /* Optional field */
1216 for (; q && *q && !isspacech(*q); q++) {
1217 switch (tolowerch(*q)) {
1219 working->flags |= CE_BINARY;
1223 * XXX - Ick! Ugly! Remove ASAP!
1224 * We want `c' and `C' for "create". But we
1225 * will temporarily treat `c' as `g', because
1226 * FreeBSD releases <= 4.8 have a typo of
1227 * checking ('G' || 'c') for CE_GLOB.
1230 warnx("Assuming 'g' for 'c' in flags for line:\n%s",
1232 warnx("The 'c' flag will eventually mean 'CREATE'");
1233 working->flags |= CE_GLOB;
1236 working->flags |= CE_CREATE;
1239 working->flags |= CE_NODUMP;
1242 working->flags |= CE_GLOB;
1245 working->flags |= CE_BZCOMPACT;
1248 working->flags |= CE_NOSIGNAL;
1251 working->flags |= CE_SIGNALGROUP;
1254 /* Depreciated flag - keep for compatibility purposes */
1257 working->flags |= CE_COMPACT;
1261 case 'f': /* Used by OpenBSD for "CE_FOLLOW" */
1262 case 'm': /* Used by OpenBSD for "CE_MONITOR" */
1263 case 'p': /* Used by NetBSD for "CE_PLAIN0" */
1265 errx(1, "illegal flag in config file -- %c",
1273 q = parse = sob(++parse); /* Optional field */
1280 working->pid_file = NULL;
1283 working->pid_file = strdup(q);
1284 else if (isdigit(*q))
1288 "illegal pid file or signal number in config file:\n%s",
1294 q = parse = sob(++parse); /* Optional field */
1295 *(parse = son(parse)) = '\0';
1298 working->sig = SIGHUP;
1302 working->sig = atoi(q);
1306 "illegal signal number in config file:\n%s",
1309 if (working->sig < 1 || working->sig >= NSIG)
1314 * Finish figuring out what pid-file to use (if any) in
1315 * later processing if this logfile needs to be rotated.
1317 if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) {
1319 * This config-entry specified 'n' for nosignal,
1320 * see if it also specified an explicit pid_file.
1321 * This would be a pretty pointless combination.
1323 if (working->pid_file != NULL) {
1324 warnx("Ignoring '%s' because flag 'n' was specified in line:\n%s",
1325 working->pid_file, errline);
1326 free(working->pid_file);
1327 working->pid_file = NULL;
1329 } else if (working->pid_file == NULL) {
1331 * This entry did not specify the 'n' flag, which
1332 * means it should signal syslogd unless it had
1333 * specified some other pid-file (and obviously the
1334 * syslog pid-file will not be for a process-group).
1335 * Also, we should only try to notify syslog if we
1338 if (working->flags & CE_SIGNALGROUP) {
1339 warnx("Ignoring flag 'U' in line:\n%s",
1341 working->flags &= ~CE_SIGNALGROUP;
1344 working->pid_file = strdup(path_syslogpid);
1348 * Add this entry to the appropriate list of entries, unless
1349 * it was some kind of special entry (eg: <default>).
1352 ; /* Do not add to any list */
1353 } else if (working->flags & CE_GLOB) {
1354 STAILQ_INSERT_TAIL(glob_p, working, cf_nextp);
1356 STAILQ_INSERT_TAIL(work_p, working, cf_nextp);
1359 if (errline != NULL)
1364 missing_field(char *p, char *errline)
1368 errx(1, "missing field in config file:\n%s", errline);
1373 * Only add to the queue if the file hasn't already been added. This is
1374 * done to prevent circular include loops.
1377 add_to_queue(const char *fname, struct ilist *inclist)
1379 struct include_entry *inc;
1381 STAILQ_FOREACH(inc, inclist, inc_nextp) {
1382 if (strcmp(fname, inc->file) == 0) {
1383 warnx("duplicate include detected: %s", fname);
1388 inc = malloc(sizeof(struct include_entry));
1390 err(1, "malloc of inc");
1391 inc->file = strdup(fname);
1394 printf("\t+ Adding %s to the processing queue.\n", fname);
1396 STAILQ_INSERT_TAIL(inclist, inc, inc_nextp);
1400 do_rotate(const struct conf_entry *ent)
1402 char dirpart[MAXPATHLEN], namepart[MAXPATHLEN];
1403 char file1[MAXPATHLEN], file2[MAXPATHLEN];
1404 char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN];
1405 char jfile1[MAXPATHLEN];
1406 int flags, numlogs_c;
1407 fk_entry free_or_keep;
1408 struct sigwork_entry *swork;
1412 free_or_keep = FREE_ENT;
1417 /* build complete name of archive directory into dirpart */
1418 if (*archdirname == '/') { /* absolute */
1419 strlcpy(dirpart, archdirname, sizeof(dirpart));
1420 } else { /* relative */
1421 /* get directory part of logfile */
1422 strlcpy(dirpart, ent->log, sizeof(dirpart));
1423 if ((p = rindex(dirpart, '/')) == NULL)
1427 strlcat(dirpart, archdirname, sizeof(dirpart));
1430 /* check if archive directory exists, if not, create it */
1431 if (lstat(dirpart, &st))
1432 createdir(ent, dirpart);
1434 /* get filename part of logfile */
1435 if ((p = rindex(ent->log, '/')) == NULL)
1436 strlcpy(namepart, ent->log, sizeof(namepart));
1438 strlcpy(namepart, p + 1, sizeof(namepart));
1440 /* name of oldest log */
1441 (void) snprintf(file1, sizeof(file1), "%s/%s.%d", dirpart,
1442 namepart, ent->numlogs);
1443 (void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1445 snprintf(jfile1, sizeof(jfile1), "%s%s", file1,
1446 BZCOMPRESS_POSTFIX);
1448 /* name of oldest log */
1449 (void) snprintf(file1, sizeof(file1), "%s.%d", ent->log,
1451 (void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1453 snprintf(jfile1, sizeof(jfile1), "%s%s", file1,
1454 BZCOMPRESS_POSTFIX);
1458 printf("\trm -f %s\n", file1);
1459 printf("\trm -f %s\n", zfile1);
1460 printf("\trm -f %s\n", jfile1);
1462 (void) unlink(file1);
1463 (void) unlink(zfile1);
1464 (void) unlink(jfile1);
1467 /* Move down log files */
1468 numlogs_c = ent->numlogs; /* copy for countdown */
1469 while (numlogs_c--) {
1471 (void) strlcpy(file2, file1, sizeof(file2));
1474 (void) snprintf(file1, sizeof(file1), "%s/%s.%d",
1475 dirpart, namepart, numlogs_c);
1477 (void) snprintf(file1, sizeof(file1), "%s.%d",
1478 ent->log, numlogs_c);
1480 (void) strlcpy(zfile1, file1, sizeof(zfile1));
1481 (void) strlcpy(zfile2, file2, sizeof(zfile2));
1482 if (lstat(file1, &st)) {
1483 (void) strlcat(zfile1, COMPRESS_POSTFIX,
1485 (void) strlcat(zfile2, COMPRESS_POSTFIX,
1487 if (lstat(zfile1, &st)) {
1488 strlcpy(zfile1, file1, sizeof(zfile1));
1489 strlcpy(zfile2, file2, sizeof(zfile2));
1490 strlcat(zfile1, BZCOMPRESS_POSTFIX,
1492 strlcat(zfile2, BZCOMPRESS_POSTFIX,
1494 if (lstat(zfile1, &st))
1499 printf("\tmv %s %s\n", zfile1, zfile2);
1501 /* XXX - Ought to be checking for failure! */
1502 (void)rename(zfile1, zfile2);
1504 change_attrs(zfile2, ent);
1507 if (ent->numlogs > 0) {
1510 * Note that savelog() may succeed with using link()
1511 * for the archtodir case, but there is no good way
1512 * of knowing if it will when doing "noaction", so
1513 * here we claim that it will have to do a copy...
1516 printf("\tcp %s %s\n", ent->log, file1);
1518 printf("\tln %s %s\n", ent->log, file1);
1520 if (!(flags & CE_BINARY)) {
1521 /* Report the trimming to the old log */
1522 log_trim(ent->log, ent);
1524 savelog(ent->log, file1);
1526 change_attrs(file1, ent);
1529 /* Create the new log file and move it into place */
1531 printf("Start new log...\n");
1535 * Save all signalling and file-compression to be done after log
1536 * files from all entries have been rotated. This way any one
1537 * process will not be sent the same signal multiple times when
1538 * multiple log files had to be rotated.
1541 if (ent->pid_file != NULL)
1542 swork = save_sigwork(ent);
1543 if (ent->numlogs > 0 && (flags & (CE_COMPACT | CE_BZCOMPACT))) {
1545 * The zipwork_entry will include a pointer to this
1546 * conf_entry, so the conf_entry should not be freed.
1548 free_or_keep = KEEP_ENT;
1549 save_zipwork(ent, swork, ent->fsize, file1);
1552 return (free_or_keep);
1556 do_sigwork(struct sigwork_entry *swork)
1558 struct sigwork_entry *nextsig;
1561 if (!(swork->sw_pidok) || swork->sw_pid == 0)
1562 return; /* no work to do... */
1565 * If nosignal (-s) was specified, then do not signal any process.
1566 * Note that a nosignal request triggers a warning message if the
1567 * rotated logfile needs to be compressed, *unless* -R was also
1568 * specified. We assume that an `-sR' request came from a process
1569 * which writes to the logfile, and as such, we assume that process
1570 * has already made sure the logfile is not presently in use. This
1571 * just sets swork->sw_pidok to a special value, and do_zipwork
1572 * will print any necessary warning(s).
1576 swork->sw_pidok = -1;
1581 * Compute the pause between consecutive signals. Use a longer
1582 * sleep time if we will be sending two signals to the same
1583 * deamon or process-group.
1586 nextsig = SLIST_NEXT(swork, sw_nextp);
1587 if (nextsig != NULL) {
1588 if (swork->sw_pid == nextsig->sw_pid)
1595 printf("\tkill -%d %d \t\t# %s\n", swork->sw_signum,
1596 (int)swork->sw_pid, swork->sw_fname);
1598 printf("\tsleep %d\n", secs);
1602 kres = kill(swork->sw_pid, swork->sw_signum);
1605 * Assume that "no such process" (ESRCH) is something
1606 * to warn about, but is not an error. Presumably the
1607 * process which writes to the rotated log file(s) is
1608 * gone, in which case we should have no problem with
1609 * compressing the rotated log file(s).
1612 swork->sw_pidok = 0;
1613 warn("can't notify %s, pid %d", swork->sw_pidtype,
1614 (int)swork->sw_pid);
1617 printf("Notified %s pid %d = %s\n", swork->sw_pidtype,
1618 (int)swork->sw_pid, swork->sw_fname);
1621 printf("Pause %d second(s) between signals\n",
1629 do_zipwork(struct zipwork_entry *zwork)
1631 const char *pgm_name, *pgm_path;
1632 int errsav, fcount, zstatus;
1634 char zresult[MAXPATHLEN];
1637 strlcpy(zresult, zwork->zw_fname, sizeof(zresult));
1638 if (zwork != NULL && zwork->zw_conf != NULL) {
1639 if (zwork->zw_conf->flags & CE_COMPACT) {
1640 pgm_path = _PATH_GZIP;
1641 strlcat(zresult, COMPRESS_POSTFIX, sizeof(zresult));
1642 } else if (zwork->zw_conf->flags & CE_BZCOMPACT) {
1643 pgm_path = _PATH_BZIP2;
1644 strlcat(zresult, BZCOMPRESS_POSTFIX, sizeof(zresult));
1647 if (pgm_path == NULL) {
1648 warnx("invalid entry for %s in do_zipwork", zwork->zw_fname);
1651 pgm_name = strrchr(pgm_path, '/');
1652 if (pgm_name == NULL)
1653 pgm_name = pgm_path;
1657 if (zwork->zw_swork != NULL && zwork->zw_swork->sw_pidok <= 0) {
1659 "log %s not compressed because daemon(s) not notified",
1661 change_attrs(zwork->zw_fname, zwork->zw_conf);
1666 printf("\t%s %s\n", pgm_name, zwork->zw_fname);
1667 change_attrs(zresult, zwork->zw_conf);
1673 while (pidzip < 0) {
1675 * The fork failed. If the failure was due to a temporary
1676 * problem, then wait a short time and try it again.
1679 warn("fork() for `%s %s'", pgm_name, zwork->zw_fname);
1680 if (errsav != EAGAIN || fcount > 5)
1681 errx(1, "Exiting...");
1687 /* The child process executes the compression command */
1688 execl(pgm_path, pgm_path, "-f", zwork->zw_fname, (char *)0);
1689 err(1, "execl(`%s -f %s')", pgm_path, zwork->zw_fname);
1692 wpid = waitpid(pidzip, &zstatus, 0);
1694 /* XXX - should this be a fatal error? */
1695 warn("%s: waitpid(%d)", pgm_path, pidzip);
1698 if (!WIFEXITED(zstatus)) {
1699 warnx("`%s -f %s' did not terminate normally", pgm_name,
1703 if (WEXITSTATUS(zstatus)) {
1704 warnx("`%s -f %s' terminated with a non-zero status (%d)",
1705 pgm_name, zwork->zw_fname, WEXITSTATUS(zstatus));
1709 /* Compression was successful, set file attributes on the result. */
1710 change_attrs(zresult, zwork->zw_conf);
1714 * Save information on any process we need to signal. Any single
1715 * process may need to be sent different signal-values for different
1716 * log files, but usually a single signal-value will cause the process
1717 * to close and re-open all of it's log files.
1719 static struct sigwork_entry *
1720 save_sigwork(const struct conf_entry *ent)
1722 struct sigwork_entry *sprev, *stmp;
1728 SLIST_FOREACH(stmp, &swhead, sw_nextp) {
1729 ndiff = strcmp(ent->pid_file, stmp->sw_fname);
1733 if (ent->sig == stmp->sw_signum)
1735 if (ent->sig > stmp->sw_signum) {
1742 if (stmp != NULL && ndiff == 0)
1745 tmpsiz = sizeof(struct sigwork_entry) + strlen(ent->pid_file) + 1;
1746 stmp = malloc(tmpsiz);
1747 set_swpid(stmp, ent);
1748 stmp->sw_signum = ent->sig;
1749 strcpy(stmp->sw_fname, ent->pid_file);
1751 SLIST_INSERT_HEAD(&swhead, stmp, sw_nextp);
1753 SLIST_INSERT_AFTER(sprev, stmp, sw_nextp);
1758 * Save information on any file we need to compress. We may see the same
1759 * file multiple times, so check the full list to avoid duplicates. The
1760 * list itself is sorted smallest-to-largest, because that's the order we
1761 * want to compress the files. If the partition is very low on disk space,
1762 * then the smallest files are the most likely to compress, and compressing
1763 * them first will free up more space for the larger files.
1765 static struct zipwork_entry *
1766 save_zipwork(const struct conf_entry *ent, const struct sigwork_entry *swork,
1767 int zsize, const char *zipfname)
1769 struct zipwork_entry *zprev, *ztmp;
1773 /* Compute the size if the caller did not know it. */
1775 zsize = sizefile(zipfname);
1779 SLIST_FOREACH(ztmp, &zwhead, zw_nextp) {
1780 ndiff = strcmp(zipfname, ztmp->zw_fname);
1783 if (zsize > ztmp->zw_fsize)
1786 if (ztmp != NULL && ndiff == 0)
1789 tmpsiz = sizeof(struct zipwork_entry) + strlen(zipfname) + 1;
1790 ztmp = malloc(tmpsiz);
1791 ztmp->zw_conf = ent;
1792 ztmp->zw_swork = swork;
1793 ztmp->zw_fsize = zsize;
1794 strcpy(ztmp->zw_fname, zipfname);
1796 SLIST_INSERT_HEAD(&zwhead, ztmp, zw_nextp);
1798 SLIST_INSERT_AFTER(zprev, ztmp, zw_nextp);
1802 /* Send a signal to the pid specified by pidfile */
1804 set_swpid(struct sigwork_entry *swork, const struct conf_entry *ent)
1807 long minok, maxok, rval;
1808 char *endp, *linep, line[BUFSIZ];
1812 swork->sw_pidok = 0;
1814 swork->sw_pidtype = "daemon";
1815 if (ent->flags & CE_SIGNALGROUP) {
1817 * If we are expected to signal a process-group when
1818 * rotating this logfile, then the value read in should
1819 * be the negative of a valid process ID.
1823 swork->sw_pidtype = "process-group";
1826 f = fopen(ent->pid_file, "r");
1828 if (errno == ENOENT && enforcepid == 0) {
1830 * Warn if the PID file doesn't exist, but do
1831 * not consider it an error. Most likely it
1832 * means the process has been terminated,
1833 * so it should be safe to rotate any log
1834 * files that the process would have been using.
1836 swork->sw_pidok = 1;
1837 warnx("pid file doesn't exist: %s", ent->pid_file);
1839 warn("can't open pid file: %s", ent->pid_file);
1843 if (fgets(line, BUFSIZ, f) == NULL) {
1845 * Warn if the PID file is empty, but do not consider
1846 * it an error. Most likely it means the process has
1847 * has terminated, so it should be safe to rotate any
1848 * log files that the process would have been using.
1850 if (feof(f) && enforcepid == 0) {
1851 swork->sw_pidok = 1;
1852 warnx("pid file is empty: %s", ent->pid_file);
1854 warn("can't read from pid file: %s", ent->pid_file);
1862 while (*linep == ' ')
1864 rval = strtol(linep, &endp, 10);
1865 if (*endp != '\0' && !isspacech(*endp)) {
1866 warnx("pid file does not start with a valid number: %s",
1868 } else if (rval < minok || rval > maxok) {
1869 warnx("bad value '%ld' for process number in %s",
1870 rval, ent->pid_file);
1872 warnx("\t(expecting value between %ld and %ld)",
1875 swork->sw_pidok = 1;
1876 swork->sw_pid = rval;
1882 /* Log the fact that the logs were turned over */
1884 log_trim(const char *logname, const struct conf_entry *log_ent)
1889 if ((f = fopen(logname, "a")) == NULL)
1892 if (log_ent->def_cfg)
1893 xtra = " using <default> rule";
1894 if (log_ent->firstcreate)
1895 fprintf(f, "%s %s newsyslog[%d]: logfile first created%s\n",
1896 daytime, hostname, (int) getpid(), xtra);
1897 else if (log_ent->r_reason != NULL)
1898 fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s%s\n",
1899 daytime, hostname, (int) getpid(), log_ent->r_reason, xtra);
1901 fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s\n",
1902 daytime, hostname, (int) getpid(), xtra);
1903 if (fclose(f) == EOF)
1904 err(1, "log_trim: fclose");
1908 /* Return size in kilobytes of a file */
1910 sizefile(const char *file)
1914 if (stat(file, &sb) < 0)
1916 return (kbytes(dbtob(sb.st_blocks)));
1919 /* Return the age of old log file (file.0) */
1921 age_old_log(char *file)
1925 char tmp[MAXPATHLEN + sizeof(".0") + sizeof(COMPRESS_POSTFIX) +
1926 sizeof(BZCOMPRESS_POSTFIX) + 1];
1931 /* build name of archive directory into tmp */
1932 if (*archdirname == '/') { /* absolute */
1933 strlcpy(tmp, archdirname, sizeof(tmp));
1934 } else { /* relative */
1935 /* get directory part of logfile */
1936 strlcpy(tmp, file, sizeof(tmp));
1937 if ((p = rindex(tmp, '/')) == NULL)
1941 strlcat(tmp, archdirname, sizeof(tmp));
1944 strlcat(tmp, "/", sizeof(tmp));
1946 /* get filename part of logfile */
1947 if ((p = rindex(file, '/')) == NULL)
1948 strlcat(tmp, file, sizeof(tmp));
1950 strlcat(tmp, p + 1, sizeof(tmp));
1952 (void) strlcpy(tmp, file, sizeof(tmp));
1955 strlcat(tmp, ".0", sizeof(tmp));
1956 if (stat(tmp, &sb) < 0) {
1958 * A plain '.0' file does not exist. Try again, first
1959 * with the added suffix of '.gz', then with an added
1960 * suffix of '.bz2' instead of '.gz'.
1962 endp = strchr(tmp, '\0');
1963 strlcat(tmp, COMPRESS_POSTFIX, sizeof(tmp));
1964 if (stat(tmp, &sb) < 0) {
1965 *endp = '\0'; /* Remove .gz */
1966 strlcat(tmp, BZCOMPRESS_POSTFIX, sizeof(tmp));
1967 if (stat(tmp, &sb) < 0)
1971 return ((int)(ptimeget_secs(timenow) - sb.st_mtime + 1800) / 3600);
1974 /* Skip Over Blanks */
1978 while (p && *p && isspace(*p))
1983 /* Skip Over Non-Blanks */
1987 while (p && *p && !isspace(*p))
1992 /* Check if string is actually a number */
1994 isnumberstr(const char *string)
1997 if (!isdigitch(*string++))
2003 /* Check if string contains a glob */
2005 isglobstr(const char *string)
2009 while ((chr = *string++)) {
2010 if (chr == '*' || chr == '?' || chr == '[')
2017 * Save the active log file under a new name. A link to the new name
2018 * is the quick-and-easy way to do this. If that fails (which it will
2019 * if the destination is on another partition), then make a copy of
2020 * the file to the new location.
2023 savelog(char *from, char *to)
2028 res = link(from, to);
2032 if ((src = fopen(from, "r")) == NULL)
2033 err(1, "can't fopen %s for reading", from);
2034 if ((dst = fopen(to, "w")) == NULL)
2035 err(1, "can't fopen %s for writing", to);
2037 while ((c = getc(src)) != EOF) {
2038 if ((putc(c, dst)) == EOF)
2039 err(1, "error writing to %s", to);
2043 err(1, "error reading from %s", from);
2044 if ((fclose(src)) != 0)
2045 err(1, "can't fclose %s", to);
2046 if ((fclose(dst)) != 0)
2047 err(1, "can't fclose %s", from);
2050 /* create one or more directory components of a path */
2052 createdir(const struct conf_entry *ent, char *dirpart)
2056 char mkdirpath[MAXPATHLEN];
2064 if (*s != '/' && *s != '\0')
2067 res = lstat(mkdirpath, &st);
2070 printf("\tmkdir %s\n", mkdirpath);
2072 res = mkdir(mkdirpath, 0755);
2074 err(1, "Error on mkdir(\"%s\") for -a",
2082 if (ent->firstcreate)
2083 printf("Created directory '%s' for new %s\n",
2086 printf("Created directory '%s' for -a\n", dirpart);
2091 * Create a new log file, destroying any currently-existing version
2092 * of the log file in the process. If the caller wants a backup copy
2093 * of the file to exist, they should call 'link(logfile,logbackup)'
2094 * before calling this routine.
2097 createlog(const struct conf_entry *ent)
2101 char *realfile, *slash, tempfile[MAXPATHLEN];
2104 realfile = ent->log;
2107 * If this log file is being created for the first time (-C option),
2108 * then it may also be true that the parent directory does not exist
2109 * yet. Check, and create that directory if it is missing.
2111 if (ent->firstcreate) {
2112 strlcpy(tempfile, realfile, sizeof(tempfile));
2113 slash = strrchr(tempfile, '/');
2114 if (slash != NULL) {
2116 failed = stat(tempfile, &st);
2117 if (failed && errno != ENOENT)
2118 err(1, "Error on stat(%s)", tempfile);
2120 createdir(ent, tempfile);
2121 else if (!S_ISDIR(st.st_mode))
2122 errx(1, "%s exists but is not a directory",
2128 * First create an unused filename, so it can be chown'ed and
2129 * chmod'ed before it is moved into the real location. mkstemp
2130 * will create the file mode=600 & owned by us. Note that all
2131 * temp files will have a suffix of '.z<something>'.
2133 strlcpy(tempfile, realfile, sizeof(tempfile));
2134 strlcat(tempfile, ".zXXXXXX", sizeof(tempfile));
2136 printf("\tmktemp %s\n", tempfile);
2138 fd = mkstemp(tempfile);
2140 err(1, "can't mkstemp logfile %s", tempfile);
2143 * Add status message to what will become the new log file.
2145 if (!(ent->flags & CE_BINARY)) {
2146 if (log_trim(tempfile, ent))
2147 err(1, "can't add status message to log");
2151 /* Change the owner/group, if we are supposed to */
2152 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2154 printf("\tchown %u:%u %s\n", ent->uid, ent->gid,
2157 failed = fchown(fd, ent->uid, ent->gid);
2159 err(1, "can't fchown temp file %s", tempfile);
2163 /* Turn on NODUMP if it was requested in the config-file. */
2164 if (ent->flags & CE_NODUMP) {
2166 printf("\tchflags nodump %s\n", tempfile);
2168 failed = fchflags(fd, UF_NODUMP);
2170 warn("log_trim: fchflags(NODUMP)");
2176 * Note that if the real logfile still exists, and if the call
2177 * to rename() fails, then "neither the old file nor the new
2178 * file shall be changed or created" (to quote the standard).
2179 * If the call succeeds, then the file will be replaced without
2180 * any window where some other process might find that the file
2182 * XXX - ? It may be that for some error conditions, we could
2183 * retry by first removing the realfile and then renaming.
2186 printf("\tchmod %o %s\n", ent->permissions, tempfile);
2187 printf("\tmv %s %s\n", tempfile, realfile);
2189 failed = fchmod(fd, ent->permissions);
2191 err(1, "can't fchmod temp file '%s'", tempfile);
2192 failed = rename(tempfile, realfile);
2194 err(1, "can't mv %s to %s", tempfile, realfile);
2202 * Change the attributes of a given filename to what was specified in
2203 * the newsyslog.conf entry. This routine is only called for files
2204 * that newsyslog expects that it has created, and thus it is a fatal
2205 * error if this routine finds that the file does not exist.
2208 change_attrs(const char *fname, const struct conf_entry *ent)
2213 printf("\tchmod %o %s\n", ent->permissions, fname);
2215 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
2216 printf("\tchown %u:%u %s\n",
2217 ent->uid, ent->gid, fname);
2219 if (ent->flags & CE_NODUMP)
2220 printf("\tchflags nodump %s\n", fname);
2224 failed = chmod(fname, ent->permissions);
2227 err(1, "chmod(%s) in change_attrs", fname);
2228 warn("change_attrs couldn't chmod(%s)", fname);
2231 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2232 failed = chown(fname, ent->uid, ent->gid);
2234 warn("can't chown %s", fname);
2237 if (ent->flags & CE_NODUMP) {
2238 failed = chflags(fname, UF_NODUMP);
2240 warn("can't chflags %s NODUMP", fname);