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 force = 0; /* Force the trim no matter what */
171 int rotatereq = 0; /* -R = Always rotate the file(s) as given */
172 /* on the command (this also requires */
173 /* that a list of files *are* given on */
174 /* the run command). */
175 char *requestor; /* The name given on a -R request */
176 char *archdirname; /* Directory path to old logfiles archive */
177 char *destdir = NULL; /* Directory to treat at root for logs */
178 const char *conf; /* Configuration file to use */
180 struct ptime_data *dbg_timenow; /* A "timenow" value set via -D option */
181 struct ptime_data *timenow; /* The time to use for checking at-fields */
183 #define DAYTIME_LEN 16
184 char daytime[DAYTIME_LEN]; /* The current time in human readable form,
185 * used for rotation-tracking messages. */
186 char hostname[MAXHOSTNAMELEN]; /* hostname */
188 static struct conf_entry *get_worklist(char **files);
189 static void parse_file(FILE *cf, const char *cfname, struct conf_entry **work_p,
190 struct conf_entry **glob_p, struct conf_entry **defconf_p);
191 static char *sob(char *p);
192 static char *son(char *p);
193 static int isnumberstr(const char *);
194 static char *missing_field(char *p, char *errline);
195 static void change_attrs(const char *, const struct conf_entry *);
196 static fk_entry do_entry(struct conf_entry *);
197 static fk_entry do_rotate(const struct conf_entry *);
198 static void do_sigwork(struct sigwork_entry *);
199 static void do_zipwork(struct zipwork_entry *);
200 static struct sigwork_entry *
201 save_sigwork(const struct conf_entry *);
202 static struct zipwork_entry *
203 save_zipwork(const struct conf_entry *, const struct
204 sigwork_entry *, int, const char *);
205 static void set_swpid(struct sigwork_entry *, const struct conf_entry *);
206 static int sizefile(const char *);
207 static void expand_globs(struct conf_entry **work_p,
208 struct conf_entry **glob_p);
209 static void free_clist(struct conf_entry **firstent);
210 static void free_entry(struct conf_entry *ent);
211 static struct conf_entry *init_entry(const char *fname,
212 struct conf_entry *src_entry);
213 static void parse_args(int argc, char **argv);
214 static int parse_doption(const char *doption);
215 static void usage(void);
216 static int log_trim(const char *logname, const struct conf_entry *log_ent);
217 static int age_old_log(char *file);
218 static void savelog(char *from, char *to);
219 static void createdir(const struct conf_entry *ent, char *dirpart);
220 static void createlog(const struct conf_entry *ent);
223 * All the following take a parameter of 'int', but expect values in the
224 * range of unsigned char. Define wrappers which take values of type 'char',
225 * whether signed or unsigned, and ensure they end up in the right range.
227 #define isdigitch(Anychar) isdigit((u_char)(Anychar))
228 #define isprintch(Anychar) isprint((u_char)(Anychar))
229 #define isspacech(Anychar) isspace((u_char)(Anychar))
230 #define tolowerch(Anychar) tolower((u_char)(Anychar))
233 main(int argc, char **argv)
235 fk_entry free_or_keep;
236 struct conf_entry *p, *q;
237 struct sigwork_entry *stmp;
238 struct zipwork_entry *ztmp;
243 parse_args(argc, argv);
247 if (needroot && getuid() && geteuid())
248 errx(1, "must have root privs");
249 p = q = get_worklist(argv);
252 * Rotate all the files which need to be rotated. Note that
253 * some users have *hundreds* of entries in newsyslog.conf!
256 free_or_keep = do_entry(p);
258 if (free_or_keep == FREE_ENT)
264 * Send signals to any processes which need a signal to tell
265 * them to close and re-open the log file(s) we have rotated.
266 * Note that zipwork_entries include pointers to these
267 * sigwork_entry's, so we can not free the entries here.
269 if (!SLIST_EMPTY(&swhead)) {
270 if (noaction || verbose)
271 printf("Signal all daemon process(es)...\n");
272 SLIST_FOREACH(stmp, &swhead, sw_nextp)
275 printf("\tsleep 10\n");
278 printf("Pause 10 seconds to allow daemon(s)"
279 " to close log file(s)\n");
284 * Compress all files that we're expected to compress, now
285 * that all processes should have closed the files which
288 if (!SLIST_EMPTY(&zwhead)) {
289 if (noaction || verbose)
290 printf("Compress all rotated log file(s)...\n");
291 while (!SLIST_EMPTY(&zwhead)) {
292 ztmp = SLIST_FIRST(&zwhead);
294 SLIST_REMOVE_HEAD(&zwhead, zw_nextp);
298 /* Now free all the sigwork entries. */
299 while (!SLIST_EMPTY(&swhead)) {
300 stmp = SLIST_FIRST(&swhead);
301 SLIST_REMOVE_HEAD(&swhead, sw_nextp);
305 while (wait(NULL) > 0 || errno == EINTR)
310 static struct conf_entry *
311 init_entry(const char *fname, struct conf_entry *src_entry)
313 struct conf_entry *tempwork;
316 printf("\t--> [creating entry for %s]\n", fname);
318 tempwork = malloc(sizeof(struct conf_entry));
319 if (tempwork == NULL)
320 err(1, "malloc of conf_entry for %s", fname);
322 if (destdir == NULL || fname[0] != '/')
323 tempwork->log = strdup(fname);
325 asprintf(&tempwork->log, "%s%s", destdir, fname);
326 if (tempwork->log == NULL)
327 err(1, "strdup for %s", fname);
329 if (src_entry != NULL) {
330 tempwork->pid_file = NULL;
331 if (src_entry->pid_file)
332 tempwork->pid_file = strdup(src_entry->pid_file);
333 tempwork->r_reason = NULL;
334 tempwork->firstcreate = 0;
335 tempwork->rotate = 0;
336 tempwork->fsize = -1;
337 tempwork->uid = src_entry->uid;
338 tempwork->gid = src_entry->gid;
339 tempwork->numlogs = src_entry->numlogs;
340 tempwork->trsize = src_entry->trsize;
341 tempwork->hours = src_entry->hours;
342 tempwork->trim_at = NULL;
343 if (src_entry->trim_at != NULL)
344 tempwork->trim_at = ptime_init(src_entry->trim_at);
345 tempwork->permissions = src_entry->permissions;
346 tempwork->flags = src_entry->flags;
347 tempwork->sig = src_entry->sig;
348 tempwork->def_cfg = src_entry->def_cfg;
350 /* Initialize as a "do-nothing" entry */
351 tempwork->pid_file = NULL;
352 tempwork->r_reason = NULL;
353 tempwork->firstcreate = 0;
354 tempwork->rotate = 0;
355 tempwork->fsize = -1;
356 tempwork->uid = (uid_t)-1;
357 tempwork->gid = (gid_t)-1;
358 tempwork->numlogs = 1;
359 tempwork->trsize = -1;
360 tempwork->hours = -1;
361 tempwork->trim_at = NULL;
362 tempwork->permissions = 0;
364 tempwork->sig = SIGHUP;
365 tempwork->def_cfg = 0;
367 tempwork->next = NULL;
373 free_entry(struct conf_entry *ent)
379 if (ent->log != NULL) {
381 printf("\t--> [freeing entry for %s]\n", ent->log);
386 if (ent->pid_file != NULL) {
388 ent->pid_file = NULL;
391 if (ent->r_reason != NULL) {
393 ent->r_reason = NULL;
396 if (ent->trim_at != NULL) {
397 ptime_free(ent->trim_at);
405 free_clist(struct conf_entry **firstent)
407 struct conf_entry *ent, *nextent;
409 if (firstent == NULL)
410 return; /* There is nothing to do. */
423 do_entry(struct conf_entry * ent)
425 #define REASON_MAX 80
427 fk_entry free_or_keep;
429 char temp_reason[REASON_MAX];
431 free_or_keep = FREE_ENT;
433 if (ent->flags & CE_COMPACT)
434 printf("%s <%dZ>: ", ent->log, ent->numlogs);
435 else if (ent->flags & CE_BZCOMPACT)
436 printf("%s <%dJ>: ", ent->log, ent->numlogs);
438 printf("%s <%d>: ", ent->log, ent->numlogs);
440 ent->fsize = sizefile(ent->log);
441 modtime = age_old_log(ent->log);
443 ent->firstcreate = 0;
444 if (ent->fsize < 0) {
446 * If either the C flag or the -C option was specified,
447 * and if we won't be creating the file, then have the
448 * verbose message include a hint as to why the file
449 * will not be created.
451 temp_reason[0] = '\0';
453 ent->firstcreate = 1;
454 else if ((ent->flags & CE_CREATE) && createlogs)
455 ent->firstcreate = 1;
456 else if (ent->flags & CE_CREATE)
457 strlcpy(temp_reason, " (no -C option)", REASON_MAX);
459 strlcpy(temp_reason, " (no C flag)", REASON_MAX);
461 if (ent->firstcreate) {
463 printf("does not exist -> will create.\n");
465 } else if (verbose) {
466 printf("does not exist, skipped%s.\n", temp_reason);
469 if (ent->flags & CE_TRIMAT && !force && !rotatereq) {
470 diffsecs = ptimeget_diff(timenow, ent->trim_at);
471 if (diffsecs < 0.0) {
472 /* trim_at is some time in the future. */
474 ptime_adjust4dst(ent->trim_at,
476 printf("--> will trim at %s",
477 ptimeget_ctime(ent->trim_at));
479 return (free_or_keep);
480 } else if (diffsecs >= 3600.0) {
482 * trim_at is more than an hour in the past,
483 * so find the next valid trim_at time, and
484 * tell the user what that will be.
486 if (verbose && dbg_at_times)
487 printf("\n\t--> prev trim at %s\t",
488 ptimeget_ctime(ent->trim_at));
490 ptimeset_nxtime(ent->trim_at);
491 printf("--> will trim at %s",
492 ptimeget_ctime(ent->trim_at));
494 return (free_or_keep);
495 } else if (verbose && noaction && dbg_at_times) {
497 * If we are just debugging at-times, then
498 * a detailed message is helpful. Also
499 * skip "doing" any commands, since they
500 * would all be turned off by no-action.
502 printf("\n\t--> timematch at %s",
503 ptimeget_ctime(ent->trim_at));
504 return (free_or_keep);
505 } else if (verbose && ent->hours <= 0) {
506 printf("--> time is up\n");
509 if (verbose && (ent->trsize > 0))
510 printf("size (Kb): %d [%d] ", ent->fsize, ent->trsize);
511 if (verbose && (ent->hours > 0))
512 printf(" age (hr): %d [%d] ", modtime, ent->hours);
515 * Figure out if this logfile needs to be rotated.
517 temp_reason[0] = '\0';
520 snprintf(temp_reason, REASON_MAX, " due to -R from %s",
524 snprintf(temp_reason, REASON_MAX, " due to -F request");
525 } else if ((ent->trsize > 0) && (ent->fsize >= ent->trsize)) {
527 snprintf(temp_reason, REASON_MAX, " due to size>%dK",
529 } else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) {
531 } else if ((ent->hours > 0) && ((modtime >= ent->hours) ||
537 * If the file needs to be rotated, then rotate it.
539 if (ent->rotate && !norotate) {
540 if (temp_reason[0] != '\0')
541 ent->r_reason = strdup(temp_reason);
543 printf("--> trimming log....\n");
544 if (noaction && !verbose) {
545 if (ent->flags & CE_COMPACT)
546 printf("%s <%dZ>: trimming\n",
547 ent->log, ent->numlogs);
548 else if (ent->flags & CE_BZCOMPACT)
549 printf("%s <%dJ>: trimming\n",
550 ent->log, ent->numlogs);
552 printf("%s <%d>: trimming\n",
553 ent->log, ent->numlogs);
555 free_or_keep = do_rotate(ent);
558 printf("--> skipping\n");
561 return (free_or_keep);
566 parse_args(int argc, char **argv)
571 timenow = ptime_init(NULL);
572 ptimeset_time(timenow, time(NULL));
573 strlcpy(daytime, ptimeget_ctime(timenow) + 4, DAYTIME_LEN);
575 /* Let's get our hostname */
576 (void)gethostname(hostname, sizeof(hostname));
578 /* Truncate domain */
579 if ((p = strchr(hostname, '.')) != NULL)
582 /* Parse command line options. */
583 while ((ch = getopt(argc, argv, "a:d:f:nrsvCD:FNR:")) != -1)
587 archdirname = optarg;
608 /* Useful for things like rc.diskless... */
613 * Set some debugging option. The specific option
614 * depends on the value of optarg. These options
615 * may come and go without notice or documentation.
617 if (parse_doption(optarg))
629 requestor = strdup(optarg);
631 case 'm': /* Used by OpenBSD for "monitor mode" */
637 if (force && norotate) {
638 warnx("Only one of -F and -N may be specified.");
644 if (optind == argc) {
645 warnx("At least one filename must be given when -R is specified.");
649 /* Make sure "requestor" value is safe for a syslog message. */
650 for (p = requestor; *p != '\0'; p++) {
651 if (!isprintch(*p) && (*p != '\t'))
658 * Note that the 'daytime' variable is not changed.
659 * That is only used in messages that track when a
660 * logfile is rotated, and if a file *is* rotated,
661 * then it will still rotated at the "real now" time.
664 timenow = dbg_timenow;
665 fprintf(stderr, "Debug: Running as if TimeNow is %s",
666 ptimeget_ctime(dbg_timenow));
672 * These debugging options are mainly meant for developer use, such
673 * as writing regression-tests. They would not be needed by users
674 * during normal operation of newsyslog...
677 parse_doption(const char *doption)
679 const char TN[] = "TN=";
682 if (strncmp(doption, TN, sizeof(TN) - 1) == 0) {
684 * The "TimeNow" debugging option. This might be off
685 * by an hour when crossing a timezone change.
687 dbg_timenow = ptime_init(NULL);
688 res = ptime_relparse(dbg_timenow, PTM_PARSE_ISO8601,
689 time(NULL), doption + sizeof(TN) - 1);
691 warnx("Non-existent time specified on -D %s", doption);
692 return (0); /* failure */
693 } else if (res < 0) {
694 warnx("Malformed time given on -D %s", doption);
695 return (0); /* failure */
697 return (1); /* successfully parsed */
701 if (strcmp(doption, "ats") == 0) {
703 return (1); /* successfully parsed */
706 /* XXX - This check could probably be dropped. */
707 if ((strcmp(doption, "neworder") == 0) || (strcmp(doption, "oldorder")
709 warnx("NOTE: newsyslog always uses 'neworder'.");
710 return (1); /* successfully parsed */
713 warnx("Unknown -D (debug) option: '%s'", doption);
714 return (0); /* failure */
722 "usage: newsyslog [-CFNnrsv] [-a directory] [-d directory] [-f config-file]\n"
723 " [ [-R requestor] filename ... ]\n");
728 * Parse a configuration file and return a linked list of all the logs
729 * which should be processed.
731 static struct conf_entry *
732 get_worklist(char **files)
737 struct conf_entry *defconf, *dupent, *ent, *firstnew;
738 struct conf_entry *globlist, *lastnew, *worklist;
741 defconf = globlist = worklist = NULL;
747 if (strcmp(fname, "-") != 0)
748 f = fopen(fname, "r");
756 parse_file(f, fname, &worklist, &globlist, &defconf);
760 * All config-file information has been read in and turned into
761 * a worklist and a globlist. If there were no specific files
762 * given on the run command, then the only thing left to do is to
763 * call a routine which finds all files matched by the globlist
764 * and adds them to the worklist. Then return the worklist.
766 if (*files == NULL) {
767 expand_globs(&worklist, &globlist);
768 free_clist(&globlist);
776 * If newsyslog was given a specific list of files to process,
777 * it may be that some of those files were not listed in any
778 * config file. Those unlisted files should get the default
779 * rotation action. First, create the default-rotation action
780 * if none was found in a system config file.
782 if (defconf == NULL) {
783 defconf = init_entry(DEFAULT_MARKER, NULL);
784 defconf->numlogs = 3;
785 defconf->trsize = 50;
786 defconf->permissions = S_IRUSR|S_IWUSR;
790 * If newsyslog was run with a list of specific filenames,
791 * then create a new worklist which has only those files in
792 * it, picking up the rotation-rules for those files from
793 * the original worklist.
795 * XXX - Note that this will copy multiple rules for a single
796 * logfile, if multiple entries are an exact match for
797 * that file. That matches the historic behavior, but do
798 * we want to continue to allow it? If so, it should
799 * probably be handled more intelligently.
801 firstnew = lastnew = NULL;
802 for (given = files; *given; ++given) {
804 * First try to find exact-matches for this given file.
807 for (ent = worklist; ent; ent = ent->next) {
808 if (strcmp(ent->log, *given) == 0) {
810 dupent = init_entry(*given, ent);
814 lastnew->next = dupent;
820 printf("\t+ Matched entry %s\n", *given);
825 * There was no exact-match for this given file, so look
826 * for a "glob" entry which does match.
829 if (verbose > 2 && globlist != NULL)
830 printf("\t+ Checking globs for %s\n", *given);
831 for (ent = globlist; ent; ent = ent->next) {
832 fnres = fnmatch(ent->log, *given, FNM_PATHNAME);
834 printf("\t+ = %d for pattern %s\n", fnres,
838 dupent = init_entry(*given, ent);
842 lastnew->next = dupent;
844 /* This new entry is not a glob! */
845 dupent->flags &= ~CE_GLOB;
846 /* Only allow a match to one glob-entry */
852 printf("\t+ Matched %s via %s\n", *given,
858 * This given file was not found in any config file, so
859 * add a worklist item based on the default entry.
862 printf("\t+ No entry matched %s (will use %s)\n",
863 *given, DEFAULT_MARKER);
864 dupent = init_entry(*given, defconf);
868 lastnew->next = dupent;
869 /* Mark that it was *not* found in a config file */
875 * Free all the entries in the original work list, the list of
876 * glob entries, and the default entry.
878 free_clist(&worklist);
879 free_clist(&globlist);
882 /* And finally, return a worklist which matches the given files. */
887 * Expand the list of entries with filename patterns, and add all files
888 * which match those glob-entries onto the worklist.
891 expand_globs(struct conf_entry **work_p, struct conf_entry **glob_p)
896 struct conf_entry *dupent, *ent, *firstmatch, *globent;
897 struct conf_entry *lastmatch;
901 if ((glob_p == NULL) || (*glob_p == NULL))
902 return; /* There is nothing to do. */
905 * The worklist contains all fully-specified (non-GLOB) names.
907 * Now expand the list of filename-pattern (GLOB) entries into
908 * a second list, which (by definition) will only match files
909 * that already exist. Do not add a glob-related entry for any
910 * file which already exists in the fully-specified list.
912 firstmatch = lastmatch = NULL;
913 for (globent = *glob_p; globent; globent = globent->next) {
915 gres = glob(globent->log, GLOB_NOCHECK, NULL, &pglob);
917 warn("cannot expand pattern (%d): %s", gres,
923 printf("\t+ Expanding pattern %s\n", globent->log);
924 for (i = 0; i < pglob.gl_matchc; i++) {
925 mfname = pglob.gl_pathv[i];
927 /* See if this file already has a specific entry. */
929 for (ent = *work_p; ent; ent = ent->next) {
930 if (strcmp(mfname, ent->log) == 0) {
938 /* Make sure the named matched is a file. */
939 gres = lstat(mfname, &st_fm);
941 /* Error on a file that glob() matched?!? */
942 warn("Skipping %s - lstat() error", mfname);
945 if (!S_ISREG(st_fm.st_mode)) {
946 /* We only rotate files! */
948 printf("\t+ . skipping %s (!file)\n",
954 printf("\t+ . add file %s\n", mfname);
955 dupent = init_entry(mfname, globent);
959 lastmatch->next = dupent;
961 /* This new entry is not a glob! */
962 dupent->flags &= ~CE_GLOB;
966 printf("\t+ Done with pattern %s\n", globent->log);
969 /* Add the list of matched files to the end of the worklist. */
971 *work_p = firstmatch;
976 ent->next = firstmatch;
982 * Parse a configuration file and update a linked list of all the logs to
986 parse_file(FILE *cf, const char *cfname, struct conf_entry **work_p,
987 struct conf_entry **glob_p, struct conf_entry **defconf_p)
989 char line[BUFSIZ], *parse, *q;
990 char *cp, *errline, *group;
991 struct conf_entry *lastglob, *lastwork, *working;
994 int eol, ptm_opts, res, special;
997 * XXX - for now, assume that only one config file will be read,
998 * ie, this routine is only called one time.
1000 lastglob = lastwork = NULL;
1003 while (fgets(line, BUFSIZ, cf)) {
1004 if ((line[0] == '\n') || (line[0] == '#') ||
1005 (strlen(line) == 0))
1007 if (errline != NULL)
1009 errline = strdup(line);
1010 for (cp = line + 1; *cp != '\0'; cp++) {
1013 if (*(cp - 1) == '\\') {
1022 q = parse = missing_field(sob(line), errline);
1025 errx(1, "malformed line (missing fields):\n%s",
1030 * Allow people to set debug options via the config file.
1031 * (NOTE: debug optons are undocumented, and may disappear
1032 * at any time, etc).
1034 if (strcasecmp(DEBUG_MARKER, q) == 0) {
1035 q = parse = missing_field(sob(++parse), errline);
1038 warnx("debug line specifies no option:\n%s",
1048 working = init_entry(q, NULL);
1049 if (strcasecmp(DEFAULT_MARKER, q) == 0) {
1051 if (defconf_p == NULL) {
1052 warnx("Ignoring entry for %s in %s!", q,
1054 free_entry(working);
1056 } else if (*defconf_p != NULL) {
1057 warnx("Ignoring duplicate entry for %s!", q);
1058 free_entry(working);
1061 *defconf_p = working;
1064 q = parse = missing_field(sob(++parse), errline);
1067 errx(1, "malformed line (missing fields):\n%s",
1070 if ((group = strchr(q, ':')) != NULL ||
1071 (group = strrchr(q, '.')) != NULL) {
1074 if (!(isnumberstr(q))) {
1075 if ((pwd = getpwnam(q)) == NULL)
1077 "error in config file; unknown user:\n%s",
1079 working->uid = pwd->pw_uid;
1081 working->uid = atoi(q);
1083 working->uid = (uid_t)-1;
1087 if (!(isnumberstr(q))) {
1088 if ((grp = getgrnam(q)) == NULL)
1090 "error in config file; unknown group:\n%s",
1092 working->gid = grp->gr_gid;
1094 working->gid = atoi(q);
1096 working->gid = (gid_t)-1;
1098 q = parse = missing_field(sob(++parse), errline);
1101 errx(1, "malformed line (missing fields):\n%s",
1105 working->uid = (uid_t)-1;
1106 working->gid = (gid_t)-1;
1109 if (!sscanf(q, "%o", &working->permissions))
1110 errx(1, "error in config file; bad permissions:\n%s",
1113 q = parse = missing_field(sob(++parse), errline);
1116 errx(1, "malformed line (missing fields):\n%s",
1119 if (!sscanf(q, "%d", &working->numlogs) || working->numlogs < 0)
1120 errx(1, "error in config file; bad value for count of logs to save:\n%s",
1123 q = parse = missing_field(sob(++parse), errline);
1126 errx(1, "malformed line (missing fields):\n%s",
1130 working->trsize = atoi(q);
1131 else if (strcmp(q, "*") == 0)
1132 working->trsize = -1;
1134 warnx("Invalid value of '%s' for 'size' in line:\n%s",
1136 working->trsize = -1;
1140 q = parse = missing_field(sob(++parse), errline);
1148 ul = strtoul(q, &ep, 10);
1151 else if (*ep == '*')
1152 working->hours = -1;
1153 else if (ul > INT_MAX)
1154 errx(1, "interval is too large:\n%s", errline);
1156 working->hours = ul;
1158 if (*ep == '\0' || strcmp(ep, "*") == 0)
1160 if (*ep != '@' && *ep != '$')
1161 errx(1, "malformed interval/at:\n%s", errline);
1163 working->flags |= CE_TRIMAT;
1164 working->trim_at = ptime_init(NULL);
1165 ptm_opts = PTM_PARSE_ISO8601;
1167 ptm_opts = PTM_PARSE_DWM;
1168 ptm_opts |= PTM_PARSE_MATCHDOM;
1169 res = ptime_relparse(working->trim_at, ptm_opts,
1170 ptimeget_secs(timenow), ep + 1);
1172 errx(1, "nonexistent time for 'at' value:\n%s",
1175 errx(1, "malformed 'at' value:\n%s", errline);
1182 q = parse = sob(++parse); /* Optional field */
1189 for (; q && *q && !isspacech(*q); q++) {
1190 switch (tolowerch(*q)) {
1192 working->flags |= CE_BINARY;
1196 * XXX - Ick! Ugly! Remove ASAP!
1197 * We want `c' and `C' for "create". But we
1198 * will temporarily treat `c' as `g', because
1199 * FreeBSD releases <= 4.8 have a typo of
1200 * checking ('G' || 'c') for CE_GLOB.
1203 warnx("Assuming 'g' for 'c' in flags for line:\n%s",
1205 warnx("The 'c' flag will eventually mean 'CREATE'");
1206 working->flags |= CE_GLOB;
1209 working->flags |= CE_CREATE;
1212 working->flags |= CE_NODUMP;
1215 working->flags |= CE_GLOB;
1218 working->flags |= CE_BZCOMPACT;
1221 working->flags |= CE_NOSIGNAL;
1224 working->flags |= CE_SIGNALGROUP;
1227 /* Depreciated flag - keep for compatibility purposes */
1230 working->flags |= CE_COMPACT;
1234 case 'f': /* Used by OpenBSD for "CE_FOLLOW" */
1235 case 'm': /* Used by OpenBSD for "CE_MONITOR" */
1236 case 'p': /* Used by NetBSD for "CE_PLAIN0" */
1238 errx(1, "illegal flag in config file -- %c",
1246 q = parse = sob(++parse); /* Optional field */
1253 working->pid_file = NULL;
1256 working->pid_file = strdup(q);
1257 else if (isdigit(*q))
1261 "illegal pid file or signal number in config file:\n%s",
1267 q = parse = sob(++parse); /* Optional field */
1268 *(parse = son(parse)) = '\0';
1271 working->sig = SIGHUP;
1275 working->sig = atoi(q);
1279 "illegal signal number in config file:\n%s",
1282 if (working->sig < 1 || working->sig >= NSIG)
1287 * Finish figuring out what pid-file to use (if any) in
1288 * later processing if this logfile needs to be rotated.
1290 if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) {
1292 * This config-entry specified 'n' for nosignal,
1293 * see if it also specified an explicit pid_file.
1294 * This would be a pretty pointless combination.
1296 if (working->pid_file != NULL) {
1297 warnx("Ignoring '%s' because flag 'n' was specified in line:\n%s",
1298 working->pid_file, errline);
1299 free(working->pid_file);
1300 working->pid_file = NULL;
1302 } else if (working->pid_file == NULL) {
1304 * This entry did not specify the 'n' flag, which
1305 * means it should signal syslogd unless it had
1306 * specified some other pid-file (and obviously the
1307 * syslog pid-file will not be for a process-group).
1308 * Also, we should only try to notify syslog if we
1311 if (working->flags & CE_SIGNALGROUP) {
1312 warnx("Ignoring flag 'U' in line:\n%s",
1314 working->flags &= ~CE_SIGNALGROUP;
1317 working->pid_file = strdup(_PATH_SYSLOGPID);
1321 * Add this entry to the appropriate list of entries, unless
1322 * it was some kind of special entry (eg: <default>).
1325 ; /* Do not add to any list */
1326 } else if (working->flags & CE_GLOB) {
1330 lastglob->next = working;
1336 lastwork->next = working;
1340 if (errline != NULL)
1345 missing_field(char *p, char *errline)
1349 errx(1, "missing field in config file:\n%s", errline);
1354 do_rotate(const struct conf_entry *ent)
1356 char dirpart[MAXPATHLEN], namepart[MAXPATHLEN];
1357 char file1[MAXPATHLEN], file2[MAXPATHLEN];
1358 char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN];
1359 char jfile1[MAXPATHLEN];
1360 int flags, numlogs_c;
1361 fk_entry free_or_keep;
1362 struct sigwork_entry *swork;
1366 free_or_keep = FREE_ENT;
1371 /* build complete name of archive directory into dirpart */
1372 if (*archdirname == '/') { /* absolute */
1373 strlcpy(dirpart, archdirname, sizeof(dirpart));
1374 } else { /* relative */
1375 /* get directory part of logfile */
1376 strlcpy(dirpart, ent->log, sizeof(dirpart));
1377 if ((p = rindex(dirpart, '/')) == NULL)
1381 strlcat(dirpart, archdirname, sizeof(dirpart));
1384 /* check if archive directory exists, if not, create it */
1385 if (lstat(dirpart, &st))
1386 createdir(ent, dirpart);
1388 /* get filename part of logfile */
1389 if ((p = rindex(ent->log, '/')) == NULL)
1390 strlcpy(namepart, ent->log, sizeof(namepart));
1392 strlcpy(namepart, p + 1, sizeof(namepart));
1394 /* name of oldest log */
1395 (void) snprintf(file1, sizeof(file1), "%s/%s.%d", dirpart,
1396 namepart, ent->numlogs);
1397 (void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1399 snprintf(jfile1, sizeof(jfile1), "%s%s", file1,
1400 BZCOMPRESS_POSTFIX);
1402 /* name of oldest log */
1403 (void) snprintf(file1, sizeof(file1), "%s.%d", ent->log,
1405 (void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1407 snprintf(jfile1, sizeof(jfile1), "%s%s", file1,
1408 BZCOMPRESS_POSTFIX);
1412 printf("\trm -f %s\n", file1);
1413 printf("\trm -f %s\n", zfile1);
1414 printf("\trm -f %s\n", jfile1);
1416 (void) unlink(file1);
1417 (void) unlink(zfile1);
1418 (void) unlink(jfile1);
1421 /* Move down log files */
1422 numlogs_c = ent->numlogs; /* copy for countdown */
1423 while (numlogs_c--) {
1425 (void) strlcpy(file2, file1, sizeof(file2));
1428 (void) snprintf(file1, sizeof(file1), "%s/%s.%d",
1429 dirpart, namepart, numlogs_c);
1431 (void) snprintf(file1, sizeof(file1), "%s.%d",
1432 ent->log, numlogs_c);
1434 (void) strlcpy(zfile1, file1, sizeof(zfile1));
1435 (void) strlcpy(zfile2, file2, sizeof(zfile2));
1436 if (lstat(file1, &st)) {
1437 (void) strlcat(zfile1, COMPRESS_POSTFIX,
1439 (void) strlcat(zfile2, COMPRESS_POSTFIX,
1441 if (lstat(zfile1, &st)) {
1442 strlcpy(zfile1, file1, sizeof(zfile1));
1443 strlcpy(zfile2, file2, sizeof(zfile2));
1444 strlcat(zfile1, BZCOMPRESS_POSTFIX,
1446 strlcat(zfile2, BZCOMPRESS_POSTFIX,
1448 if (lstat(zfile1, &st))
1453 printf("\tmv %s %s\n", zfile1, zfile2);
1455 /* XXX - Ought to be checking for failure! */
1456 (void)rename(zfile1, zfile2);
1458 change_attrs(zfile2, ent);
1461 if (ent->numlogs > 0) {
1464 * Note that savelog() may succeed with using link()
1465 * for the archtodir case, but there is no good way
1466 * of knowing if it will when doing "noaction", so
1467 * here we claim that it will have to do a copy...
1470 printf("\tcp %s %s\n", ent->log, file1);
1472 printf("\tln %s %s\n", ent->log, file1);
1474 if (!(flags & CE_BINARY)) {
1475 /* Report the trimming to the old log */
1476 log_trim(ent->log, ent);
1478 savelog(ent->log, file1);
1480 change_attrs(file1, ent);
1483 /* Create the new log file and move it into place */
1485 printf("Start new log...\n");
1489 * Save all signalling and file-compression to be done after log
1490 * files from all entries have been rotated. This way any one
1491 * process will not be sent the same signal multiple times when
1492 * multiple log files had to be rotated.
1495 if (ent->pid_file != NULL)
1496 swork = save_sigwork(ent);
1497 if (ent->numlogs > 0 && (flags & (CE_COMPACT | CE_BZCOMPACT))) {
1499 * The zipwork_entry will include a pointer to this
1500 * conf_entry, so the conf_entry should not be freed.
1502 free_or_keep = KEEP_ENT;
1503 save_zipwork(ent, swork, ent->fsize, file1);
1506 return (free_or_keep);
1510 do_sigwork(struct sigwork_entry *swork)
1512 struct sigwork_entry *nextsig;
1515 if (!(swork->sw_pidok) || swork->sw_pid == 0)
1516 return; /* no work to do... */
1519 * If nosignal (-s) was specified, then do not signal any process.
1520 * Note that a nosignal request triggers a warning message if the
1521 * rotated logfile needs to be compressed, *unless* -R was also
1522 * specified. We assume that an `-sR' request came from a process
1523 * which writes to the logfile, and as such, we assume that process
1524 * has already made sure the logfile is not presently in use. This
1525 * just sets swork->sw_pidok to a special value, and do_zipwork
1526 * will print any necessary warning(s).
1530 swork->sw_pidok = -1;
1535 * Compute the pause between consecutive signals. Use a longer
1536 * sleep time if we will be sending two signals to the same
1537 * deamon or process-group.
1540 nextsig = SLIST_NEXT(swork, sw_nextp);
1541 if (nextsig != NULL) {
1542 if (swork->sw_pid == nextsig->sw_pid)
1549 printf("\tkill -%d %d \t\t# %s\n", swork->sw_signum,
1550 (int)swork->sw_pid, swork->sw_fname);
1552 printf("\tsleep %d\n", secs);
1556 kres = kill(swork->sw_pid, swork->sw_signum);
1559 * Assume that "no such process" (ESRCH) is something
1560 * to warn about, but is not an error. Presumably the
1561 * process which writes to the rotated log file(s) is
1562 * gone, in which case we should have no problem with
1563 * compressing the rotated log file(s).
1566 swork->sw_pidok = 0;
1567 warn("can't notify %s, pid %d", swork->sw_pidtype,
1568 (int)swork->sw_pid);
1571 printf("Notified %s pid %d = %s\n", swork->sw_pidtype,
1572 (int)swork->sw_pid, swork->sw_fname);
1575 printf("Pause %d second(s) between signals\n",
1583 do_zipwork(struct zipwork_entry *zwork)
1585 const char *pgm_name, *pgm_path;
1586 int errsav, fcount, zstatus;
1588 char zresult[MAXPATHLEN];
1591 strlcpy(zresult, zwork->zw_fname, sizeof(zresult));
1592 if (zwork != NULL && zwork->zw_conf != NULL) {
1593 if (zwork->zw_conf->flags & CE_COMPACT) {
1594 pgm_path = _PATH_GZIP;
1595 strlcat(zresult, COMPRESS_POSTFIX, sizeof(zresult));
1596 } else if (zwork->zw_conf->flags & CE_BZCOMPACT) {
1597 pgm_path = _PATH_BZIP2;
1598 strlcat(zresult, BZCOMPRESS_POSTFIX, sizeof(zresult));
1601 if (pgm_path == NULL) {
1602 warnx("invalid entry for %s in do_zipwork", zwork->zw_fname);
1605 pgm_name = strrchr(pgm_path, '/');
1606 if (pgm_name == NULL)
1607 pgm_name = pgm_path;
1611 if (zwork->zw_swork != NULL && zwork->zw_swork->sw_pidok <= 0) {
1613 "log %s not compressed because daemon(s) not notified",
1615 change_attrs(zwork->zw_fname, zwork->zw_conf);
1620 printf("\t%s %s\n", pgm_name, zwork->zw_fname);
1621 change_attrs(zresult, zwork->zw_conf);
1627 while (pidzip < 0) {
1629 * The fork failed. If the failure was due to a temporary
1630 * problem, then wait a short time and try it again.
1633 warn("fork() for `%s %s'", pgm_name, zwork->zw_fname);
1634 if (errsav != EAGAIN || fcount > 5)
1635 errx(1, "Exiting...");
1641 /* The child process executes the compression command */
1642 execl(pgm_path, pgm_path, "-f", zwork->zw_fname, (char *)0);
1643 err(1, "execl(`%s -f %s')", pgm_path, zwork->zw_fname);
1646 wpid = waitpid(pidzip, &zstatus, 0);
1648 /* XXX - should this be a fatal error? */
1649 warn("%s: waitpid(%d)", pgm_path, pidzip);
1652 if (!WIFEXITED(zstatus)) {
1653 warnx("`%s -f %s' did not terminate normally", pgm_name,
1657 if (WEXITSTATUS(zstatus)) {
1658 warnx("`%s -f %s' terminated with a non-zero status (%d)",
1659 pgm_name, zwork->zw_fname, WEXITSTATUS(zstatus));
1663 /* Compression was successful, set file attributes on the result. */
1664 change_attrs(zresult, zwork->zw_conf);
1668 * Save information on any process we need to signal. Any single
1669 * process may need to be sent different signal-values for different
1670 * log files, but usually a single signal-value will cause the process
1671 * to close and re-open all of it's log files.
1673 static struct sigwork_entry *
1674 save_sigwork(const struct conf_entry *ent)
1676 struct sigwork_entry *sprev, *stmp;
1682 SLIST_FOREACH(stmp, &swhead, sw_nextp) {
1683 ndiff = strcmp(ent->pid_file, stmp->sw_fname);
1687 if (ent->sig == stmp->sw_signum)
1689 if (ent->sig > stmp->sw_signum) {
1696 if (stmp != NULL && ndiff == 0)
1699 tmpsiz = sizeof(struct sigwork_entry) + strlen(ent->pid_file) + 1;
1700 stmp = malloc(tmpsiz);
1701 set_swpid(stmp, ent);
1702 stmp->sw_signum = ent->sig;
1703 strcpy(stmp->sw_fname, ent->pid_file);
1705 SLIST_INSERT_HEAD(&swhead, stmp, sw_nextp);
1707 SLIST_INSERT_AFTER(sprev, stmp, sw_nextp);
1712 * Save information on any file we need to compress. We may see the same
1713 * file multiple times, so check the full list to avoid duplicates. The
1714 * list itself is sorted smallest-to-largest, because that's the order we
1715 * want to compress the files. If the partition is very low on disk space,
1716 * then the smallest files are the most likely to compress, and compressing
1717 * them first will free up more space for the larger files.
1719 static struct zipwork_entry *
1720 save_zipwork(const struct conf_entry *ent, const struct sigwork_entry *swork,
1721 int zsize, const char *zipfname)
1723 struct zipwork_entry *zprev, *ztmp;
1727 /* Compute the size if the caller did not know it. */
1729 zsize = sizefile(zipfname);
1733 SLIST_FOREACH(ztmp, &zwhead, zw_nextp) {
1734 ndiff = strcmp(zipfname, ztmp->zw_fname);
1737 if (zsize > ztmp->zw_fsize)
1740 if (ztmp != NULL && ndiff == 0)
1743 tmpsiz = sizeof(struct zipwork_entry) + strlen(zipfname) + 1;
1744 ztmp = malloc(tmpsiz);
1745 ztmp->zw_conf = ent;
1746 ztmp->zw_swork = swork;
1747 ztmp->zw_fsize = zsize;
1748 strcpy(ztmp->zw_fname, zipfname);
1750 SLIST_INSERT_HEAD(&zwhead, ztmp, zw_nextp);
1752 SLIST_INSERT_AFTER(zprev, ztmp, zw_nextp);
1756 /* Send a signal to the pid specified by pidfile */
1758 set_swpid(struct sigwork_entry *swork, const struct conf_entry *ent)
1761 long minok, maxok, rval;
1762 char *endp, *linep, line[BUFSIZ];
1766 swork->sw_pidok = 0;
1768 swork->sw_pidtype = "daemon";
1769 if (ent->flags & CE_SIGNALGROUP) {
1771 * If we are expected to signal a process-group when
1772 * rotating this logfile, then the value read in should
1773 * be the negative of a valid process ID.
1777 swork->sw_pidtype = "process-group";
1780 f = fopen(ent->pid_file, "r");
1782 warn("can't open pid file: %s", ent->pid_file);
1786 if (fgets(line, BUFSIZ, f) == NULL) {
1788 * Warn if the PID file is empty, but do not consider
1789 * it an error. Most likely it means the process has
1790 * has terminated, so it should be safe to rotate any
1791 * log files that the process would have been using.
1794 swork->sw_pidok = 1;
1795 warnx("pid file is empty: %s", ent->pid_file);
1797 warn("can't read from pid file: %s", ent->pid_file);
1805 while (*linep == ' ')
1807 rval = strtol(linep, &endp, 10);
1808 if (*endp != '\0' && !isspacech(*endp)) {
1809 warnx("pid file does not start with a valid number: %s",
1811 } else if (rval < minok || rval > maxok) {
1812 warnx("bad value '%ld' for process number in %s",
1813 rval, ent->pid_file);
1815 warnx("\t(expecting value between %ld and %ld)",
1818 swork->sw_pidok = 1;
1819 swork->sw_pid = rval;
1825 /* Log the fact that the logs were turned over */
1827 log_trim(const char *logname, const struct conf_entry *log_ent)
1832 if ((f = fopen(logname, "a")) == NULL)
1835 if (log_ent->def_cfg)
1836 xtra = " using <default> rule";
1837 if (log_ent->firstcreate)
1838 fprintf(f, "%s %s newsyslog[%d]: logfile first created%s\n",
1839 daytime, hostname, (int) getpid(), xtra);
1840 else if (log_ent->r_reason != NULL)
1841 fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s%s\n",
1842 daytime, hostname, (int) getpid(), log_ent->r_reason, xtra);
1844 fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s\n",
1845 daytime, hostname, (int) getpid(), xtra);
1846 if (fclose(f) == EOF)
1847 err(1, "log_trim: fclose");
1851 /* Return size in kilobytes of a file */
1853 sizefile(const char *file)
1857 if (stat(file, &sb) < 0)
1859 return (kbytes(dbtob(sb.st_blocks)));
1862 /* Return the age of old log file (file.0) */
1864 age_old_log(char *file)
1868 char tmp[MAXPATHLEN + sizeof(".0") + sizeof(COMPRESS_POSTFIX) +
1869 sizeof(BZCOMPRESS_POSTFIX) + 1];
1874 /* build name of archive directory into tmp */
1875 if (*archdirname == '/') { /* absolute */
1876 strlcpy(tmp, archdirname, sizeof(tmp));
1877 } else { /* relative */
1878 /* get directory part of logfile */
1879 strlcpy(tmp, file, sizeof(tmp));
1880 if ((p = rindex(tmp, '/')) == NULL)
1884 strlcat(tmp, archdirname, sizeof(tmp));
1887 strlcat(tmp, "/", sizeof(tmp));
1889 /* get filename part of logfile */
1890 if ((p = rindex(file, '/')) == NULL)
1891 strlcat(tmp, file, sizeof(tmp));
1893 strlcat(tmp, p + 1, sizeof(tmp));
1895 (void) strlcpy(tmp, file, sizeof(tmp));
1898 strlcat(tmp, ".0", sizeof(tmp));
1899 if (stat(tmp, &sb) < 0) {
1901 * A plain '.0' file does not exist. Try again, first
1902 * with the added suffix of '.gz', then with an added
1903 * suffix of '.bz2' instead of '.gz'.
1905 endp = strchr(tmp, '\0');
1906 strlcat(tmp, COMPRESS_POSTFIX, sizeof(tmp));
1907 if (stat(tmp, &sb) < 0) {
1908 *endp = '\0'; /* Remove .gz */
1909 strlcat(tmp, BZCOMPRESS_POSTFIX, sizeof(tmp));
1910 if (stat(tmp, &sb) < 0)
1914 return ((int)(ptimeget_secs(timenow) - sb.st_mtime + 1800) / 3600);
1917 /* Skip Over Blanks */
1921 while (p && *p && isspace(*p))
1926 /* Skip Over Non-Blanks */
1930 while (p && *p && !isspace(*p))
1935 /* Check if string is actually a number */
1937 isnumberstr(const char *string)
1940 if (!isdigitch(*string++))
1947 * Save the active log file under a new name. A link to the new name
1948 * is the quick-and-easy way to do this. If that fails (which it will
1949 * if the destination is on another partition), then make a copy of
1950 * the file to the new location.
1953 savelog(char *from, char *to)
1958 res = link(from, to);
1962 if ((src = fopen(from, "r")) == NULL)
1963 err(1, "can't fopen %s for reading", from);
1964 if ((dst = fopen(to, "w")) == NULL)
1965 err(1, "can't fopen %s for writing", to);
1967 while ((c = getc(src)) != EOF) {
1968 if ((putc(c, dst)) == EOF)
1969 err(1, "error writing to %s", to);
1973 err(1, "error reading from %s", from);
1974 if ((fclose(src)) != 0)
1975 err(1, "can't fclose %s", to);
1976 if ((fclose(dst)) != 0)
1977 err(1, "can't fclose %s", from);
1980 /* create one or more directory components of a path */
1982 createdir(const struct conf_entry *ent, char *dirpart)
1986 char mkdirpath[MAXPATHLEN];
1994 if (*s != '/' && *s != '\0')
1997 res = lstat(mkdirpath, &st);
2000 printf("\tmkdir %s\n", mkdirpath);
2002 res = mkdir(mkdirpath, 0755);
2004 err(1, "Error on mkdir(\"%s\") for -a",
2012 if (ent->firstcreate)
2013 printf("Created directory '%s' for new %s\n",
2016 printf("Created directory '%s' for -a\n", dirpart);
2021 * Create a new log file, destroying any currently-existing version
2022 * of the log file in the process. If the caller wants a backup copy
2023 * of the file to exist, they should call 'link(logfile,logbackup)'
2024 * before calling this routine.
2027 createlog(const struct conf_entry *ent)
2031 char *realfile, *slash, tempfile[MAXPATHLEN];
2034 realfile = ent->log;
2037 * If this log file is being created for the first time (-C option),
2038 * then it may also be true that the parent directory does not exist
2039 * yet. Check, and create that directory if it is missing.
2041 if (ent->firstcreate) {
2042 strlcpy(tempfile, realfile, sizeof(tempfile));
2043 slash = strrchr(tempfile, '/');
2044 if (slash != NULL) {
2046 failed = stat(tempfile, &st);
2047 if (failed && errno != ENOENT)
2048 err(1, "Error on stat(%s)", tempfile);
2050 createdir(ent, tempfile);
2051 else if (!S_ISDIR(st.st_mode))
2052 errx(1, "%s exists but is not a directory",
2058 * First create an unused filename, so it can be chown'ed and
2059 * chmod'ed before it is moved into the real location. mkstemp
2060 * will create the file mode=600 & owned by us. Note that all
2061 * temp files will have a suffix of '.z<something>'.
2063 strlcpy(tempfile, realfile, sizeof(tempfile));
2064 strlcat(tempfile, ".zXXXXXX", sizeof(tempfile));
2066 printf("\tmktemp %s\n", tempfile);
2068 fd = mkstemp(tempfile);
2070 err(1, "can't mkstemp logfile %s", tempfile);
2073 * Add status message to what will become the new log file.
2075 if (!(ent->flags & CE_BINARY)) {
2076 if (log_trim(tempfile, ent))
2077 err(1, "can't add status message to log");
2081 /* Change the owner/group, if we are supposed to */
2082 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2084 printf("\tchown %u:%u %s\n", ent->uid, ent->gid,
2087 failed = fchown(fd, ent->uid, ent->gid);
2089 err(1, "can't fchown temp file %s", tempfile);
2093 /* Turn on NODUMP if it was requested in the config-file. */
2094 if (ent->flags & CE_NODUMP) {
2096 printf("\tchflags nodump %s\n", tempfile);
2098 failed = fchflags(fd, UF_NODUMP);
2100 warn("log_trim: fchflags(NODUMP)");
2106 * Note that if the real logfile still exists, and if the call
2107 * to rename() fails, then "neither the old file nor the new
2108 * file shall be changed or created" (to quote the standard).
2109 * If the call succeeds, then the file will be replaced without
2110 * any window where some other process might find that the file
2112 * XXX - ? It may be that for some error conditions, we could
2113 * retry by first removing the realfile and then renaming.
2116 printf("\tchmod %o %s\n", ent->permissions, tempfile);
2117 printf("\tmv %s %s\n", tempfile, realfile);
2119 failed = fchmod(fd, ent->permissions);
2121 err(1, "can't fchmod temp file '%s'", tempfile);
2122 failed = rename(tempfile, realfile);
2124 err(1, "can't mv %s to %s", tempfile, realfile);
2132 * Change the attributes of a given filename to what was specified in
2133 * the newsyslog.conf entry. This routine is only called for files
2134 * that newsyslog expects that it has created, and thus it is a fatal
2135 * error if this routine finds that the file does not exist.
2138 change_attrs(const char *fname, const struct conf_entry *ent)
2143 printf("\tchmod %o %s\n", ent->permissions, fname);
2145 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
2146 printf("\tchown %u:%u %s\n",
2147 ent->uid, ent->gid, fname);
2149 if (ent->flags & CE_NODUMP)
2150 printf("\tchflags nodump %s\n", fname);
2154 failed = chmod(fname, ent->permissions);
2157 err(1, "chmod(%s) in change_attrs", fname);
2158 warn("change_attrs couldn't chmod(%s)", fname);
2161 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2162 failed = chown(fname, ent->uid, ent->gid);
2164 warn("can't chown %s", fname);
2167 if (ent->flags & CE_NODUMP) {
2168 failed = chflags(fname, UF_NODUMP);
2170 warn("can't chflags %s NODUMP", fname);