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"
91 /* Define this symbol to try out the "new order" for work items. */
94 #define USE_NEWORDER 1 /* Initial value for dbg_new_order */
98 * Bit-values for the 'flags' parsed from a config-file entry.
100 #define CE_COMPACT 0x0001 /* Compact the achived log files with gzip. */
101 #define CE_BZCOMPACT 0x0002 /* Compact the achived log files with bzip2. */
102 #define CE_COMPACTWAIT 0x0004 /* wait until compressing one file finishes */
103 /* before starting the next step. */
104 #define CE_BINARY 0x0008 /* Logfile is in binary, do not add status */
105 /* messages to logfile(s) when rotating. */
106 #define CE_NOSIGNAL 0x0010 /* There is no process to signal when */
107 /* trimming this file. */
108 #define CE_TRIMAT 0x0020 /* trim file at a specific time. */
109 #define CE_GLOB 0x0040 /* name of the log is file name pattern. */
110 #define CE_SIGNALGROUP 0x0080 /* Signal a process-group instead of a single */
111 /* process when trimming this file. */
112 #define CE_CREATE 0x0100 /* Create the log file if it does not exist. */
113 #define CE_NODUMP 0x0200 /* Set 'nodump' on newly created log file. */
115 #define MIN_PID 5 /* Don't touch pids lower than this */
116 #define MAX_PID 99999 /* was lower, see /usr/include/sys/proc.h */
118 #define kbytes(size) (((size) + 1023) >> 10)
120 #define DEFAULT_MARKER "<default>"
121 #define DEBUG_MARKER "<debug>"
124 char *log; /* Name of the log */
125 char *pid_file; /* PID file */
126 char *r_reason; /* The reason this file is being rotated */
127 int firstcreate; /* Creating log for the first time (-C). */
128 int rotate; /* Non-zero if this file should be rotated */
129 int fsize; /* size found for the log file */
130 uid_t uid; /* Owner of log */
131 gid_t gid; /* Group of log */
132 int numlogs; /* Number of logs to keep */
133 int trsize; /* Size cutoff to trigger trimming the log */
134 int hours; /* Hours between log trimming */
135 struct ptime_data *trim_at; /* Specific time to do trimming */
136 unsigned int permissions; /* File permissions on the log */
137 int flags; /* CE_COMPACT, CE_BZCOMPACT, CE_BINARY */
138 int sig; /* Signal to send */
139 int def_cfg; /* Using the <default> rule for this file */
140 struct conf_entry *next;/* Linked list pointer */
143 struct sigwork_entry {
144 SLIST_ENTRY(sigwork_entry) sw_nextp;
145 int sw_signum; /* the signal to send */
146 int sw_pidok; /* true if pid value is valid */
147 pid_t sw_pid; /* the process id from the PID file */
148 const char *sw_pidtype; /* "daemon" or "process group" */
149 char sw_fname[1]; /* file the PID was read from */
152 struct zipwork_entry {
153 SLIST_ENTRY(zipwork_entry) zw_nextp;
154 const struct conf_entry *zw_conf; /* for chown/perm/flag info */
155 const struct sigwork_entry *zw_swork; /* to know success of signal */
156 int zw_fsize; /* size of the file to compress */
157 char zw_fname[1]; /* the file to compress */
164 SLIST_HEAD(swlisthead, sigwork_entry) swhead = SLIST_HEAD_INITIALIZER(swhead);
165 SLIST_HEAD(zwlisthead, zipwork_entry) zwhead = SLIST_HEAD_INITIALIZER(zwhead);
167 int dbg_at_times; /* -D Show details of 'trim_at' code */
169 * The debug options "neworder" and "oldorder" can be used to change
170 * which order work is done in. Note that both options will disappear
171 * in the near future, and the "new" order will be the only order.
173 int dbg_new_order = USE_NEWORDER;
175 int archtodir = 0; /* Archive old logfiles to other directory */
176 int createlogs; /* Create (non-GLOB) logfiles which do not */
177 /* already exist. 1=='for entries with */
178 /* C flag', 2=='for all entries'. */
179 int verbose = 0; /* Print out what's going on */
180 int needroot = 1; /* Root privs are necessary */
181 int noaction = 0; /* Don't do anything, just show it */
182 int norotate = 0; /* Don't rotate */
183 int nosignal; /* Do not send any signals */
184 int force = 0; /* Force the trim no matter what */
185 int rotatereq = 0; /* -R = Always rotate the file(s) as given */
186 /* on the command (this also requires */
187 /* that a list of files *are* given on */
188 /* the run command). */
189 char *requestor; /* The name given on a -R request */
190 char *archdirname; /* Directory path to old logfiles archive */
191 char *destdir = NULL; /* Directory to treat at root for logs */
192 const char *conf; /* Configuration file to use */
194 struct ptime_data *dbg_timenow; /* A "timenow" value set via -D option */
195 struct ptime_data *timenow; /* The time to use for checking at-fields */
197 char hostname[MAXHOSTNAMELEN]; /* hostname */
198 char daytime[16]; /* The current time in human readable form,
199 * used for rotation-tracking messages. */
201 static struct conf_entry *get_worklist(char **files);
202 static void parse_file(FILE *cf, const char *cfname, struct conf_entry **work_p,
203 struct conf_entry **glob_p, struct conf_entry **defconf_p);
204 static char *sob(char *p);
205 static char *son(char *p);
206 static int isnumberstr(const char *);
207 static char *missing_field(char *p, char *errline);
208 static void change_attrs(const char *, const struct conf_entry *);
209 static fk_entry do_entry(struct conf_entry *);
210 static fk_entry do_rotate(const struct conf_entry *);
212 static void do_sigwork(struct sigwork_entry *);
213 static void do_zipwork(struct zipwork_entry *);
214 static struct sigwork_entry *
215 save_sigwork(const struct conf_entry *);
216 static struct zipwork_entry *
217 save_zipwork(const struct conf_entry *, const struct
218 sigwork_entry *, int, const char *);
219 static void set_swpid(struct sigwork_entry *, const struct conf_entry *);
221 static int sizefile(const char *);
222 static void expand_globs(struct conf_entry **work_p,
223 struct conf_entry **glob_p);
224 static void free_clist(struct conf_entry **firstent);
225 static void free_entry(struct conf_entry *ent);
226 static struct conf_entry *init_entry(const char *fname,
227 struct conf_entry *src_entry);
228 static void parse_args(int argc, char **argv);
229 static int parse_doption(const char *doption);
230 static void usage(void);
231 static int log_trim(const char *logname, const struct conf_entry *log_ent);
232 static void compress_log(char *logname, int dowait);
233 static void bzcompress_log(char *logname, int dowait);
234 static int age_old_log(char *file);
235 static int send_signal(const struct conf_entry *ent);
236 static void savelog(char *from, char *to);
237 static void createdir(const struct conf_entry *ent, char *dirpart);
238 static void createlog(const struct conf_entry *ent);
241 * All the following take a parameter of 'int', but expect values in the
242 * range of unsigned char. Define wrappers which take values of type 'char',
243 * whether signed or unsigned, and ensure they end up in the right range.
245 #define isdigitch(Anychar) isdigit((u_char)(Anychar))
246 #define isprintch(Anychar) isprint((u_char)(Anychar))
247 #define isspacech(Anychar) isspace((u_char)(Anychar))
248 #define tolowerch(Anychar) tolower((u_char)(Anychar))
251 main(int argc, char **argv)
253 fk_entry free_or_keep;
254 struct conf_entry *p, *q;
256 struct sigwork_entry *stmp;
257 struct zipwork_entry *ztmp;
263 parse_args(argc, argv);
267 if (needroot && getuid() && geteuid())
268 errx(1, "must have root privs");
269 p = q = get_worklist(argv);
272 * Rotate all the files which need to be rotated. Note that
273 * some users have *hundreds* of entries in newsyslog.conf!
276 free_or_keep = do_entry(p);
278 if (free_or_keep == FREE_ENT)
285 * Send signals to any processes which need a signal to tell
286 * them to close and re-open the log file(s) we have rotated.
287 * Note that zipwork_entries include pointers to these
288 * sigwork_entry's, so we can not free the entries here.
290 if (!SLIST_EMPTY(&swhead)) {
291 if (noaction || verbose)
292 printf("Signal all daemon process(es)...\n");
293 SLIST_FOREACH(stmp, &swhead, sw_nextp)
296 printf("\tsleep 10\n");
299 printf("Pause 10 seconds to allow daemon(s)"
300 " to close log file(s)\n");
305 * Compress all files that we're expected to compress, now
306 * that all processes should have closed the files which
309 if (!SLIST_EMPTY(&zwhead)) {
310 if (noaction || verbose)
311 printf("Compress all rotated log file(s)...\n");
312 while (!SLIST_EMPTY(&zwhead)) {
313 ztmp = SLIST_FIRST(&zwhead);
315 SLIST_REMOVE_HEAD(&zwhead, zw_nextp);
319 /* Now free all the sigwork entries. */
320 while (!SLIST_EMPTY(&swhead)) {
321 stmp = SLIST_FIRST(&swhead);
322 SLIST_REMOVE_HEAD(&swhead, sw_nextp);
325 #endif /* TRY_NEWORDER */
327 while (wait(NULL) > 0 || errno == EINTR)
332 static struct conf_entry *
333 init_entry(const char *fname, struct conf_entry *src_entry)
335 struct conf_entry *tempwork;
338 printf("\t--> [creating entry for %s]\n", fname);
340 tempwork = malloc(sizeof(struct conf_entry));
341 if (tempwork == NULL)
342 err(1, "malloc of conf_entry for %s", fname);
344 if (destdir == NULL || fname[0] != '/')
345 tempwork->log = strdup(fname);
347 asprintf(&tempwork->log, "%s%s", destdir, fname);
348 if (tempwork->log == NULL)
349 err(1, "strdup for %s", fname);
351 if (src_entry != NULL) {
352 tempwork->pid_file = NULL;
353 if (src_entry->pid_file)
354 tempwork->pid_file = strdup(src_entry->pid_file);
355 tempwork->r_reason = NULL;
356 tempwork->firstcreate = 0;
357 tempwork->rotate = 0;
358 tempwork->fsize = -1;
359 tempwork->uid = src_entry->uid;
360 tempwork->gid = src_entry->gid;
361 tempwork->numlogs = src_entry->numlogs;
362 tempwork->trsize = src_entry->trsize;
363 tempwork->hours = src_entry->hours;
364 tempwork->trim_at = NULL;
365 if (src_entry->trim_at != NULL)
366 tempwork->trim_at = ptime_init(src_entry->trim_at);
367 tempwork->permissions = src_entry->permissions;
368 tempwork->flags = src_entry->flags;
369 tempwork->sig = src_entry->sig;
370 tempwork->def_cfg = src_entry->def_cfg;
372 /* Initialize as a "do-nothing" entry */
373 tempwork->pid_file = NULL;
374 tempwork->r_reason = NULL;
375 tempwork->firstcreate = 0;
376 tempwork->rotate = 0;
377 tempwork->fsize = -1;
378 tempwork->uid = (uid_t)-1;
379 tempwork->gid = (gid_t)-1;
380 tempwork->numlogs = 1;
381 tempwork->trsize = -1;
382 tempwork->hours = -1;
383 tempwork->trim_at = NULL;
384 tempwork->permissions = 0;
386 tempwork->sig = SIGHUP;
387 tempwork->def_cfg = 0;
389 tempwork->next = NULL;
395 free_entry(struct conf_entry *ent)
401 if (ent->log != NULL) {
403 printf("\t--> [freeing entry for %s]\n", ent->log);
408 if (ent->pid_file != NULL) {
410 ent->pid_file = NULL;
413 if (ent->r_reason != NULL) {
415 ent->r_reason = NULL;
418 if (ent->trim_at != NULL) {
419 ptime_free(ent->trim_at);
427 free_clist(struct conf_entry **firstent)
429 struct conf_entry *ent, *nextent;
431 if (firstent == NULL)
432 return; /* There is nothing to do. */
445 do_entry(struct conf_entry * ent)
447 #define REASON_MAX 80
449 fk_entry free_or_keep;
451 char temp_reason[REASON_MAX];
453 free_or_keep = FREE_ENT;
455 if (ent->flags & CE_COMPACT)
456 printf("%s <%dZ>: ", ent->log, ent->numlogs);
457 else if (ent->flags & CE_BZCOMPACT)
458 printf("%s <%dJ>: ", ent->log, ent->numlogs);
460 printf("%s <%d>: ", ent->log, ent->numlogs);
462 ent->fsize = sizefile(ent->log);
463 modtime = age_old_log(ent->log);
465 ent->firstcreate = 0;
466 if (ent->fsize < 0) {
468 * If either the C flag or the -C option was specified,
469 * and if we won't be creating the file, then have the
470 * verbose message include a hint as to why the file
471 * will not be created.
473 temp_reason[0] = '\0';
475 ent->firstcreate = 1;
476 else if ((ent->flags & CE_CREATE) && createlogs)
477 ent->firstcreate = 1;
478 else if (ent->flags & CE_CREATE)
479 strncpy(temp_reason, " (no -C option)", REASON_MAX);
481 strncpy(temp_reason, " (no C flag)", REASON_MAX);
483 if (ent->firstcreate) {
485 printf("does not exist -> will create.\n");
487 } else if (verbose) {
488 printf("does not exist, skipped%s.\n", temp_reason);
491 if (ent->flags & CE_TRIMAT && !force && !rotatereq) {
492 diffsecs = ptimeget_diff(timenow, ent->trim_at);
493 if (diffsecs < 0.0) {
494 /* trim_at is some time in the future. */
496 ptime_adjust4dst(ent->trim_at,
498 printf("--> will trim at %s",
499 ptimeget_ctime(ent->trim_at));
501 return (free_or_keep);
502 } else if (diffsecs >= 3600.0) {
504 * trim_at is more than an hour in the past,
505 * so find the next valid trim_at time, and
506 * tell the user what that will be.
508 if (verbose && dbg_at_times)
509 printf("\n\t--> prev trim at %s\t",
510 ptimeget_ctime(ent->trim_at));
512 ptimeset_nxtime(ent->trim_at);
513 printf("--> will trim at %s",
514 ptimeget_ctime(ent->trim_at));
516 return (free_or_keep);
517 } else if (verbose && noaction && dbg_at_times) {
519 * If we are just debugging at-times, then
520 * a detailed message is helpful. Also
521 * skip "doing" any commands, since they
522 * would all be turned off by no-action.
524 printf("\n\t--> timematch at %s",
525 ptimeget_ctime(ent->trim_at));
526 return (free_or_keep);
527 } else if (verbose && ent->hours <= 0) {
528 printf("--> time is up\n");
531 if (verbose && (ent->trsize > 0))
532 printf("size (Kb): %d [%d] ", ent->fsize, ent->trsize);
533 if (verbose && (ent->hours > 0))
534 printf(" age (hr): %d [%d] ", modtime, ent->hours);
537 * Figure out if this logfile needs to be rotated.
539 temp_reason[0] = '\0';
542 snprintf(temp_reason, REASON_MAX, " due to -R from %s",
546 snprintf(temp_reason, REASON_MAX, " due to -F request");
547 } else if ((ent->trsize > 0) && (ent->fsize >= ent->trsize)) {
549 snprintf(temp_reason, REASON_MAX, " due to size>%dK",
551 } else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) {
553 } else if ((ent->hours > 0) && ((modtime >= ent->hours) ||
559 * If the file needs to be rotated, then rotate it.
561 if (ent->rotate && !norotate) {
562 if (temp_reason[0] != '\0')
563 ent->r_reason = strdup(temp_reason);
565 printf("--> trimming log....\n");
566 if (noaction && !verbose) {
567 if (ent->flags & CE_COMPACT)
568 printf("%s <%dZ>: trimming\n",
569 ent->log, ent->numlogs);
570 else if (ent->flags & CE_BZCOMPACT)
571 printf("%s <%dJ>: trimming\n",
572 ent->log, ent->numlogs);
574 printf("%s <%d>: trimming\n",
575 ent->log, ent->numlogs);
577 free_or_keep = do_rotate(ent);
580 printf("--> skipping\n");
583 return (free_or_keep);
587 /* Send a signal to the pid specified by pidfile */
589 send_signal(const struct conf_entry *ent)
594 long minok, maxok, rval;
595 const char *target_name;
596 char *endp, *linep, line[BUFSIZ];
599 f = fopen(ent->pid_file, "r");
601 warn("can't open pid file: %s", ent->pid_file);
606 if (fgets(line, BUFSIZ, f) == NULL) {
608 * XXX - If the pid file is empty, is that really a
609 * problem? Wouldn't that mean that the process
610 * has shut down? In that case there would be no
611 * problem with compressing the rotated log file.
614 warnx("pid file is empty: %s", ent->pid_file);
616 warn("can't read from pid file: %s", ent->pid_file);
623 target_name = "daemon";
626 if (ent->flags & CE_SIGNALGROUP) {
628 * If we are expected to signal a process-group when
629 * rotating this logfile, then the value read in should
630 * be the negative of a valid process ID.
632 target_name = "process-group";
639 while (*linep == ' ')
641 rval = strtol(linep, &endp, 10);
642 if (*endp != '\0' && !isspacech(*endp)) {
643 warnx("pid file does not start with a valid number: %s",
646 } else if (rval < minok || rval > maxok) {
647 warnx("bad value '%ld' for process number in %s",
648 rval, ent->pid_file);
650 warnx("\t(expecting value between %ld and %ld)",
663 printf("\tkill -%d %d\n", ent->sig, (int) target_pid);
664 } else if (kill(target_pid, ent->sig)) {
666 * XXX - Iff the error was "no such process", should that
667 * really be an error for us? Perhaps the process
668 * is already gone, in which case there would be no
669 * problem with compressing the rotated log file.
671 warn("can't notify %s, pid %d", target_name,
676 printf("%s pid %d notified\n", target_name,
684 parse_args(int argc, char **argv)
689 timenow = ptime_init(NULL);
690 ptimeset_time(timenow, time(NULL));
691 (void)strncpy(daytime, ptimeget_ctime(timenow) + 4, 15);
694 /* Let's get our hostname */
695 (void)gethostname(hostname, sizeof(hostname));
697 /* Truncate domain */
698 if ((p = strchr(hostname, '.')) != NULL)
701 /* Parse command line options. */
702 while ((ch = getopt(argc, argv, "a:d:f:nrsvCD:FNR:")) != -1)
706 archdirname = optarg;
727 /* Useful for things like rc.diskless... */
732 * Set some debugging option. The specific option
733 * depends on the value of optarg. These options
734 * may come and go without notice or documentation.
736 if (parse_doption(optarg))
748 requestor = strdup(optarg);
750 case 'm': /* Used by OpenBSD for "monitor mode" */
756 if (force && norotate) {
757 warnx("Only one of -F and -N may be specified.");
763 if (optind == argc) {
764 warnx("At least one filename must be given when -R is specified.");
768 /* Make sure "requestor" value is safe for a syslog message. */
769 for (p = requestor; *p != '\0'; p++) {
770 if (!isprintch(*p) && (*p != '\t'))
777 * Note that the 'daytime' variable is not changed.
778 * That is only used in messages that track when a
779 * logfile is rotated, and if a file *is* rotated,
780 * then it will still rotated at the "real now" time.
783 timenow = dbg_timenow;
784 fprintf(stderr, "Debug: Running as if TimeNow is %s",
785 ptimeget_ctime(dbg_timenow));
791 * These debugging options are mainly meant for developer use, such
792 * as writing regression-tests. They would not be needed by users
793 * during normal operation of newsyslog...
796 parse_doption(const char *doption)
798 const char TN[] = "TN=";
801 if (strncmp(doption, TN, sizeof(TN) - 1) == 0) {
803 * The "TimeNow" debugging option. This might be off
804 * by an hour when crossing a timezone change.
806 dbg_timenow = ptime_init(NULL);
807 res = ptime_relparse(dbg_timenow, PTM_PARSE_ISO8601,
808 time(NULL), doption + sizeof(TN) - 1);
810 warnx("Non-existent time specified on -D %s", doption);
811 return (0); /* failure */
812 } else if (res < 0) {
813 warnx("Malformed time given on -D %s", doption);
814 return (0); /* failure */
816 return (1); /* successfully parsed */
820 if (strcmp(doption, "ats") == 0) {
822 return (1); /* successfully parsed */
825 if (strcmp(doption, "neworder") == 0) {
829 warnx("NOTE: The code for 'neworder' was not compiled in.");
831 return (1); /* successfully parsed */
833 if (strcmp(doption, "oldorder") == 0) {
837 warnx("NOTE: The code for 'neworder' was not compiled in.");
839 return (1); /* successfully parsed */
842 warnx("Unknown -D (debug) option: '%s'", doption);
843 return (0); /* failure */
851 "usage: newsyslog [-CFNnrsv] [-a directory] [-d directory] [-f config-file]\n"
852 " [ [-R requestor] filename ... ]\n");
857 * Parse a configuration file and return a linked list of all the logs
858 * which should be processed.
860 static struct conf_entry *
861 get_worklist(char **files)
866 struct conf_entry *defconf, *dupent, *ent, *firstnew;
867 struct conf_entry *globlist, *lastnew, *worklist;
870 defconf = globlist = worklist = NULL;
876 if (strcmp(fname, "-") != 0)
877 f = fopen(fname, "r");
885 parse_file(f, fname, &worklist, &globlist, &defconf);
889 * All config-file information has been read in and turned into
890 * a worklist and a globlist. If there were no specific files
891 * given on the run command, then the only thing left to do is to
892 * call a routine which finds all files matched by the globlist
893 * and adds them to the worklist. Then return the worklist.
895 if (*files == NULL) {
896 expand_globs(&worklist, &globlist);
897 free_clist(&globlist);
905 * If newsyslog was given a specific list of files to process,
906 * it may be that some of those files were not listed in any
907 * config file. Those unlisted files should get the default
908 * rotation action. First, create the default-rotation action
909 * if none was found in a system config file.
911 if (defconf == NULL) {
912 defconf = init_entry(DEFAULT_MARKER, NULL);
913 defconf->numlogs = 3;
914 defconf->trsize = 50;
915 defconf->permissions = S_IRUSR|S_IWUSR;
919 * If newsyslog was run with a list of specific filenames,
920 * then create a new worklist which has only those files in
921 * it, picking up the rotation-rules for those files from
922 * the original worklist.
924 * XXX - Note that this will copy multiple rules for a single
925 * logfile, if multiple entries are an exact match for
926 * that file. That matches the historic behavior, but do
927 * we want to continue to allow it? If so, it should
928 * probably be handled more intelligently.
930 firstnew = lastnew = NULL;
931 for (given = files; *given; ++given) {
933 * First try to find exact-matches for this given file.
936 for (ent = worklist; ent; ent = ent->next) {
937 if (strcmp(ent->log, *given) == 0) {
939 dupent = init_entry(*given, ent);
943 lastnew->next = dupent;
949 printf("\t+ Matched entry %s\n", *given);
954 * There was no exact-match for this given file, so look
955 * for a "glob" entry which does match.
958 if (verbose > 2 && globlist != NULL)
959 printf("\t+ Checking globs for %s\n", *given);
960 for (ent = globlist; ent; ent = ent->next) {
961 fnres = fnmatch(ent->log, *given, FNM_PATHNAME);
963 printf("\t+ = %d for pattern %s\n", fnres,
967 dupent = init_entry(*given, ent);
971 lastnew->next = dupent;
973 /* This new entry is not a glob! */
974 dupent->flags &= ~CE_GLOB;
975 /* Only allow a match to one glob-entry */
981 printf("\t+ Matched %s via %s\n", *given,
987 * This given file was not found in any config file, so
988 * add a worklist item based on the default entry.
991 printf("\t+ No entry matched %s (will use %s)\n",
992 *given, DEFAULT_MARKER);
993 dupent = init_entry(*given, defconf);
997 lastnew->next = dupent;
998 /* Mark that it was *not* found in a config file */
1004 * Free all the entries in the original work list, the list of
1005 * glob entries, and the default entry.
1007 free_clist(&worklist);
1008 free_clist(&globlist);
1009 free_entry(defconf);
1011 /* And finally, return a worklist which matches the given files. */
1016 * Expand the list of entries with filename patterns, and add all files
1017 * which match those glob-entries onto the worklist.
1020 expand_globs(struct conf_entry **work_p, struct conf_entry **glob_p)
1022 int gmatch, gres, i;
1024 struct conf_entry *dupent, *ent, *firstmatch, *globent;
1025 struct conf_entry *lastmatch;
1029 if ((glob_p == NULL) || (*glob_p == NULL))
1030 return; /* There is nothing to do. */
1033 * The worklist contains all fully-specified (non-GLOB) names.
1035 * Now expand the list of filename-pattern (GLOB) entries into
1036 * a second list, which (by definition) will only match files
1037 * that already exist. Do not add a glob-related entry for any
1038 * file which already exists in the fully-specified list.
1040 firstmatch = lastmatch = NULL;
1041 for (globent = *glob_p; globent; globent = globent->next) {
1043 gres = glob(globent->log, GLOB_NOCHECK, NULL, &pglob);
1045 warn("cannot expand pattern (%d): %s", gres,
1051 printf("\t+ Expanding pattern %s\n", globent->log);
1052 for (i = 0; i < pglob.gl_matchc; i++) {
1053 mfname = pglob.gl_pathv[i];
1055 /* See if this file already has a specific entry. */
1057 for (ent = *work_p; ent; ent = ent->next) {
1058 if (strcmp(mfname, ent->log) == 0) {
1066 /* Make sure the named matched is a file. */
1067 gres = lstat(mfname, &st_fm);
1069 /* Error on a file that glob() matched?!? */
1070 warn("Skipping %s - lstat() error", mfname);
1073 if (!S_ISREG(st_fm.st_mode)) {
1074 /* We only rotate files! */
1076 printf("\t+ . skipping %s (!file)\n",
1082 printf("\t+ . add file %s\n", mfname);
1083 dupent = init_entry(mfname, globent);
1085 firstmatch = dupent;
1087 lastmatch->next = dupent;
1089 /* This new entry is not a glob! */
1090 dupent->flags &= ~CE_GLOB;
1094 printf("\t+ Done with pattern %s\n", globent->log);
1097 /* Add the list of matched files to the end of the worklist. */
1099 *work_p = firstmatch;
1104 ent->next = firstmatch;
1110 * Parse a configuration file and update a linked list of all the logs to
1114 parse_file(FILE *cf, const char *cfname, struct conf_entry **work_p,
1115 struct conf_entry **glob_p, struct conf_entry **defconf_p)
1117 char line[BUFSIZ], *parse, *q;
1118 char *cp, *errline, *group;
1119 struct conf_entry *lastglob, *lastwork, *working;
1122 int eol, ptm_opts, res, special;
1125 * XXX - for now, assume that only one config file will be read,
1126 * ie, this routine is only called one time.
1128 lastglob = lastwork = NULL;
1131 while (fgets(line, BUFSIZ, cf)) {
1132 if ((line[0] == '\n') || (line[0] == '#') ||
1133 (strlen(line) == 0))
1135 if (errline != NULL)
1137 errline = strdup(line);
1138 for (cp = line + 1; *cp != '\0'; cp++) {
1141 if (*(cp - 1) == '\\') {
1150 q = parse = missing_field(sob(line), errline);
1153 errx(1, "malformed line (missing fields):\n%s",
1158 * Allow people to set debug options via the config file.
1159 * (NOTE: debug optons are undocumented, and may disappear
1160 * at any time, etc).
1162 if (strcasecmp(DEBUG_MARKER, q) == 0) {
1163 q = parse = missing_field(sob(++parse), errline);
1166 warnx("debug line specifies no option:\n%s",
1176 working = init_entry(q, NULL);
1177 if (strcasecmp(DEFAULT_MARKER, q) == 0) {
1179 if (defconf_p == NULL) {
1180 warnx("Ignoring entry for %s in %s!", q,
1182 free_entry(working);
1184 } else if (*defconf_p != NULL) {
1185 warnx("Ignoring duplicate entry for %s!", q);
1186 free_entry(working);
1189 *defconf_p = working;
1192 q = parse = missing_field(sob(++parse), errline);
1195 errx(1, "malformed line (missing fields):\n%s",
1198 if ((group = strchr(q, ':')) != NULL ||
1199 (group = strrchr(q, '.')) != NULL) {
1202 if (!(isnumberstr(q))) {
1203 if ((pwd = getpwnam(q)) == NULL)
1205 "error in config file; unknown user:\n%s",
1207 working->uid = pwd->pw_uid;
1209 working->uid = atoi(q);
1211 working->uid = (uid_t)-1;
1215 if (!(isnumberstr(q))) {
1216 if ((grp = getgrnam(q)) == NULL)
1218 "error in config file; unknown group:\n%s",
1220 working->gid = grp->gr_gid;
1222 working->gid = atoi(q);
1224 working->gid = (gid_t)-1;
1226 q = parse = missing_field(sob(++parse), errline);
1229 errx(1, "malformed line (missing fields):\n%s",
1233 working->uid = (uid_t)-1;
1234 working->gid = (gid_t)-1;
1237 if (!sscanf(q, "%o", &working->permissions))
1238 errx(1, "error in config file; bad permissions:\n%s",
1241 q = parse = missing_field(sob(++parse), errline);
1244 errx(1, "malformed line (missing fields):\n%s",
1247 if (!sscanf(q, "%d", &working->numlogs) || working->numlogs < 0)
1248 errx(1, "error in config file; bad value for count of logs to save:\n%s",
1251 q = parse = missing_field(sob(++parse), errline);
1254 errx(1, "malformed line (missing fields):\n%s",
1258 working->trsize = atoi(q);
1259 else if (strcmp(q, "*") == 0)
1260 working->trsize = -1;
1262 warnx("Invalid value of '%s' for 'size' in line:\n%s",
1264 working->trsize = -1;
1268 q = parse = missing_field(sob(++parse), errline);
1276 ul = strtoul(q, &ep, 10);
1279 else if (*ep == '*')
1280 working->hours = -1;
1281 else if (ul > INT_MAX)
1282 errx(1, "interval is too large:\n%s", errline);
1284 working->hours = ul;
1286 if (*ep == '\0' || strcmp(ep, "*") == 0)
1288 if (*ep != '@' && *ep != '$')
1289 errx(1, "malformed interval/at:\n%s", errline);
1291 working->flags |= CE_TRIMAT;
1292 working->trim_at = ptime_init(NULL);
1293 ptm_opts = PTM_PARSE_ISO8601;
1295 ptm_opts = PTM_PARSE_DWM;
1296 ptm_opts |= PTM_PARSE_MATCHDOM;
1297 res = ptime_relparse(working->trim_at, ptm_opts,
1298 ptimeget_secs(timenow), ep + 1);
1300 errx(1, "nonexistent time for 'at' value:\n%s",
1303 errx(1, "malformed 'at' value:\n%s", errline);
1310 q = parse = sob(++parse); /* Optional field */
1317 for (; q && *q && !isspacech(*q); q++) {
1318 switch (tolowerch(*q)) {
1320 working->flags |= CE_BINARY;
1324 * XXX - Ick! Ugly! Remove ASAP!
1325 * We want `c' and `C' for "create". But we
1326 * will temporarily treat `c' as `g', because
1327 * FreeBSD releases <= 4.8 have a typo of
1328 * checking ('G' || 'c') for CE_GLOB.
1331 warnx("Assuming 'g' for 'c' in flags for line:\n%s",
1333 warnx("The 'c' flag will eventually mean 'CREATE'");
1334 working->flags |= CE_GLOB;
1337 working->flags |= CE_CREATE;
1340 working->flags |= CE_NODUMP;
1343 working->flags |= CE_GLOB;
1346 working->flags |= CE_BZCOMPACT;
1349 working->flags |= CE_NOSIGNAL;
1352 working->flags |= CE_SIGNALGROUP;
1355 working->flags |= CE_COMPACTWAIT;
1358 working->flags |= CE_COMPACT;
1362 case 'f': /* Used by OpenBSD for "CE_FOLLOW" */
1363 case 'm': /* Used by OpenBSD for "CE_MONITOR" */
1364 case 'p': /* Used by NetBSD for "CE_PLAIN0" */
1366 errx(1, "illegal flag in config file -- %c",
1374 q = parse = sob(++parse); /* Optional field */
1381 working->pid_file = NULL;
1384 working->pid_file = strdup(q);
1385 else if (isdigit(*q))
1389 "illegal pid file or signal number in config file:\n%s",
1395 q = parse = sob(++parse); /* Optional field */
1396 *(parse = son(parse)) = '\0';
1399 working->sig = SIGHUP;
1403 working->sig = atoi(q);
1407 "illegal signal number in config file:\n%s",
1410 if (working->sig < 1 || working->sig >= NSIG)
1415 * Finish figuring out what pid-file to use (if any) in
1416 * later processing if this logfile needs to be rotated.
1418 if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) {
1420 * This config-entry specified 'n' for nosignal,
1421 * see if it also specified an explicit pid_file.
1422 * This would be a pretty pointless combination.
1424 if (working->pid_file != NULL) {
1425 warnx("Ignoring '%s' because flag 'n' was specified in line:\n%s",
1426 working->pid_file, errline);
1427 free(working->pid_file);
1428 working->pid_file = NULL;
1430 } else if (working->pid_file == NULL) {
1432 * This entry did not specify the 'n' flag, which
1433 * means it should signal syslogd unless it had
1434 * specified some other pid-file (and obviously the
1435 * syslog pid-file will not be for a process-group).
1436 * Also, we should only try to notify syslog if we
1439 if (working->flags & CE_SIGNALGROUP) {
1440 warnx("Ignoring flag 'U' in line:\n%s",
1442 working->flags &= ~CE_SIGNALGROUP;
1445 working->pid_file = strdup(_PATH_SYSLOGPID);
1449 * Add this entry to the appropriate list of entries, unless
1450 * it was some kind of special entry (eg: <default>).
1453 ; /* Do not add to any list */
1454 } else if (working->flags & CE_GLOB) {
1458 lastglob->next = working;
1464 lastwork->next = working;
1468 if (errline != NULL)
1473 missing_field(char *p, char *errline)
1477 errx(1, "missing field in config file:\n%s", errline);
1482 do_rotate(const struct conf_entry *ent)
1484 char dirpart[MAXPATHLEN], namepart[MAXPATHLEN];
1485 char file1[MAXPATHLEN], file2[MAXPATHLEN];
1486 char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN];
1487 char jfile1[MAXPATHLEN];
1488 int flags, notified, need_notification, numlogs_c;
1489 fk_entry free_or_keep;
1493 free_or_keep = FREE_ENT;
1498 /* build complete name of archive directory into dirpart */
1499 if (*archdirname == '/') { /* absolute */
1500 strlcpy(dirpart, archdirname, sizeof(dirpart));
1501 } else { /* relative */
1502 /* get directory part of logfile */
1503 strlcpy(dirpart, ent->log, sizeof(dirpart));
1504 if ((p = rindex(dirpart, '/')) == NULL)
1508 strlcat(dirpart, archdirname, sizeof(dirpart));
1511 /* check if archive directory exists, if not, create it */
1512 if (lstat(dirpart, &st))
1513 createdir(ent, dirpart);
1515 /* get filename part of logfile */
1516 if ((p = rindex(ent->log, '/')) == NULL)
1517 strlcpy(namepart, ent->log, sizeof(namepart));
1519 strlcpy(namepart, p + 1, sizeof(namepart));
1521 /* name of oldest log */
1522 (void) snprintf(file1, sizeof(file1), "%s/%s.%d", dirpart,
1523 namepart, ent->numlogs);
1524 (void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1526 snprintf(jfile1, sizeof(jfile1), "%s%s", file1,
1527 BZCOMPRESS_POSTFIX);
1529 /* name of oldest log */
1530 (void) snprintf(file1, sizeof(file1), "%s.%d", ent->log,
1532 (void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1534 snprintf(jfile1, sizeof(jfile1), "%s%s", file1,
1535 BZCOMPRESS_POSTFIX);
1539 printf("\trm -f %s\n", file1);
1540 printf("\trm -f %s\n", zfile1);
1541 printf("\trm -f %s\n", jfile1);
1543 (void) unlink(file1);
1544 (void) unlink(zfile1);
1545 (void) unlink(jfile1);
1548 /* Move down log files */
1549 numlogs_c = ent->numlogs; /* copy for countdown */
1550 while (numlogs_c--) {
1552 (void) strlcpy(file2, file1, sizeof(file2));
1555 (void) snprintf(file1, sizeof(file1), "%s/%s.%d",
1556 dirpart, namepart, numlogs_c);
1558 (void) snprintf(file1, sizeof(file1), "%s.%d",
1559 ent->log, numlogs_c);
1561 (void) strlcpy(zfile1, file1, sizeof(zfile1));
1562 (void) strlcpy(zfile2, file2, sizeof(zfile2));
1563 if (lstat(file1, &st)) {
1564 (void) strlcat(zfile1, COMPRESS_POSTFIX,
1566 (void) strlcat(zfile2, COMPRESS_POSTFIX,
1568 if (lstat(zfile1, &st)) {
1569 strlcpy(zfile1, file1, sizeof(zfile1));
1570 strlcpy(zfile2, file2, sizeof(zfile2));
1571 strlcat(zfile1, BZCOMPRESS_POSTFIX,
1573 strlcat(zfile2, BZCOMPRESS_POSTFIX,
1575 if (lstat(zfile1, &st))
1580 printf("\tmv %s %s\n", zfile1, zfile2);
1582 /* XXX - Ought to be checking for failure! */
1583 (void)rename(zfile1, zfile2);
1585 change_attrs(zfile2, ent);
1588 if (ent->numlogs > 0) {
1591 * Note that savelog() may succeed with using link()
1592 * for the archtodir case, but there is no good way
1593 * of knowing if it will when doing "noaction", so
1594 * here we claim that it will have to do a copy...
1597 printf("\tcp %s %s\n", ent->log, file1);
1599 printf("\tln %s %s\n", ent->log, file1);
1601 if (!(flags & CE_BINARY)) {
1602 /* Report the trimming to the old log */
1603 log_trim(ent->log, ent);
1605 savelog(ent->log, file1);
1607 change_attrs(file1, ent);
1610 /* Create the new log file and move it into place */
1612 printf("Start new log...\n");
1617 * Save all signalling and file-compression to be done after log
1618 * files from all entries have been rotated. This way any one
1619 * process will not be sent the same signal multiple times when
1620 * multiple log files had to be rotated.
1622 if (dbg_new_order) {
1623 struct sigwork_entry *swork;
1626 if (ent->pid_file != NULL)
1627 swork = save_sigwork(ent);
1628 if (ent->numlogs > 0 && (flags & (CE_COMPACT | CE_BZCOMPACT))) {
1630 * The zipwork_entry will include a pointer to this
1631 * conf_entry, so the conf_entry should not be freed.
1633 free_or_keep = KEEP_ENT;
1634 save_zipwork(ent, swork, ent->fsize, file1);
1636 return (free_or_keep);
1638 #endif /* TRY_NEWORDER */
1641 * Find out if there is a process to signal. If nosignal (-s) was
1642 * specified, then do not signal any process. Note that nosignal
1643 * will trigger a warning message if the rotated logfile needs to
1644 * be compressed, *unless* -R was specified. This is because there
1645 * presumably still are process(es) writing to the old logfile, but
1646 * we assume that a -sR request comes from a process which writes
1647 * to the logfile, and as such, that process has already made sure
1648 * that the logfile is not presently in use.
1650 need_notification = notified = 0;
1651 if (ent->pid_file != NULL) {
1652 need_notification = 1;
1654 notified = send_signal(ent); /* the normal case! */
1656 need_notification = 0;
1659 if ((flags & CE_COMPACT) || (flags & CE_BZCOMPACT)) {
1660 if (need_notification && !notified)
1662 "log %s.0 not compressed because daemon(s) not notified",
1664 else if (noaction) {
1665 printf("\tsleep 10\n");
1666 if (flags & CE_COMPACT)
1667 printf("\tgzip %s.0\n", ent->log);
1669 printf("\tbzip2 %s.0\n", ent->log);
1673 printf("small pause to allow daemon(s) to close log\n");
1677 (void) snprintf(file1, sizeof(file1), "%s/%s",
1679 if (flags & CE_COMPACT)
1681 flags & CE_COMPACTWAIT);
1682 else if (flags & CE_BZCOMPACT)
1683 bzcompress_log(file1,
1684 flags & CE_COMPACTWAIT);
1686 if (flags & CE_COMPACT)
1687 compress_log(ent->log,
1688 flags & CE_COMPACTWAIT);
1689 else if (flags & CE_BZCOMPACT)
1690 bzcompress_log(ent->log,
1691 flags & CE_COMPACTWAIT);
1695 return (free_or_keep);
1700 do_sigwork(struct sigwork_entry *swork)
1702 struct sigwork_entry *nextsig;
1705 if (!(swork->sw_pidok) || swork->sw_pid == 0)
1706 return; /* no work to do... */
1709 * If nosignal (-s) was specified, then do not signal any process.
1710 * Note that a nosignal request triggers a warning message if the
1711 * rotated logfile needs to be compressed, *unless* -R was also
1712 * specified. We assume that an `-sR' request came from a process
1713 * which writes to the logfile, and as such, we assume that process
1714 * has already made sure the logfile is not presently in use. This
1715 * just sets swork->sw_pidok to a special value, and do_zipwork
1716 * will print any necessary warning(s).
1720 swork->sw_pidok = -1;
1725 * Compute the pause between consecutive signals. Use a longer
1726 * sleep time if we will be sending two signals to the same
1727 * deamon or process-group.
1730 nextsig = SLIST_NEXT(swork, sw_nextp);
1731 if (nextsig != NULL) {
1732 if (swork->sw_pid == nextsig->sw_pid)
1739 printf("\tkill -%d %d \t\t# %s\n", swork->sw_signum,
1740 (int)swork->sw_pid, swork->sw_fname);
1742 printf("\tsleep %d\n", secs);
1746 kres = kill(swork->sw_pid, swork->sw_signum);
1749 * Assume that "no such process" (ESRCH) is something
1750 * to warn about, but is not an error. Presumably the
1751 * process which writes to the rotated log file(s) is
1752 * gone, in which case we should have no problem with
1753 * compressing the rotated log file(s).
1756 swork->sw_pidok = 0;
1757 warn("can't notify %s, pid %d", swork->sw_pidtype,
1758 (int)swork->sw_pid);
1761 printf("Notified %s pid %d = %s\n", swork->sw_pidtype,
1762 (int)swork->sw_pid, swork->sw_fname);
1765 printf("Pause %d second(s) between signals\n",
1773 do_zipwork(struct zipwork_entry *zwork)
1775 const char *pgm_name, *pgm_path;
1778 char zresult[MAXPATHLEN];
1781 strlcpy(zresult, zwork->zw_fname, sizeof(zresult));
1782 if (zwork != NULL && zwork->zw_conf != NULL) {
1783 if (zwork->zw_conf->flags & CE_COMPACT) {
1784 pgm_path = _PATH_GZIP;
1785 strlcat(zresult, COMPRESS_POSTFIX, sizeof(zresult));
1786 } else if (zwork->zw_conf->flags & CE_BZCOMPACT) {
1787 pgm_path = _PATH_BZIP2;
1788 strlcat(zresult, BZCOMPRESS_POSTFIX, sizeof(zresult));
1791 if (pgm_path == NULL) {
1792 warnx("invalid entry for %s in do_zipwork", zwork->zw_fname);
1796 if (zwork->zw_swork != NULL && zwork->zw_swork->sw_pidok <= 0) {
1798 "log %s not compressed because daemon(s) not notified",
1800 change_attrs(zwork->zw_fname, zwork->zw_conf);
1805 pgm_name = strrchr(pgm_path, '/');
1806 if (pgm_name == NULL)
1807 pgm_name = pgm_path;
1810 printf("\t%s %s\n", pgm_name, zwork->zw_fname);
1811 change_attrs(zresult, zwork->zw_conf);
1817 err(1, "gzip fork");
1819 /* The child process executes the compression command */
1820 execl(pgm_path, pgm_path, "-f", zwork->zw_fname, (char *)0);
1821 err(1, "%s", pgm_path);
1824 wpid = waitpid(pidzip, &zstatus, 0);
1826 warn("%s: waitpid(%d)", pgm_path, pidzip);
1829 if (!WIFEXITED(zstatus)) {
1830 warn("%s: did not terminate normally", pgm_path);
1833 if (WEXITSTATUS(zstatus)) {
1834 warn("%s: terminated with %d (non-zero) status",
1835 pgm_path, WEXITSTATUS(zstatus));
1839 /* Compression was successful, set file attributes on the result. */
1840 change_attrs(zresult, zwork->zw_conf);
1844 * Save information on any process we need to signal. Any single
1845 * process may need to be sent different signal-values for different
1846 * log files, but usually a single signal-value will cause the process
1847 * to close and re-open all of it's log files.
1849 static struct sigwork_entry *
1850 save_sigwork(const struct conf_entry *ent)
1852 struct sigwork_entry *sprev, *stmp;
1858 SLIST_FOREACH(stmp, &swhead, sw_nextp) {
1859 ndiff = strcmp(ent->pid_file, stmp->sw_fname);
1863 if (ent->sig == stmp->sw_signum)
1865 if (ent->sig > stmp->sw_signum) {
1872 if (stmp != NULL && ndiff == 0)
1875 tmpsiz = sizeof(struct sigwork_entry) + strlen(ent->pid_file) + 1;
1876 stmp = malloc(tmpsiz);
1877 set_swpid(stmp, ent);
1878 stmp->sw_signum = ent->sig;
1879 strcpy(stmp->sw_fname, ent->pid_file);
1881 SLIST_INSERT_HEAD(&swhead, stmp, sw_nextp);
1883 SLIST_INSERT_AFTER(sprev, stmp, sw_nextp);
1888 * Save information on any file we need to compress. We may see the same
1889 * file multiple times, so check the full list to avoid duplicates. The
1890 * list itself is sorted smallest-to-largest, because that's the order we
1891 * want to compress the files. If the partition is very low on disk space,
1892 * then the smallest files are the most likely to compress, and compressing
1893 * them first will free up more space for the larger files.
1895 static struct zipwork_entry *
1896 save_zipwork(const struct conf_entry *ent, const struct sigwork_entry *swork,
1897 int zsize, const char *zipfname)
1899 struct zipwork_entry *zprev, *ztmp;
1903 /* Compute the size if the caller did not know it. */
1905 zsize = sizefile(zipfname);
1909 SLIST_FOREACH(ztmp, &zwhead, zw_nextp) {
1910 ndiff = strcmp(zipfname, ztmp->zw_fname);
1913 if (zsize > ztmp->zw_fsize)
1916 if (ztmp != NULL && ndiff == 0)
1919 tmpsiz = sizeof(struct zipwork_entry) + strlen(zipfname) + 1;
1920 ztmp = malloc(tmpsiz);
1921 ztmp->zw_conf = ent;
1922 ztmp->zw_swork = swork;
1923 ztmp->zw_fsize = zsize;
1924 strcpy(ztmp->zw_fname, zipfname);
1926 SLIST_INSERT_HEAD(&zwhead, ztmp, zw_nextp);
1928 SLIST_INSERT_AFTER(zprev, ztmp, zw_nextp);
1932 /* Send a signal to the pid specified by pidfile */
1934 set_swpid(struct sigwork_entry *swork, const struct conf_entry *ent)
1937 long minok, maxok, rval;
1938 char *endp, *linep, line[BUFSIZ];
1942 swork->sw_pidok = 0;
1944 swork->sw_pidtype = "daemon";
1945 if (ent->flags & CE_SIGNALGROUP) {
1947 * If we are expected to signal a process-group when
1948 * rotating this logfile, then the value read in should
1949 * be the negative of a valid process ID.
1953 swork->sw_pidtype = "process-group";
1956 f = fopen(ent->pid_file, "r");
1958 warn("can't open pid file: %s", ent->pid_file);
1962 if (fgets(line, BUFSIZ, f) == NULL) {
1964 * Warn if the PID file is empty, but do not consider
1965 * it an error. Most likely it means the process has
1966 * has terminated, so it should be safe to rotate any
1967 * log files that the process would have been using.
1970 swork->sw_pidok = 1;
1971 warnx("pid file is empty: %s", ent->pid_file);
1973 warn("can't read from pid file: %s", ent->pid_file);
1981 while (*linep == ' ')
1983 rval = strtol(linep, &endp, 10);
1984 if (*endp != '\0' && !isspacech(*endp)) {
1985 warnx("pid file does not start with a valid number: %s",
1987 } else if (rval < minok || rval > maxok) {
1988 warnx("bad value '%ld' for process number in %s",
1989 rval, ent->pid_file);
1991 warnx("\t(expecting value between %ld and %ld)",
1994 swork->sw_pidok = 1;
1995 swork->sw_pid = rval;
2000 #endif /* TRY_NEWORDER */
2002 /* Log the fact that the logs were turned over */
2004 log_trim(const char *logname, const struct conf_entry *log_ent)
2009 if ((f = fopen(logname, "a")) == NULL)
2012 if (log_ent->def_cfg)
2013 xtra = " using <default> rule";
2014 if (log_ent->firstcreate)
2015 fprintf(f, "%s %s newsyslog[%d]: logfile first created%s\n",
2016 daytime, hostname, (int) getpid(), xtra);
2017 else if (log_ent->r_reason != NULL)
2018 fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s%s\n",
2019 daytime, hostname, (int) getpid(), log_ent->r_reason, xtra);
2021 fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s\n",
2022 daytime, hostname, (int) getpid(), xtra);
2023 if (fclose(f) == EOF)
2024 err(1, "log_trim: fclose");
2029 * XXX - Note that both compress_log and bzcompress_log will lose the
2030 * NODUMP flag if it was set on somelog.0. Fixing that in newsyslog
2031 * (as opposed to fixing gzip/bzip2) will require some restructuring
2032 * of the code. That restructuring is planned for a later update...
2034 /* Fork of gzip to compress the old log file */
2036 compress_log(char *logname, int dowait)
2039 char tmp[MAXPATHLEN];
2041 while (dowait && (wait(NULL) > 0 || errno == EINTR))
2043 (void) snprintf(tmp, sizeof(tmp), "%s.0", logname);
2046 err(1, "gzip fork");
2048 (void) execl(_PATH_GZIP, _PATH_GZIP, "-f", tmp, (char *)0);
2053 /* Fork of bzip2 to compress the old log file */
2055 bzcompress_log(char *logname, int dowait)
2058 char tmp[MAXPATHLEN];
2060 while (dowait && (wait(NULL) > 0 || errno == EINTR))
2062 snprintf(tmp, sizeof(tmp), "%s.0", logname);
2065 err(1, "bzip2 fork");
2067 execl(_PATH_BZIP2, _PATH_BZIP2, "-f", tmp, (char *)0);
2068 err(1, _PATH_BZIP2);
2072 /* Return size in kilobytes of a file */
2074 sizefile(const char *file)
2078 if (stat(file, &sb) < 0)
2080 return (kbytes(dbtob(sb.st_blocks)));
2083 /* Return the age of old log file (file.0) */
2085 age_old_log(char *file)
2089 char tmp[MAXPATHLEN + sizeof(".0") + sizeof(COMPRESS_POSTFIX) +
2090 sizeof(BZCOMPRESS_POSTFIX) + 1];
2095 /* build name of archive directory into tmp */
2096 if (*archdirname == '/') { /* absolute */
2097 strlcpy(tmp, archdirname, sizeof(tmp));
2098 } else { /* relative */
2099 /* get directory part of logfile */
2100 strlcpy(tmp, file, sizeof(tmp));
2101 if ((p = rindex(tmp, '/')) == NULL)
2105 strlcat(tmp, archdirname, sizeof(tmp));
2108 strlcat(tmp, "/", sizeof(tmp));
2110 /* get filename part of logfile */
2111 if ((p = rindex(file, '/')) == NULL)
2112 strlcat(tmp, file, sizeof(tmp));
2114 strlcat(tmp, p + 1, sizeof(tmp));
2116 (void) strlcpy(tmp, file, sizeof(tmp));
2119 strlcat(tmp, ".0", sizeof(tmp));
2120 if (stat(tmp, &sb) < 0) {
2122 * A plain '.0' file does not exist. Try again, first
2123 * with the added suffix of '.gz', then with an added
2124 * suffix of '.bz2' instead of '.gz'.
2126 endp = strchr(tmp, '\0');
2127 strlcat(tmp, COMPRESS_POSTFIX, sizeof(tmp));
2128 if (stat(tmp, &sb) < 0) {
2129 *endp = '\0'; /* Remove .gz */
2130 strlcat(tmp, BZCOMPRESS_POSTFIX, sizeof(tmp));
2131 if (stat(tmp, &sb) < 0)
2135 return ((int)(ptimeget_secs(timenow) - sb.st_mtime + 1800) / 3600);
2138 /* Skip Over Blanks */
2142 while (p && *p && isspace(*p))
2147 /* Skip Over Non-Blanks */
2151 while (p && *p && !isspace(*p))
2156 /* Check if string is actually a number */
2158 isnumberstr(const char *string)
2161 if (!isdigitch(*string++))
2168 * Save the active log file under a new name. A link to the new name
2169 * is the quick-and-easy way to do this. If that fails (which it will
2170 * if the destination is on another partition), then make a copy of
2171 * the file to the new location.
2174 savelog(char *from, char *to)
2179 res = link(from, to);
2183 if ((src = fopen(from, "r")) == NULL)
2184 err(1, "can't fopen %s for reading", from);
2185 if ((dst = fopen(to, "w")) == NULL)
2186 err(1, "can't fopen %s for writing", to);
2188 while ((c = getc(src)) != EOF) {
2189 if ((putc(c, dst)) == EOF)
2190 err(1, "error writing to %s", to);
2194 err(1, "error reading from %s", from);
2195 if ((fclose(src)) != 0)
2196 err(1, "can't fclose %s", to);
2197 if ((fclose(dst)) != 0)
2198 err(1, "can't fclose %s", from);
2201 /* create one or more directory components of a path */
2203 createdir(const struct conf_entry *ent, char *dirpart)
2207 char mkdirpath[MAXPATHLEN];
2215 if (*s != '/' && *s != '\0')
2218 res = lstat(mkdirpath, &st);
2221 printf("\tmkdir %s\n", mkdirpath);
2223 res = mkdir(mkdirpath, 0755);
2225 err(1, "Error on mkdir(\"%s\") for -a",
2233 if (ent->firstcreate)
2234 printf("Created directory '%s' for new %s\n",
2237 printf("Created directory '%s' for -a\n", dirpart);
2242 * Create a new log file, destroying any currently-existing version
2243 * of the log file in the process. If the caller wants a backup copy
2244 * of the file to exist, they should call 'link(logfile,logbackup)'
2245 * before calling this routine.
2248 createlog(const struct conf_entry *ent)
2252 char *realfile, *slash, tempfile[MAXPATHLEN];
2255 realfile = ent->log;
2258 * If this log file is being created for the first time (-C option),
2259 * then it may also be true that the parent directory does not exist
2260 * yet. Check, and create that directory if it is missing.
2262 if (ent->firstcreate) {
2263 strlcpy(tempfile, realfile, sizeof(tempfile));
2264 slash = strrchr(tempfile, '/');
2265 if (slash != NULL) {
2267 failed = stat(tempfile, &st);
2268 if (failed && errno != ENOENT)
2269 err(1, "Error on stat(%s)", tempfile);
2271 createdir(ent, tempfile);
2272 else if (!S_ISDIR(st.st_mode))
2273 errx(1, "%s exists but is not a directory",
2279 * First create an unused filename, so it can be chown'ed and
2280 * chmod'ed before it is moved into the real location. mkstemp
2281 * will create the file mode=600 & owned by us. Note that all
2282 * temp files will have a suffix of '.z<something>'.
2284 strlcpy(tempfile, realfile, sizeof(tempfile));
2285 strlcat(tempfile, ".zXXXXXX", sizeof(tempfile));
2287 printf("\tmktemp %s\n", tempfile);
2289 fd = mkstemp(tempfile);
2291 err(1, "can't mkstemp logfile %s", tempfile);
2294 * Add status message to what will become the new log file.
2296 if (!(ent->flags & CE_BINARY)) {
2297 if (log_trim(tempfile, ent))
2298 err(1, "can't add status message to log");
2302 /* Change the owner/group, if we are supposed to */
2303 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2305 printf("\tchown %u:%u %s\n", ent->uid, ent->gid,
2308 failed = fchown(fd, ent->uid, ent->gid);
2310 err(1, "can't fchown temp file %s", tempfile);
2314 /* Turn on NODUMP if it was requested in the config-file. */
2315 if (ent->flags & CE_NODUMP) {
2317 printf("\tchflags nodump %s\n", tempfile);
2319 failed = fchflags(fd, UF_NODUMP);
2321 warn("log_trim: fchflags(NODUMP)");
2327 * Note that if the real logfile still exists, and if the call
2328 * to rename() fails, then "neither the old file nor the new
2329 * file shall be changed or created" (to quote the standard).
2330 * If the call succeeds, then the file will be replaced without
2331 * any window where some other process might find that the file
2333 * XXX - ? It may be that for some error conditions, we could
2334 * retry by first removing the realfile and then renaming.
2337 printf("\tchmod %o %s\n", ent->permissions, tempfile);
2338 printf("\tmv %s %s\n", tempfile, realfile);
2340 failed = fchmod(fd, ent->permissions);
2342 err(1, "can't fchmod temp file '%s'", tempfile);
2343 failed = rename(tempfile, realfile);
2345 err(1, "can't mv %s to %s", tempfile, realfile);
2353 change_attrs(const char *fname, const struct conf_entry *ent)
2358 printf("\tchmod %o %s\n", ent->permissions, fname);
2360 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
2361 printf("\tchown %u:%u %s\n",
2362 ent->uid, ent->gid, fname);
2364 if (ent->flags & CE_NODUMP)
2365 printf("\tchflags nodump %s\n", fname);
2369 failed = chmod(fname, ent->permissions);
2371 warn("can't chmod %s", fname);
2373 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2374 failed = chown(fname, ent->uid, ent->gid);
2376 warn("can't chown %s", fname);
2379 if (ent->flags & CE_NODUMP) {
2380 failed = chflags(fname, UF_NODUMP);
2382 warn("can't chflags %s NODUMP", fname);