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>"
116 char *log; /* Name of the log */
117 char *pid_file; /* PID file */
118 char *r_reason; /* The reason this file is being rotated */
119 int firstcreate; /* Creating log for the first time (-C). */
120 int rotate; /* Non-zero if this file should be rotated */
121 int fsize; /* size found for the log file */
122 uid_t uid; /* Owner of log */
123 gid_t gid; /* Group of log */
124 int numlogs; /* Number of logs to keep */
125 int trsize; /* Size cutoff to trigger trimming the log */
126 int hours; /* Hours between log trimming */
127 struct ptime_data *trim_at; /* Specific time to do trimming */
128 unsigned int permissions; /* File permissions on the log */
129 int flags; /* CE_COMPACT, CE_BZCOMPACT, CE_BINARY */
130 int sig; /* Signal to send */
131 int def_cfg; /* Using the <default> rule for this file */
132 struct conf_entry *next;/* Linked list pointer */
135 struct sigwork_entry {
136 SLIST_ENTRY(sigwork_entry) sw_nextp;
137 int sw_signum; /* the signal to send */
138 int sw_pidok; /* true if pid value is valid */
139 pid_t sw_pid; /* the process id from the PID file */
140 const char *sw_pidtype; /* "daemon" or "process group" */
141 char sw_fname[1]; /* file the PID was read from */
144 struct zipwork_entry {
145 SLIST_ENTRY(zipwork_entry) zw_nextp;
146 const struct conf_entry *zw_conf; /* for chown/perm/flag info */
147 const struct sigwork_entry *zw_swork; /* to know success of signal */
148 int zw_fsize; /* size of the file to compress */
149 char zw_fname[1]; /* the file to compress */
156 SLIST_HEAD(swlisthead, sigwork_entry) swhead = SLIST_HEAD_INITIALIZER(swhead);
157 SLIST_HEAD(zwlisthead, zipwork_entry) zwhead = SLIST_HEAD_INITIALIZER(zwhead);
159 int dbg_at_times; /* -D Show details of 'trim_at' code */
161 int archtodir = 0; /* Archive old logfiles to other directory */
162 int createlogs; /* Create (non-GLOB) logfiles which do not */
163 /* already exist. 1=='for entries with */
164 /* C flag', 2=='for all entries'. */
165 int verbose = 0; /* Print out what's going on */
166 int needroot = 1; /* Root privs are necessary */
167 int noaction = 0; /* Don't do anything, just show it */
168 int norotate = 0; /* Don't rotate */
169 int nosignal; /* Do not send any signals */
170 int enforcepid = 0; /* If PID file does not exist or empty, do nothing */
171 int force = 0; /* Force the trim no matter what */
172 int rotatereq = 0; /* -R = Always rotate the file(s) as given */
173 /* on the command (this also requires */
174 /* that a list of files *are* given on */
175 /* the run command). */
176 char *requestor; /* The name given on a -R request */
177 char *archdirname; /* Directory path to old logfiles archive */
178 char *destdir = NULL; /* Directory to treat at root for logs */
179 const char *conf; /* Configuration file to use */
181 struct ptime_data *dbg_timenow; /* A "timenow" value set via -D option */
182 struct ptime_data *timenow; /* The time to use for checking at-fields */
184 #define DAYTIME_LEN 16
185 char daytime[DAYTIME_LEN]; /* The current time in human readable form,
186 * used for rotation-tracking messages. */
187 char hostname[MAXHOSTNAMELEN]; /* hostname */
189 static struct conf_entry *get_worklist(char **files);
190 static void parse_file(FILE *cf, const char *cfname, struct conf_entry **work_p,
191 struct conf_entry **glob_p, struct conf_entry **defconf_p);
192 static char *sob(char *p);
193 static char *son(char *p);
194 static int isnumberstr(const char *);
195 static char *missing_field(char *p, char *errline);
196 static void change_attrs(const char *, const struct conf_entry *);
197 static fk_entry do_entry(struct conf_entry *);
198 static fk_entry do_rotate(const struct conf_entry *);
199 static void do_sigwork(struct sigwork_entry *);
200 static void do_zipwork(struct zipwork_entry *);
201 static struct sigwork_entry *
202 save_sigwork(const struct conf_entry *);
203 static struct zipwork_entry *
204 save_zipwork(const struct conf_entry *, const struct
205 sigwork_entry *, int, const char *);
206 static void set_swpid(struct sigwork_entry *, const struct conf_entry *);
207 static int sizefile(const char *);
208 static void expand_globs(struct conf_entry **work_p,
209 struct conf_entry **glob_p);
210 static void free_clist(struct conf_entry **firstent);
211 static void free_entry(struct conf_entry *ent);
212 static struct conf_entry *init_entry(const char *fname,
213 struct conf_entry *src_entry);
214 static void parse_args(int argc, char **argv);
215 static int parse_doption(const char *doption);
216 static void usage(void);
217 static int log_trim(const char *logname, const struct conf_entry *log_ent);
218 static int age_old_log(char *file);
219 static void savelog(char *from, char *to);
220 static void createdir(const struct conf_entry *ent, char *dirpart);
221 static void createlog(const struct conf_entry *ent);
224 * All the following take a parameter of 'int', but expect values in the
225 * range of unsigned char. Define wrappers which take values of type 'char',
226 * whether signed or unsigned, and ensure they end up in the right range.
228 #define isdigitch(Anychar) isdigit((u_char)(Anychar))
229 #define isprintch(Anychar) isprint((u_char)(Anychar))
230 #define isspacech(Anychar) isspace((u_char)(Anychar))
231 #define tolowerch(Anychar) tolower((u_char)(Anychar))
234 main(int argc, char **argv)
236 fk_entry free_or_keep;
237 struct conf_entry *p, *q;
238 struct sigwork_entry *stmp;
239 struct zipwork_entry *ztmp;
244 parse_args(argc, argv);
248 if (needroot && getuid() && geteuid())
249 errx(1, "must have root privs");
250 p = q = get_worklist(argv);
253 * Rotate all the files which need to be rotated. Note that
254 * some users have *hundreds* of entries in newsyslog.conf!
257 free_or_keep = do_entry(p);
259 if (free_or_keep == FREE_ENT)
265 * Send signals to any processes which need a signal to tell
266 * them to close and re-open the log file(s) we have rotated.
267 * Note that zipwork_entries include pointers to these
268 * sigwork_entry's, so we can not free the entries here.
270 if (!SLIST_EMPTY(&swhead)) {
271 if (noaction || verbose)
272 printf("Signal all daemon process(es)...\n");
273 SLIST_FOREACH(stmp, &swhead, sw_nextp)
276 printf("\tsleep 10\n");
279 printf("Pause 10 seconds to allow daemon(s)"
280 " to close log file(s)\n");
285 * Compress all files that we're expected to compress, now
286 * that all processes should have closed the files which
289 if (!SLIST_EMPTY(&zwhead)) {
290 if (noaction || verbose)
291 printf("Compress all rotated log file(s)...\n");
292 while (!SLIST_EMPTY(&zwhead)) {
293 ztmp = SLIST_FIRST(&zwhead);
295 SLIST_REMOVE_HEAD(&zwhead, zw_nextp);
299 /* Now free all the sigwork entries. */
300 while (!SLIST_EMPTY(&swhead)) {
301 stmp = SLIST_FIRST(&swhead);
302 SLIST_REMOVE_HEAD(&swhead, sw_nextp);
306 while (wait(NULL) > 0 || errno == EINTR)
311 static struct conf_entry *
312 init_entry(const char *fname, struct conf_entry *src_entry)
314 struct conf_entry *tempwork;
317 printf("\t--> [creating entry for %s]\n", fname);
319 tempwork = malloc(sizeof(struct conf_entry));
320 if (tempwork == NULL)
321 err(1, "malloc of conf_entry for %s", fname);
323 if (destdir == NULL || fname[0] != '/')
324 tempwork->log = strdup(fname);
326 asprintf(&tempwork->log, "%s%s", destdir, fname);
327 if (tempwork->log == NULL)
328 err(1, "strdup for %s", fname);
330 if (src_entry != NULL) {
331 tempwork->pid_file = NULL;
332 if (src_entry->pid_file)
333 tempwork->pid_file = strdup(src_entry->pid_file);
334 tempwork->r_reason = NULL;
335 tempwork->firstcreate = 0;
336 tempwork->rotate = 0;
337 tempwork->fsize = -1;
338 tempwork->uid = src_entry->uid;
339 tempwork->gid = src_entry->gid;
340 tempwork->numlogs = src_entry->numlogs;
341 tempwork->trsize = src_entry->trsize;
342 tempwork->hours = src_entry->hours;
343 tempwork->trim_at = NULL;
344 if (src_entry->trim_at != NULL)
345 tempwork->trim_at = ptime_init(src_entry->trim_at);
346 tempwork->permissions = src_entry->permissions;
347 tempwork->flags = src_entry->flags;
348 tempwork->sig = src_entry->sig;
349 tempwork->def_cfg = src_entry->def_cfg;
351 /* Initialize as a "do-nothing" entry */
352 tempwork->pid_file = NULL;
353 tempwork->r_reason = NULL;
354 tempwork->firstcreate = 0;
355 tempwork->rotate = 0;
356 tempwork->fsize = -1;
357 tempwork->uid = (uid_t)-1;
358 tempwork->gid = (gid_t)-1;
359 tempwork->numlogs = 1;
360 tempwork->trsize = -1;
361 tempwork->hours = -1;
362 tempwork->trim_at = NULL;
363 tempwork->permissions = 0;
365 tempwork->sig = SIGHUP;
366 tempwork->def_cfg = 0;
368 tempwork->next = NULL;
374 free_entry(struct conf_entry *ent)
380 if (ent->log != NULL) {
382 printf("\t--> [freeing entry for %s]\n", ent->log);
387 if (ent->pid_file != NULL) {
389 ent->pid_file = NULL;
392 if (ent->r_reason != NULL) {
394 ent->r_reason = NULL;
397 if (ent->trim_at != NULL) {
398 ptime_free(ent->trim_at);
406 free_clist(struct conf_entry **firstent)
408 struct conf_entry *ent, *nextent;
410 if (firstent == NULL)
411 return; /* There is nothing to do. */
424 do_entry(struct conf_entry * ent)
426 #define REASON_MAX 80
428 fk_entry free_or_keep;
430 char temp_reason[REASON_MAX];
432 free_or_keep = FREE_ENT;
434 if (ent->flags & CE_COMPACT)
435 printf("%s <%dZ>: ", ent->log, ent->numlogs);
436 else if (ent->flags & CE_BZCOMPACT)
437 printf("%s <%dJ>: ", ent->log, ent->numlogs);
439 printf("%s <%d>: ", ent->log, ent->numlogs);
441 ent->fsize = sizefile(ent->log);
442 modtime = age_old_log(ent->log);
444 ent->firstcreate = 0;
445 if (ent->fsize < 0) {
447 * If either the C flag or the -C option was specified,
448 * and if we won't be creating the file, then have the
449 * verbose message include a hint as to why the file
450 * will not be created.
452 temp_reason[0] = '\0';
454 ent->firstcreate = 1;
455 else if ((ent->flags & CE_CREATE) && createlogs)
456 ent->firstcreate = 1;
457 else if (ent->flags & CE_CREATE)
458 strlcpy(temp_reason, " (no -C option)", REASON_MAX);
460 strlcpy(temp_reason, " (no C flag)", REASON_MAX);
462 if (ent->firstcreate) {
464 printf("does not exist -> will create.\n");
466 } else if (verbose) {
467 printf("does not exist, skipped%s.\n", temp_reason);
470 if (ent->flags & CE_TRIMAT && !force && !rotatereq) {
471 diffsecs = ptimeget_diff(timenow, ent->trim_at);
472 if (diffsecs < 0.0) {
473 /* trim_at is some time in the future. */
475 ptime_adjust4dst(ent->trim_at,
477 printf("--> will trim at %s",
478 ptimeget_ctime(ent->trim_at));
480 return (free_or_keep);
481 } else if (diffsecs >= 3600.0) {
483 * trim_at is more than an hour in the past,
484 * so find the next valid trim_at time, and
485 * tell the user what that will be.
487 if (verbose && dbg_at_times)
488 printf("\n\t--> prev trim at %s\t",
489 ptimeget_ctime(ent->trim_at));
491 ptimeset_nxtime(ent->trim_at);
492 printf("--> will trim at %s",
493 ptimeget_ctime(ent->trim_at));
495 return (free_or_keep);
496 } else if (verbose && noaction && dbg_at_times) {
498 * If we are just debugging at-times, then
499 * a detailed message is helpful. Also
500 * skip "doing" any commands, since they
501 * would all be turned off by no-action.
503 printf("\n\t--> timematch at %s",
504 ptimeget_ctime(ent->trim_at));
505 return (free_or_keep);
506 } else if (verbose && ent->hours <= 0) {
507 printf("--> time is up\n");
510 if (verbose && (ent->trsize > 0))
511 printf("size (Kb): %d [%d] ", ent->fsize, ent->trsize);
512 if (verbose && (ent->hours > 0))
513 printf(" age (hr): %d [%d] ", modtime, ent->hours);
516 * Figure out if this logfile needs to be rotated.
518 temp_reason[0] = '\0';
521 snprintf(temp_reason, REASON_MAX, " due to -R from %s",
525 snprintf(temp_reason, REASON_MAX, " due to -F request");
526 } else if ((ent->trsize > 0) && (ent->fsize >= ent->trsize)) {
528 snprintf(temp_reason, REASON_MAX, " due to size>%dK",
530 } else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) {
532 } else if ((ent->hours > 0) && ((modtime >= ent->hours) ||
538 * If the file needs to be rotated, then rotate it.
540 if (ent->rotate && !norotate) {
541 if (temp_reason[0] != '\0')
542 ent->r_reason = strdup(temp_reason);
544 printf("--> trimming log....\n");
545 if (noaction && !verbose) {
546 if (ent->flags & CE_COMPACT)
547 printf("%s <%dZ>: trimming\n",
548 ent->log, ent->numlogs);
549 else if (ent->flags & CE_BZCOMPACT)
550 printf("%s <%dJ>: trimming\n",
551 ent->log, ent->numlogs);
553 printf("%s <%d>: trimming\n",
554 ent->log, ent->numlogs);
556 free_or_keep = do_rotate(ent);
559 printf("--> skipping\n");
562 return (free_or_keep);
567 parse_args(int argc, char **argv)
572 timenow = ptime_init(NULL);
573 ptimeset_time(timenow, time(NULL));
574 strlcpy(daytime, ptimeget_ctime(timenow) + 4, DAYTIME_LEN);
576 /* Let's get our hostname */
577 (void)gethostname(hostname, sizeof(hostname));
579 /* Truncate domain */
580 if ((p = strchr(hostname, '.')) != NULL)
583 /* Parse command line options. */
584 while ((ch = getopt(argc, argv, "a:d:f:nrsvCD:FNPR:")) != -1)
588 archdirname = optarg;
609 /* Useful for things like rc.diskless... */
614 * Set some debugging option. The specific option
615 * depends on the value of optarg. These options
616 * may come and go without notice or documentation.
618 if (parse_doption(optarg))
633 requestor = strdup(optarg);
635 case 'm': /* Used by OpenBSD for "monitor mode" */
641 if (force && norotate) {
642 warnx("Only one of -F and -N may be specified.");
648 if (optind == argc) {
649 warnx("At least one filename must be given when -R is specified.");
653 /* Make sure "requestor" value is safe for a syslog message. */
654 for (p = requestor; *p != '\0'; p++) {
655 if (!isprintch(*p) && (*p != '\t'))
662 * Note that the 'daytime' variable is not changed.
663 * That is only used in messages that track when a
664 * logfile is rotated, and if a file *is* rotated,
665 * then it will still rotated at the "real now" time.
668 timenow = dbg_timenow;
669 fprintf(stderr, "Debug: Running as if TimeNow is %s",
670 ptimeget_ctime(dbg_timenow));
676 * These debugging options are mainly meant for developer use, such
677 * as writing regression-tests. They would not be needed by users
678 * during normal operation of newsyslog...
681 parse_doption(const char *doption)
683 const char TN[] = "TN=";
686 if (strncmp(doption, TN, sizeof(TN) - 1) == 0) {
688 * The "TimeNow" debugging option. This might be off
689 * by an hour when crossing a timezone change.
691 dbg_timenow = ptime_init(NULL);
692 res = ptime_relparse(dbg_timenow, PTM_PARSE_ISO8601,
693 time(NULL), doption + sizeof(TN) - 1);
695 warnx("Non-existent time specified on -D %s", doption);
696 return (0); /* failure */
697 } else if (res < 0) {
698 warnx("Malformed time given on -D %s", doption);
699 return (0); /* failure */
701 return (1); /* successfully parsed */
705 if (strcmp(doption, "ats") == 0) {
707 return (1); /* successfully parsed */
710 /* XXX - This check could probably be dropped. */
711 if ((strcmp(doption, "neworder") == 0) || (strcmp(doption, "oldorder")
713 warnx("NOTE: newsyslog always uses 'neworder'.");
714 return (1); /* successfully parsed */
717 warnx("Unknown -D (debug) option: '%s'", doption);
718 return (0); /* failure */
726 "usage: newsyslog [-CFNnrsv] [-a directory] [-d directory] [-f config-file]\n"
727 " [ [-R requestor] filename ... ]\n");
732 * Parse a configuration file and return a linked list of all the logs
733 * which should be processed.
735 static struct conf_entry *
736 get_worklist(char **files)
741 struct conf_entry *defconf, *dupent, *ent, *firstnew;
742 struct conf_entry *globlist, *lastnew, *worklist;
745 defconf = globlist = worklist = NULL;
751 if (strcmp(fname, "-") != 0)
752 f = fopen(fname, "r");
760 parse_file(f, fname, &worklist, &globlist, &defconf);
764 * All config-file information has been read in and turned into
765 * a worklist and a globlist. If there were no specific files
766 * given on the run command, then the only thing left to do is to
767 * call a routine which finds all files matched by the globlist
768 * and adds them to the worklist. Then return the worklist.
770 if (*files == NULL) {
771 expand_globs(&worklist, &globlist);
772 free_clist(&globlist);
780 * If newsyslog was given a specific list of files to process,
781 * it may be that some of those files were not listed in any
782 * config file. Those unlisted files should get the default
783 * rotation action. First, create the default-rotation action
784 * if none was found in a system config file.
786 if (defconf == NULL) {
787 defconf = init_entry(DEFAULT_MARKER, NULL);
788 defconf->numlogs = 3;
789 defconf->trsize = 50;
790 defconf->permissions = S_IRUSR|S_IWUSR;
794 * If newsyslog was run with a list of specific filenames,
795 * then create a new worklist which has only those files in
796 * it, picking up the rotation-rules for those files from
797 * the original worklist.
799 * XXX - Note that this will copy multiple rules for a single
800 * logfile, if multiple entries are an exact match for
801 * that file. That matches the historic behavior, but do
802 * we want to continue to allow it? If so, it should
803 * probably be handled more intelligently.
805 firstnew = lastnew = NULL;
806 for (given = files; *given; ++given) {
808 * First try to find exact-matches for this given file.
811 for (ent = worklist; ent; ent = ent->next) {
812 if (strcmp(ent->log, *given) == 0) {
814 dupent = init_entry(*given, ent);
818 lastnew->next = dupent;
824 printf("\t+ Matched entry %s\n", *given);
829 * There was no exact-match for this given file, so look
830 * for a "glob" entry which does match.
833 if (verbose > 2 && globlist != NULL)
834 printf("\t+ Checking globs for %s\n", *given);
835 for (ent = globlist; ent; ent = ent->next) {
836 fnres = fnmatch(ent->log, *given, FNM_PATHNAME);
838 printf("\t+ = %d for pattern %s\n", fnres,
842 dupent = init_entry(*given, ent);
846 lastnew->next = dupent;
848 /* This new entry is not a glob! */
849 dupent->flags &= ~CE_GLOB;
850 /* Only allow a match to one glob-entry */
856 printf("\t+ Matched %s via %s\n", *given,
862 * This given file was not found in any config file, so
863 * add a worklist item based on the default entry.
866 printf("\t+ No entry matched %s (will use %s)\n",
867 *given, DEFAULT_MARKER);
868 dupent = init_entry(*given, defconf);
872 lastnew->next = dupent;
873 /* Mark that it was *not* found in a config file */
879 * Free all the entries in the original work list, the list of
880 * glob entries, and the default entry.
882 free_clist(&worklist);
883 free_clist(&globlist);
886 /* And finally, return a worklist which matches the given files. */
891 * Expand the list of entries with filename patterns, and add all files
892 * which match those glob-entries onto the worklist.
895 expand_globs(struct conf_entry **work_p, struct conf_entry **glob_p)
900 struct conf_entry *dupent, *ent, *firstmatch, *globent;
901 struct conf_entry *lastmatch;
905 if ((glob_p == NULL) || (*glob_p == NULL))
906 return; /* There is nothing to do. */
909 * The worklist contains all fully-specified (non-GLOB) names.
911 * Now expand the list of filename-pattern (GLOB) entries into
912 * a second list, which (by definition) will only match files
913 * that already exist. Do not add a glob-related entry for any
914 * file which already exists in the fully-specified list.
916 firstmatch = lastmatch = NULL;
917 for (globent = *glob_p; globent; globent = globent->next) {
919 gres = glob(globent->log, GLOB_NOCHECK, NULL, &pglob);
921 warn("cannot expand pattern (%d): %s", gres,
927 printf("\t+ Expanding pattern %s\n", globent->log);
928 for (i = 0; i < pglob.gl_matchc; i++) {
929 mfname = pglob.gl_pathv[i];
931 /* See if this file already has a specific entry. */
933 for (ent = *work_p; ent; ent = ent->next) {
934 if (strcmp(mfname, ent->log) == 0) {
942 /* Make sure the named matched is a file. */
943 gres = lstat(mfname, &st_fm);
945 /* Error on a file that glob() matched?!? */
946 warn("Skipping %s - lstat() error", mfname);
949 if (!S_ISREG(st_fm.st_mode)) {
950 /* We only rotate files! */
952 printf("\t+ . skipping %s (!file)\n",
958 printf("\t+ . add file %s\n", mfname);
959 dupent = init_entry(mfname, globent);
963 lastmatch->next = dupent;
965 /* This new entry is not a glob! */
966 dupent->flags &= ~CE_GLOB;
970 printf("\t+ Done with pattern %s\n", globent->log);
973 /* Add the list of matched files to the end of the worklist. */
975 *work_p = firstmatch;
980 ent->next = firstmatch;
986 * Parse a configuration file and update a linked list of all the logs to
990 parse_file(FILE *cf, const char *cfname, struct conf_entry **work_p,
991 struct conf_entry **glob_p, struct conf_entry **defconf_p)
993 char line[BUFSIZ], *parse, *q;
994 char *cp, *errline, *group;
995 struct conf_entry *lastglob, *lastwork, *working;
998 int eol, ptm_opts, res, special;
1001 * XXX - for now, assume that only one config file will be read,
1002 * ie, this routine is only called one time.
1004 lastglob = lastwork = NULL;
1007 while (fgets(line, BUFSIZ, cf)) {
1008 if ((line[0] == '\n') || (line[0] == '#') ||
1009 (strlen(line) == 0))
1011 if (errline != NULL)
1013 errline = strdup(line);
1014 for (cp = line + 1; *cp != '\0'; cp++) {
1017 if (*(cp - 1) == '\\') {
1026 q = parse = missing_field(sob(line), errline);
1029 errx(1, "malformed line (missing fields):\n%s",
1034 * Allow people to set debug options via the config file.
1035 * (NOTE: debug optons are undocumented, and may disappear
1036 * at any time, etc).
1038 if (strcasecmp(DEBUG_MARKER, q) == 0) {
1039 q = parse = missing_field(sob(++parse), errline);
1042 warnx("debug line specifies no option:\n%s",
1052 working = init_entry(q, NULL);
1053 if (strcasecmp(DEFAULT_MARKER, q) == 0) {
1055 if (defconf_p == NULL) {
1056 warnx("Ignoring entry for %s in %s!", q,
1058 free_entry(working);
1060 } else if (*defconf_p != NULL) {
1061 warnx("Ignoring duplicate entry for %s!", q);
1062 free_entry(working);
1065 *defconf_p = working;
1068 q = parse = missing_field(sob(++parse), errline);
1071 errx(1, "malformed line (missing fields):\n%s",
1074 if ((group = strchr(q, ':')) != NULL ||
1075 (group = strrchr(q, '.')) != NULL) {
1078 if (!(isnumberstr(q))) {
1079 if ((pwd = getpwnam(q)) == NULL)
1081 "error in config file; unknown user:\n%s",
1083 working->uid = pwd->pw_uid;
1085 working->uid = atoi(q);
1087 working->uid = (uid_t)-1;
1091 if (!(isnumberstr(q))) {
1092 if ((grp = getgrnam(q)) == NULL)
1094 "error in config file; unknown group:\n%s",
1096 working->gid = grp->gr_gid;
1098 working->gid = atoi(q);
1100 working->gid = (gid_t)-1;
1102 q = parse = missing_field(sob(++parse), errline);
1105 errx(1, "malformed line (missing fields):\n%s",
1109 working->uid = (uid_t)-1;
1110 working->gid = (gid_t)-1;
1113 if (!sscanf(q, "%o", &working->permissions))
1114 errx(1, "error in config file; bad permissions:\n%s",
1117 q = parse = missing_field(sob(++parse), errline);
1120 errx(1, "malformed line (missing fields):\n%s",
1123 if (!sscanf(q, "%d", &working->numlogs) || working->numlogs < 0)
1124 errx(1, "error in config file; bad value for count of logs to save:\n%s",
1127 q = parse = missing_field(sob(++parse), errline);
1130 errx(1, "malformed line (missing fields):\n%s",
1134 working->trsize = atoi(q);
1135 else if (strcmp(q, "*") == 0)
1136 working->trsize = -1;
1138 warnx("Invalid value of '%s' for 'size' in line:\n%s",
1140 working->trsize = -1;
1144 q = parse = missing_field(sob(++parse), errline);
1152 ul = strtoul(q, &ep, 10);
1155 else if (*ep == '*')
1156 working->hours = -1;
1157 else if (ul > INT_MAX)
1158 errx(1, "interval is too large:\n%s", errline);
1160 working->hours = ul;
1162 if (*ep == '\0' || strcmp(ep, "*") == 0)
1164 if (*ep != '@' && *ep != '$')
1165 errx(1, "malformed interval/at:\n%s", errline);
1167 working->flags |= CE_TRIMAT;
1168 working->trim_at = ptime_init(NULL);
1169 ptm_opts = PTM_PARSE_ISO8601;
1171 ptm_opts = PTM_PARSE_DWM;
1172 ptm_opts |= PTM_PARSE_MATCHDOM;
1173 res = ptime_relparse(working->trim_at, ptm_opts,
1174 ptimeget_secs(timenow), ep + 1);
1176 errx(1, "nonexistent time for 'at' value:\n%s",
1179 errx(1, "malformed 'at' value:\n%s", errline);
1186 q = parse = sob(++parse); /* Optional field */
1193 for (; q && *q && !isspacech(*q); q++) {
1194 switch (tolowerch(*q)) {
1196 working->flags |= CE_BINARY;
1200 * XXX - Ick! Ugly! Remove ASAP!
1201 * We want `c' and `C' for "create". But we
1202 * will temporarily treat `c' as `g', because
1203 * FreeBSD releases <= 4.8 have a typo of
1204 * checking ('G' || 'c') for CE_GLOB.
1207 warnx("Assuming 'g' for 'c' in flags for line:\n%s",
1209 warnx("The 'c' flag will eventually mean 'CREATE'");
1210 working->flags |= CE_GLOB;
1213 working->flags |= CE_CREATE;
1216 working->flags |= CE_NODUMP;
1219 working->flags |= CE_GLOB;
1222 working->flags |= CE_BZCOMPACT;
1225 working->flags |= CE_NOSIGNAL;
1228 working->flags |= CE_SIGNALGROUP;
1231 /* Depreciated flag - keep for compatibility purposes */
1234 working->flags |= CE_COMPACT;
1238 case 'f': /* Used by OpenBSD for "CE_FOLLOW" */
1239 case 'm': /* Used by OpenBSD for "CE_MONITOR" */
1240 case 'p': /* Used by NetBSD for "CE_PLAIN0" */
1242 errx(1, "illegal flag in config file -- %c",
1250 q = parse = sob(++parse); /* Optional field */
1257 working->pid_file = NULL;
1260 working->pid_file = strdup(q);
1261 else if (isdigit(*q))
1265 "illegal pid file or signal number in config file:\n%s",
1271 q = parse = sob(++parse); /* Optional field */
1272 *(parse = son(parse)) = '\0';
1275 working->sig = SIGHUP;
1279 working->sig = atoi(q);
1283 "illegal signal number in config file:\n%s",
1286 if (working->sig < 1 || working->sig >= NSIG)
1291 * Finish figuring out what pid-file to use (if any) in
1292 * later processing if this logfile needs to be rotated.
1294 if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) {
1296 * This config-entry specified 'n' for nosignal,
1297 * see if it also specified an explicit pid_file.
1298 * This would be a pretty pointless combination.
1300 if (working->pid_file != NULL) {
1301 warnx("Ignoring '%s' because flag 'n' was specified in line:\n%s",
1302 working->pid_file, errline);
1303 free(working->pid_file);
1304 working->pid_file = NULL;
1306 } else if (working->pid_file == NULL) {
1308 * This entry did not specify the 'n' flag, which
1309 * means it should signal syslogd unless it had
1310 * specified some other pid-file (and obviously the
1311 * syslog pid-file will not be for a process-group).
1312 * Also, we should only try to notify syslog if we
1315 if (working->flags & CE_SIGNALGROUP) {
1316 warnx("Ignoring flag 'U' in line:\n%s",
1318 working->flags &= ~CE_SIGNALGROUP;
1321 working->pid_file = strdup(_PATH_SYSLOGPID);
1325 * Add this entry to the appropriate list of entries, unless
1326 * it was some kind of special entry (eg: <default>).
1329 ; /* Do not add to any list */
1330 } else if (working->flags & CE_GLOB) {
1334 lastglob->next = working;
1340 lastwork->next = working;
1344 if (errline != NULL)
1349 missing_field(char *p, char *errline)
1353 errx(1, "missing field in config file:\n%s", errline);
1358 do_rotate(const struct conf_entry *ent)
1360 char dirpart[MAXPATHLEN], namepart[MAXPATHLEN];
1361 char file1[MAXPATHLEN], file2[MAXPATHLEN];
1362 char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN];
1363 char jfile1[MAXPATHLEN];
1364 int flags, numlogs_c;
1365 fk_entry free_or_keep;
1366 struct sigwork_entry *swork;
1370 free_or_keep = FREE_ENT;
1375 /* build complete name of archive directory into dirpart */
1376 if (*archdirname == '/') { /* absolute */
1377 strlcpy(dirpart, archdirname, sizeof(dirpart));
1378 } else { /* relative */
1379 /* get directory part of logfile */
1380 strlcpy(dirpart, ent->log, sizeof(dirpart));
1381 if ((p = rindex(dirpart, '/')) == NULL)
1385 strlcat(dirpart, archdirname, sizeof(dirpart));
1388 /* check if archive directory exists, if not, create it */
1389 if (lstat(dirpart, &st))
1390 createdir(ent, dirpart);
1392 /* get filename part of logfile */
1393 if ((p = rindex(ent->log, '/')) == NULL)
1394 strlcpy(namepart, ent->log, sizeof(namepart));
1396 strlcpy(namepart, p + 1, sizeof(namepart));
1398 /* name of oldest log */
1399 (void) snprintf(file1, sizeof(file1), "%s/%s.%d", dirpart,
1400 namepart, ent->numlogs);
1401 (void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1403 snprintf(jfile1, sizeof(jfile1), "%s%s", file1,
1404 BZCOMPRESS_POSTFIX);
1406 /* name of oldest log */
1407 (void) snprintf(file1, sizeof(file1), "%s.%d", ent->log,
1409 (void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1411 snprintf(jfile1, sizeof(jfile1), "%s%s", file1,
1412 BZCOMPRESS_POSTFIX);
1416 printf("\trm -f %s\n", file1);
1417 printf("\trm -f %s\n", zfile1);
1418 printf("\trm -f %s\n", jfile1);
1420 (void) unlink(file1);
1421 (void) unlink(zfile1);
1422 (void) unlink(jfile1);
1425 /* Move down log files */
1426 numlogs_c = ent->numlogs; /* copy for countdown */
1427 while (numlogs_c--) {
1429 (void) strlcpy(file2, file1, sizeof(file2));
1432 (void) snprintf(file1, sizeof(file1), "%s/%s.%d",
1433 dirpart, namepart, numlogs_c);
1435 (void) snprintf(file1, sizeof(file1), "%s.%d",
1436 ent->log, numlogs_c);
1438 (void) strlcpy(zfile1, file1, sizeof(zfile1));
1439 (void) strlcpy(zfile2, file2, sizeof(zfile2));
1440 if (lstat(file1, &st)) {
1441 (void) strlcat(zfile1, COMPRESS_POSTFIX,
1443 (void) strlcat(zfile2, COMPRESS_POSTFIX,
1445 if (lstat(zfile1, &st)) {
1446 strlcpy(zfile1, file1, sizeof(zfile1));
1447 strlcpy(zfile2, file2, sizeof(zfile2));
1448 strlcat(zfile1, BZCOMPRESS_POSTFIX,
1450 strlcat(zfile2, BZCOMPRESS_POSTFIX,
1452 if (lstat(zfile1, &st))
1457 printf("\tmv %s %s\n", zfile1, zfile2);
1459 /* XXX - Ought to be checking for failure! */
1460 (void)rename(zfile1, zfile2);
1462 change_attrs(zfile2, ent);
1465 if (ent->numlogs > 0) {
1468 * Note that savelog() may succeed with using link()
1469 * for the archtodir case, but there is no good way
1470 * of knowing if it will when doing "noaction", so
1471 * here we claim that it will have to do a copy...
1474 printf("\tcp %s %s\n", ent->log, file1);
1476 printf("\tln %s %s\n", ent->log, file1);
1478 if (!(flags & CE_BINARY)) {
1479 /* Report the trimming to the old log */
1480 log_trim(ent->log, ent);
1482 savelog(ent->log, file1);
1484 change_attrs(file1, ent);
1487 /* Create the new log file and move it into place */
1489 printf("Start new log...\n");
1493 * Save all signalling and file-compression to be done after log
1494 * files from all entries have been rotated. This way any one
1495 * process will not be sent the same signal multiple times when
1496 * multiple log files had to be rotated.
1499 if (ent->pid_file != NULL)
1500 swork = save_sigwork(ent);
1501 if (ent->numlogs > 0 && (flags & (CE_COMPACT | CE_BZCOMPACT))) {
1503 * The zipwork_entry will include a pointer to this
1504 * conf_entry, so the conf_entry should not be freed.
1506 free_or_keep = KEEP_ENT;
1507 save_zipwork(ent, swork, ent->fsize, file1);
1510 return (free_or_keep);
1514 do_sigwork(struct sigwork_entry *swork)
1516 struct sigwork_entry *nextsig;
1519 if (!(swork->sw_pidok) || swork->sw_pid == 0)
1520 return; /* no work to do... */
1523 * If nosignal (-s) was specified, then do not signal any process.
1524 * Note that a nosignal request triggers a warning message if the
1525 * rotated logfile needs to be compressed, *unless* -R was also
1526 * specified. We assume that an `-sR' request came from a process
1527 * which writes to the logfile, and as such, we assume that process
1528 * has already made sure the logfile is not presently in use. This
1529 * just sets swork->sw_pidok to a special value, and do_zipwork
1530 * will print any necessary warning(s).
1534 swork->sw_pidok = -1;
1539 * Compute the pause between consecutive signals. Use a longer
1540 * sleep time if we will be sending two signals to the same
1541 * deamon or process-group.
1544 nextsig = SLIST_NEXT(swork, sw_nextp);
1545 if (nextsig != NULL) {
1546 if (swork->sw_pid == nextsig->sw_pid)
1553 printf("\tkill -%d %d \t\t# %s\n", swork->sw_signum,
1554 (int)swork->sw_pid, swork->sw_fname);
1556 printf("\tsleep %d\n", secs);
1560 kres = kill(swork->sw_pid, swork->sw_signum);
1563 * Assume that "no such process" (ESRCH) is something
1564 * to warn about, but is not an error. Presumably the
1565 * process which writes to the rotated log file(s) is
1566 * gone, in which case we should have no problem with
1567 * compressing the rotated log file(s).
1570 swork->sw_pidok = 0;
1571 warn("can't notify %s, pid %d", swork->sw_pidtype,
1572 (int)swork->sw_pid);
1575 printf("Notified %s pid %d = %s\n", swork->sw_pidtype,
1576 (int)swork->sw_pid, swork->sw_fname);
1579 printf("Pause %d second(s) between signals\n",
1587 do_zipwork(struct zipwork_entry *zwork)
1589 const char *pgm_name, *pgm_path;
1590 int errsav, fcount, zstatus;
1592 char zresult[MAXPATHLEN];
1595 strlcpy(zresult, zwork->zw_fname, sizeof(zresult));
1596 if (zwork != NULL && zwork->zw_conf != NULL) {
1597 if (zwork->zw_conf->flags & CE_COMPACT) {
1598 pgm_path = _PATH_GZIP;
1599 strlcat(zresult, COMPRESS_POSTFIX, sizeof(zresult));
1600 } else if (zwork->zw_conf->flags & CE_BZCOMPACT) {
1601 pgm_path = _PATH_BZIP2;
1602 strlcat(zresult, BZCOMPRESS_POSTFIX, sizeof(zresult));
1605 if (pgm_path == NULL) {
1606 warnx("invalid entry for %s in do_zipwork", zwork->zw_fname);
1609 pgm_name = strrchr(pgm_path, '/');
1610 if (pgm_name == NULL)
1611 pgm_name = pgm_path;
1615 if (zwork->zw_swork != NULL && zwork->zw_swork->sw_pidok <= 0) {
1617 "log %s not compressed because daemon(s) not notified",
1619 change_attrs(zwork->zw_fname, zwork->zw_conf);
1624 printf("\t%s %s\n", pgm_name, zwork->zw_fname);
1625 change_attrs(zresult, zwork->zw_conf);
1631 while (pidzip < 0) {
1633 * The fork failed. If the failure was due to a temporary
1634 * problem, then wait a short time and try it again.
1637 warn("fork() for `%s %s'", pgm_name, zwork->zw_fname);
1638 if (errsav != EAGAIN || fcount > 5)
1639 errx(1, "Exiting...");
1645 /* The child process executes the compression command */
1646 execl(pgm_path, pgm_path, "-f", zwork->zw_fname, (char *)0);
1647 err(1, "execl(`%s -f %s')", pgm_path, zwork->zw_fname);
1650 wpid = waitpid(pidzip, &zstatus, 0);
1652 /* XXX - should this be a fatal error? */
1653 warn("%s: waitpid(%d)", pgm_path, pidzip);
1656 if (!WIFEXITED(zstatus)) {
1657 warnx("`%s -f %s' did not terminate normally", pgm_name,
1661 if (WEXITSTATUS(zstatus)) {
1662 warnx("`%s -f %s' terminated with a non-zero status (%d)",
1663 pgm_name, zwork->zw_fname, WEXITSTATUS(zstatus));
1667 /* Compression was successful, set file attributes on the result. */
1668 change_attrs(zresult, zwork->zw_conf);
1672 * Save information on any process we need to signal. Any single
1673 * process may need to be sent different signal-values for different
1674 * log files, but usually a single signal-value will cause the process
1675 * to close and re-open all of it's log files.
1677 static struct sigwork_entry *
1678 save_sigwork(const struct conf_entry *ent)
1680 struct sigwork_entry *sprev, *stmp;
1686 SLIST_FOREACH(stmp, &swhead, sw_nextp) {
1687 ndiff = strcmp(ent->pid_file, stmp->sw_fname);
1691 if (ent->sig == stmp->sw_signum)
1693 if (ent->sig > stmp->sw_signum) {
1700 if (stmp != NULL && ndiff == 0)
1703 tmpsiz = sizeof(struct sigwork_entry) + strlen(ent->pid_file) + 1;
1704 stmp = malloc(tmpsiz);
1705 set_swpid(stmp, ent);
1706 stmp->sw_signum = ent->sig;
1707 strcpy(stmp->sw_fname, ent->pid_file);
1709 SLIST_INSERT_HEAD(&swhead, stmp, sw_nextp);
1711 SLIST_INSERT_AFTER(sprev, stmp, sw_nextp);
1716 * Save information on any file we need to compress. We may see the same
1717 * file multiple times, so check the full list to avoid duplicates. The
1718 * list itself is sorted smallest-to-largest, because that's the order we
1719 * want to compress the files. If the partition is very low on disk space,
1720 * then the smallest files are the most likely to compress, and compressing
1721 * them first will free up more space for the larger files.
1723 static struct zipwork_entry *
1724 save_zipwork(const struct conf_entry *ent, const struct sigwork_entry *swork,
1725 int zsize, const char *zipfname)
1727 struct zipwork_entry *zprev, *ztmp;
1731 /* Compute the size if the caller did not know it. */
1733 zsize = sizefile(zipfname);
1737 SLIST_FOREACH(ztmp, &zwhead, zw_nextp) {
1738 ndiff = strcmp(zipfname, ztmp->zw_fname);
1741 if (zsize > ztmp->zw_fsize)
1744 if (ztmp != NULL && ndiff == 0)
1747 tmpsiz = sizeof(struct zipwork_entry) + strlen(zipfname) + 1;
1748 ztmp = malloc(tmpsiz);
1749 ztmp->zw_conf = ent;
1750 ztmp->zw_swork = swork;
1751 ztmp->zw_fsize = zsize;
1752 strcpy(ztmp->zw_fname, zipfname);
1754 SLIST_INSERT_HEAD(&zwhead, ztmp, zw_nextp);
1756 SLIST_INSERT_AFTER(zprev, ztmp, zw_nextp);
1760 /* Send a signal to the pid specified by pidfile */
1762 set_swpid(struct sigwork_entry *swork, const struct conf_entry *ent)
1765 long minok, maxok, rval;
1766 char *endp, *linep, line[BUFSIZ];
1770 swork->sw_pidok = 0;
1772 swork->sw_pidtype = "daemon";
1773 if (ent->flags & CE_SIGNALGROUP) {
1775 * If we are expected to signal a process-group when
1776 * rotating this logfile, then the value read in should
1777 * be the negative of a valid process ID.
1781 swork->sw_pidtype = "process-group";
1784 f = fopen(ent->pid_file, "r");
1786 if (errno == ENOENT && enforcepid == 0) {
1788 * Warn if the PID file doesn't exist, but do
1789 * not consider it an error. Most likely it
1790 * means the process has been terminated,
1791 * so it should be safe to rotate any log
1792 * files that the process would have been using.
1794 swork->sw_pidok = 1;
1795 warnx("pid file doesn't exist: %s", ent->pid_file);
1797 warn("can't open pid file: %s", ent->pid_file);
1801 if (fgets(line, BUFSIZ, f) == NULL) {
1803 * Warn if the PID file is empty, but do not consider
1804 * it an error. Most likely it means the process has
1805 * has terminated, so it should be safe to rotate any
1806 * log files that the process would have been using.
1808 if (feof(f) && enforcepid == 0) {
1809 swork->sw_pidok = 1;
1810 warnx("pid file is empty: %s", ent->pid_file);
1812 warn("can't read from pid file: %s", ent->pid_file);
1820 while (*linep == ' ')
1822 rval = strtol(linep, &endp, 10);
1823 if (*endp != '\0' && !isspacech(*endp)) {
1824 warnx("pid file does not start with a valid number: %s",
1826 } else if (rval < minok || rval > maxok) {
1827 warnx("bad value '%ld' for process number in %s",
1828 rval, ent->pid_file);
1830 warnx("\t(expecting value between %ld and %ld)",
1833 swork->sw_pidok = 1;
1834 swork->sw_pid = rval;
1840 /* Log the fact that the logs were turned over */
1842 log_trim(const char *logname, const struct conf_entry *log_ent)
1847 if ((f = fopen(logname, "a")) == NULL)
1850 if (log_ent->def_cfg)
1851 xtra = " using <default> rule";
1852 if (log_ent->firstcreate)
1853 fprintf(f, "%s %s newsyslog[%d]: logfile first created%s\n",
1854 daytime, hostname, (int) getpid(), xtra);
1855 else if (log_ent->r_reason != NULL)
1856 fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s%s\n",
1857 daytime, hostname, (int) getpid(), log_ent->r_reason, xtra);
1859 fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s\n",
1860 daytime, hostname, (int) getpid(), xtra);
1861 if (fclose(f) == EOF)
1862 err(1, "log_trim: fclose");
1866 /* Return size in kilobytes of a file */
1868 sizefile(const char *file)
1872 if (stat(file, &sb) < 0)
1874 return (kbytes(dbtob(sb.st_blocks)));
1877 /* Return the age of old log file (file.0) */
1879 age_old_log(char *file)
1883 char tmp[MAXPATHLEN + sizeof(".0") + sizeof(COMPRESS_POSTFIX) +
1884 sizeof(BZCOMPRESS_POSTFIX) + 1];
1889 /* build name of archive directory into tmp */
1890 if (*archdirname == '/') { /* absolute */
1891 strlcpy(tmp, archdirname, sizeof(tmp));
1892 } else { /* relative */
1893 /* get directory part of logfile */
1894 strlcpy(tmp, file, sizeof(tmp));
1895 if ((p = rindex(tmp, '/')) == NULL)
1899 strlcat(tmp, archdirname, sizeof(tmp));
1902 strlcat(tmp, "/", sizeof(tmp));
1904 /* get filename part of logfile */
1905 if ((p = rindex(file, '/')) == NULL)
1906 strlcat(tmp, file, sizeof(tmp));
1908 strlcat(tmp, p + 1, sizeof(tmp));
1910 (void) strlcpy(tmp, file, sizeof(tmp));
1913 strlcat(tmp, ".0", sizeof(tmp));
1914 if (stat(tmp, &sb) < 0) {
1916 * A plain '.0' file does not exist. Try again, first
1917 * with the added suffix of '.gz', then with an added
1918 * suffix of '.bz2' instead of '.gz'.
1920 endp = strchr(tmp, '\0');
1921 strlcat(tmp, COMPRESS_POSTFIX, sizeof(tmp));
1922 if (stat(tmp, &sb) < 0) {
1923 *endp = '\0'; /* Remove .gz */
1924 strlcat(tmp, BZCOMPRESS_POSTFIX, sizeof(tmp));
1925 if (stat(tmp, &sb) < 0)
1929 return ((int)(ptimeget_secs(timenow) - sb.st_mtime + 1800) / 3600);
1932 /* Skip Over Blanks */
1936 while (p && *p && isspace(*p))
1941 /* Skip Over Non-Blanks */
1945 while (p && *p && !isspace(*p))
1950 /* Check if string is actually a number */
1952 isnumberstr(const char *string)
1955 if (!isdigitch(*string++))
1962 * Save the active log file under a new name. A link to the new name
1963 * is the quick-and-easy way to do this. If that fails (which it will
1964 * if the destination is on another partition), then make a copy of
1965 * the file to the new location.
1968 savelog(char *from, char *to)
1973 res = link(from, to);
1977 if ((src = fopen(from, "r")) == NULL)
1978 err(1, "can't fopen %s for reading", from);
1979 if ((dst = fopen(to, "w")) == NULL)
1980 err(1, "can't fopen %s for writing", to);
1982 while ((c = getc(src)) != EOF) {
1983 if ((putc(c, dst)) == EOF)
1984 err(1, "error writing to %s", to);
1988 err(1, "error reading from %s", from);
1989 if ((fclose(src)) != 0)
1990 err(1, "can't fclose %s", to);
1991 if ((fclose(dst)) != 0)
1992 err(1, "can't fclose %s", from);
1995 /* create one or more directory components of a path */
1997 createdir(const struct conf_entry *ent, char *dirpart)
2001 char mkdirpath[MAXPATHLEN];
2009 if (*s != '/' && *s != '\0')
2012 res = lstat(mkdirpath, &st);
2015 printf("\tmkdir %s\n", mkdirpath);
2017 res = mkdir(mkdirpath, 0755);
2019 err(1, "Error on mkdir(\"%s\") for -a",
2027 if (ent->firstcreate)
2028 printf("Created directory '%s' for new %s\n",
2031 printf("Created directory '%s' for -a\n", dirpart);
2036 * Create a new log file, destroying any currently-existing version
2037 * of the log file in the process. If the caller wants a backup copy
2038 * of the file to exist, they should call 'link(logfile,logbackup)'
2039 * before calling this routine.
2042 createlog(const struct conf_entry *ent)
2046 char *realfile, *slash, tempfile[MAXPATHLEN];
2049 realfile = ent->log;
2052 * If this log file is being created for the first time (-C option),
2053 * then it may also be true that the parent directory does not exist
2054 * yet. Check, and create that directory if it is missing.
2056 if (ent->firstcreate) {
2057 strlcpy(tempfile, realfile, sizeof(tempfile));
2058 slash = strrchr(tempfile, '/');
2059 if (slash != NULL) {
2061 failed = stat(tempfile, &st);
2062 if (failed && errno != ENOENT)
2063 err(1, "Error on stat(%s)", tempfile);
2065 createdir(ent, tempfile);
2066 else if (!S_ISDIR(st.st_mode))
2067 errx(1, "%s exists but is not a directory",
2073 * First create an unused filename, so it can be chown'ed and
2074 * chmod'ed before it is moved into the real location. mkstemp
2075 * will create the file mode=600 & owned by us. Note that all
2076 * temp files will have a suffix of '.z<something>'.
2078 strlcpy(tempfile, realfile, sizeof(tempfile));
2079 strlcat(tempfile, ".zXXXXXX", sizeof(tempfile));
2081 printf("\tmktemp %s\n", tempfile);
2083 fd = mkstemp(tempfile);
2085 err(1, "can't mkstemp logfile %s", tempfile);
2088 * Add status message to what will become the new log file.
2090 if (!(ent->flags & CE_BINARY)) {
2091 if (log_trim(tempfile, ent))
2092 err(1, "can't add status message to log");
2096 /* Change the owner/group, if we are supposed to */
2097 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2099 printf("\tchown %u:%u %s\n", ent->uid, ent->gid,
2102 failed = fchown(fd, ent->uid, ent->gid);
2104 err(1, "can't fchown temp file %s", tempfile);
2108 /* Turn on NODUMP if it was requested in the config-file. */
2109 if (ent->flags & CE_NODUMP) {
2111 printf("\tchflags nodump %s\n", tempfile);
2113 failed = fchflags(fd, UF_NODUMP);
2115 warn("log_trim: fchflags(NODUMP)");
2121 * Note that if the real logfile still exists, and if the call
2122 * to rename() fails, then "neither the old file nor the new
2123 * file shall be changed or created" (to quote the standard).
2124 * If the call succeeds, then the file will be replaced without
2125 * any window where some other process might find that the file
2127 * XXX - ? It may be that for some error conditions, we could
2128 * retry by first removing the realfile and then renaming.
2131 printf("\tchmod %o %s\n", ent->permissions, tempfile);
2132 printf("\tmv %s %s\n", tempfile, realfile);
2134 failed = fchmod(fd, ent->permissions);
2136 err(1, "can't fchmod temp file '%s'", tempfile);
2137 failed = rename(tempfile, realfile);
2139 err(1, "can't mv %s to %s", tempfile, realfile);
2147 * Change the attributes of a given filename to what was specified in
2148 * the newsyslog.conf entry. This routine is only called for files
2149 * that newsyslog expects that it has created, and thus it is a fatal
2150 * error if this routine finds that the file does not exist.
2153 change_attrs(const char *fname, const struct conf_entry *ent)
2158 printf("\tchmod %o %s\n", ent->permissions, fname);
2160 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
2161 printf("\tchown %u:%u %s\n",
2162 ent->uid, ent->gid, fname);
2164 if (ent->flags & CE_NODUMP)
2165 printf("\tchflags nodump %s\n", fname);
2169 failed = chmod(fname, ent->permissions);
2172 err(1, "chmod(%s) in change_attrs", fname);
2173 warn("change_attrs couldn't chmod(%s)", fname);
2176 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2177 failed = chown(fname, ent->uid, ent->gid);
2179 warn("can't chown %s", fname);
2182 if (ent->flags & CE_NODUMP) {
2183 failed = chflags(fname, UF_NODUMP);
2185 warn("can't chflags %s NODUMP", fname);