2 * ------+---------+---------+-------- + --------+---------+---------+---------*
3 * This file includes significant modifications done by:
4 * Copyright (c) 2003, 2004 - Garance Alistair Drosehn <gad@FreeBSD.org>.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 * ------+---------+---------+-------- + --------+---------+---------+---------*
32 * This file contains changes from the Open Software Foundation.
36 * Copyright 1988, 1989 by the Massachusetts Institute of Technology
38 * Permission to use, copy, modify, and distribute this software and its
39 * documentation for any purpose and without fee is hereby granted, provided
40 * that the above copyright notice appear in all copies and that both that
41 * copyright notice and this permission notice appear in supporting
42 * documentation, and that the names of M.I.T. and the M.I.T. S.I.P.B. not be
43 * used in advertising or publicity pertaining to distribution of the
44 * software without specific, written prior permission. M.I.T. and the M.I.T.
45 * S.I.P.B. make no representations about the suitability of this software
46 * for any purpose. It is provided "as is" without express or implied
52 * newsyslog - roll over selected logs at the appropriate time, keeping the a
53 * specified number of backup files around.
56 #include <sys/cdefs.h>
57 __FBSDID("$FreeBSD$");
61 #include <sys/param.h>
62 #include <sys/queue.h>
87 #include "pathnames.h"
93 #define COMPRESS_TYPES 5 /* Number of supported compression types */
95 #define COMPRESS_NONE 0
96 #define COMPRESS_GZIP 1
97 #define COMPRESS_BZIP2 2
99 #define COMPRESS_ZSTD 4
102 * Bit-values for the 'flags' parsed from a config-file entry.
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. */
114 #define CE_PID2CMD 0x0400 /* Replace PID file with a shell command.*/
115 #define CE_PLAIN0 0x0800 /* Do not compress zero'th history file */
116 #define CE_RFC5424 0x1000 /* Use RFC5424 format rotation message */
118 #define MIN_PID 5 /* Don't touch pids lower than this */
119 #define MAX_PID 99999 /* was lower, see /usr/include/sys/proc.h */
121 #define kbytes(size) (((size) + 1023) >> 10)
123 #define DEFAULT_MARKER "<default>"
124 #define DEBUG_MARKER "<debug>"
125 #define INCLUDE_MARKER "<include>"
126 #define DEFAULT_TIMEFNAME_FMT "%Y%m%dT%H%M%S"
128 #define MAX_OLDLOGS 65536 /* Default maximum number of old logfiles */
130 struct compress_types {
131 const char *flag; /* Flag in configuration file */
132 const char *suffix; /* Compression suffix */
133 const char *path; /* Path to compression program */
134 const char **flags; /* Compression program flags */
135 int nflags; /* Program flags count */
138 static const char *gzip_flags[] = { "-f" };
139 #define bzip2_flags gzip_flags
140 #define xz_flags gzip_flags
141 static const char *zstd_flags[] = { "-q", "--rm" };
143 static const struct compress_types compress_type[COMPRESS_TYPES] = {
144 { "", "", "", NULL, 0 },
145 { "Z", ".gz", _PATH_GZIP, gzip_flags, nitems(gzip_flags) },
146 { "J", ".bz2", _PATH_BZIP2, bzip2_flags, nitems(bzip2_flags) },
147 { "X", ".xz", _PATH_XZ, xz_flags, nitems(xz_flags) },
148 { "Y", ".zst", _PATH_ZSTD, zstd_flags, nitems(zstd_flags) }
152 STAILQ_ENTRY(conf_entry) cf_nextp;
153 char *log; /* Name of the log */
154 char *pid_cmd_file; /* PID or command file */
155 char *r_reason; /* The reason this file is being rotated */
156 int firstcreate; /* Creating log for the first time (-C). */
157 int rotate; /* Non-zero if this file should be rotated */
158 int fsize; /* size found for the log file */
159 uid_t uid; /* Owner of log */
160 gid_t gid; /* Group of log */
161 int numlogs; /* Number of logs to keep */
162 int trsize; /* Size cutoff to trigger trimming the log */
163 int hours; /* Hours between log trimming */
164 struct ptime_data *trim_at; /* Specific time to do trimming */
165 unsigned int permissions; /* File permissions on the log */
166 int flags; /* CE_BINARY */
167 int compress; /* Compression */
168 int sig; /* Signal to send */
169 int def_cfg; /* Using the <default> rule for this file */
172 struct sigwork_entry {
173 SLIST_ENTRY(sigwork_entry) sw_nextp;
174 int sw_signum; /* the signal to send */
175 int sw_pidok; /* true if pid value is valid */
176 pid_t sw_pid; /* the process id from the PID file */
177 const char *sw_pidtype; /* "daemon" or "process group" */
178 int sw_runcmd; /* run command or send PID to signal */
179 char sw_fname[1]; /* file the PID was read from or shell cmd */
182 struct zipwork_entry {
183 SLIST_ENTRY(zipwork_entry) zw_nextp;
184 const struct conf_entry *zw_conf; /* for chown/perm/flag info */
185 const struct sigwork_entry *zw_swork; /* to know success of signal */
186 int zw_fsize; /* size of the file to compress */
187 char zw_fname[1]; /* the file to compress */
190 struct include_entry {
191 STAILQ_ENTRY(include_entry) inc_nextp;
192 const char *file; /* Name of file to process */
195 struct oldlog_entry {
196 char *fname; /* Filename of the log file */
197 time_t t; /* Parsed timestamp of the logfile */
204 STAILQ_HEAD(cflist, conf_entry);
205 static SLIST_HEAD(swlisthead, sigwork_entry) swhead =
206 SLIST_HEAD_INITIALIZER(swhead);
207 static SLIST_HEAD(zwlisthead, zipwork_entry) zwhead =
208 SLIST_HEAD_INITIALIZER(zwhead);
209 STAILQ_HEAD(ilist, include_entry);
211 int dbg_at_times; /* -D Show details of 'trim_at' code */
213 static int archtodir = 0; /* Archive old logfiles to other directory */
214 static int createlogs; /* Create (non-GLOB) logfiles which do not */
215 /* already exist. 1=='for entries with */
216 /* C flag', 2=='for all entries'. */
217 int verbose = 0; /* Print out what's going on */
218 static int needroot = 1; /* Root privs are necessary */
219 int noaction = 0; /* Don't do anything, just show it */
220 static int norotate = 0; /* Don't rotate */
221 static int nosignal; /* Do not send any signals */
222 static int enforcepid = 0; /* If PID file does not exist or empty, do nothing */
223 static int force = 0; /* Force the trim no matter what */
224 static int rotatereq = 0; /* -R = Always rotate the file(s) as given */
225 /* on the command (this also requires */
226 /* that a list of files *are* given on */
227 /* the run command). */
228 static char *requestor; /* The name given on a -R request */
229 static char *timefnamefmt = NULL;/* Use time based filenames instead of .0 */
230 static char *archdirname; /* Directory path to old logfiles archive */
231 static char *destdir = NULL; /* Directory to treat at root for logs */
232 static const char *conf; /* Configuration file to use */
234 struct ptime_data *dbg_timenow; /* A "timenow" value set via -D option */
235 static struct ptime_data *timenow; /* The time to use for checking at-fields */
237 #define DAYTIME_LEN 16
238 static char daytime[DAYTIME_LEN];/* The current time in human readable form,
239 * used for rotation-tracking messages. */
241 /* Another buffer to hold the current time in RFC5424 format. Fractional
242 * seconds are allowed by the RFC, but are not included in the
243 * rotation-tracking messages written by newsyslog and so are not accounted for
244 * in the length below.
246 #define DAYTIME_RFC5424_LEN sizeof("YYYY-MM-DDTHH:MM:SS+00:00")
247 static char daytime_rfc5424[DAYTIME_RFC5424_LEN];
249 static char hostname[MAXHOSTNAMELEN]; /* hostname */
250 static size_t hostname_shortlen;
252 static const char *path_syslogpid = _PATH_SYSLOGPID;
254 static struct cflist *get_worklist(char **files);
255 static void parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
256 struct conf_entry **defconf, struct ilist *inclist);
257 static void add_to_queue(const char *fname, struct ilist *inclist);
258 static char *sob(char *p);
259 static char *son(char *p);
260 static int isnumberstr(const char *);
261 static int isglobstr(const char *);
262 static char *missing_field(char *p, char *errline);
263 static void change_attrs(const char *, const struct conf_entry *);
264 static const char *get_logfile_suffix(const char *logfile);
265 static fk_entry do_entry(struct conf_entry *);
266 static fk_entry do_rotate(const struct conf_entry *);
267 static void do_sigwork(struct sigwork_entry *);
268 static void do_zipwork(struct zipwork_entry *);
269 static struct sigwork_entry *
270 save_sigwork(const struct conf_entry *);
271 static struct zipwork_entry *
272 save_zipwork(const struct conf_entry *, const struct
273 sigwork_entry *, int, const char *);
274 static void set_swpid(struct sigwork_entry *, const struct conf_entry *);
275 static int sizefile(const char *);
276 static void expand_globs(struct cflist *work_p, struct cflist *glob_p);
277 static void free_clist(struct cflist *list);
278 static void free_entry(struct conf_entry *ent);
279 static struct conf_entry *init_entry(const char *fname,
280 struct conf_entry *src_entry);
281 static void parse_args(int argc, char **argv);
282 static int parse_doption(const char *doption);
283 static void usage(void);
284 static int log_trim(const char *logname, const struct conf_entry *log_ent);
285 static int age_old_log(const char *file);
286 static void savelog(char *from, char *to);
287 static void createdir(const struct conf_entry *ent, char *dirpart);
288 static void createlog(const struct conf_entry *ent);
289 static int parse_signal(const char *str);
292 * All the following take a parameter of 'int', but expect values in the
293 * range of unsigned char. Define wrappers which take values of type 'char',
294 * whether signed or unsigned, and ensure they end up in the right range.
296 #define isdigitch(Anychar) isdigit((u_char)(Anychar))
297 #define isprintch(Anychar) isprint((u_char)(Anychar))
298 #define isspacech(Anychar) isspace((u_char)(Anychar))
299 #define tolowerch(Anychar) tolower((u_char)(Anychar))
302 main(int argc, char **argv)
304 struct cflist *worklist;
305 struct conf_entry *p;
306 struct sigwork_entry *stmp;
307 struct zipwork_entry *ztmp;
312 parse_args(argc, argv);
316 if (needroot && getuid() && geteuid())
317 errx(1, "must have root privs");
318 worklist = get_worklist(argv);
321 * Rotate all the files which need to be rotated. Note that
322 * some users have *hundreds* of entries in newsyslog.conf!
324 while (!STAILQ_EMPTY(worklist)) {
325 p = STAILQ_FIRST(worklist);
326 STAILQ_REMOVE_HEAD(worklist, cf_nextp);
327 if (do_entry(p) == FREE_ENT)
332 * Send signals to any processes which need a signal to tell
333 * them to close and re-open the log file(s) we have rotated.
334 * Note that zipwork_entries include pointers to these
335 * sigwork_entry's, so we can not free the entries here.
337 if (!SLIST_EMPTY(&swhead)) {
338 if (noaction || verbose)
339 printf("Signal all daemon process(es)...\n");
340 SLIST_FOREACH(stmp, &swhead, sw_nextp)
342 if (!(rotatereq && nosignal)) {
344 printf("\tsleep 10\n");
347 printf("Pause 10 seconds to allow "
348 "daemon(s) to close log file(s)\n");
354 * Compress all files that we're expected to compress, now
355 * that all processes should have closed the files which
358 if (!SLIST_EMPTY(&zwhead)) {
359 if (noaction || verbose)
360 printf("Compress all rotated log file(s)...\n");
361 while (!SLIST_EMPTY(&zwhead)) {
362 ztmp = SLIST_FIRST(&zwhead);
364 SLIST_REMOVE_HEAD(&zwhead, zw_nextp);
368 /* Now free all the sigwork entries. */
369 while (!SLIST_EMPTY(&swhead)) {
370 stmp = SLIST_FIRST(&swhead);
371 SLIST_REMOVE_HEAD(&swhead, sw_nextp);
375 while (wait(NULL) > 0 || errno == EINTR)
380 static struct conf_entry *
381 init_entry(const char *fname, struct conf_entry *src_entry)
383 struct conf_entry *tempwork;
386 printf("\t--> [creating entry for %s]\n", fname);
388 tempwork = malloc(sizeof(struct conf_entry));
389 if (tempwork == NULL)
390 err(1, "malloc of conf_entry for %s", fname);
392 if (destdir == NULL || fname[0] != '/')
393 tempwork->log = strdup(fname);
395 asprintf(&tempwork->log, "%s%s", destdir, fname);
396 if (tempwork->log == NULL)
397 err(1, "strdup for %s", fname);
399 if (src_entry != NULL) {
400 tempwork->pid_cmd_file = NULL;
401 if (src_entry->pid_cmd_file)
402 tempwork->pid_cmd_file = strdup(src_entry->pid_cmd_file);
403 tempwork->r_reason = NULL;
404 tempwork->firstcreate = 0;
405 tempwork->rotate = 0;
406 tempwork->fsize = -1;
407 tempwork->uid = src_entry->uid;
408 tempwork->gid = src_entry->gid;
409 tempwork->numlogs = src_entry->numlogs;
410 tempwork->trsize = src_entry->trsize;
411 tempwork->hours = src_entry->hours;
412 tempwork->trim_at = NULL;
413 if (src_entry->trim_at != NULL)
414 tempwork->trim_at = ptime_init(src_entry->trim_at);
415 tempwork->permissions = src_entry->permissions;
416 tempwork->flags = src_entry->flags;
417 tempwork->compress = src_entry->compress;
418 tempwork->sig = src_entry->sig;
419 tempwork->def_cfg = src_entry->def_cfg;
421 /* Initialize as a "do-nothing" entry */
422 tempwork->pid_cmd_file = NULL;
423 tempwork->r_reason = NULL;
424 tempwork->firstcreate = 0;
425 tempwork->rotate = 0;
426 tempwork->fsize = -1;
427 tempwork->uid = (uid_t)-1;
428 tempwork->gid = (gid_t)-1;
429 tempwork->numlogs = 1;
430 tempwork->trsize = -1;
431 tempwork->hours = -1;
432 tempwork->trim_at = NULL;
433 tempwork->permissions = 0;
435 tempwork->compress = COMPRESS_NONE;
436 tempwork->sig = SIGHUP;
437 tempwork->def_cfg = 0;
444 free_entry(struct conf_entry *ent)
450 if (ent->log != NULL) {
452 printf("\t--> [freeing entry for %s]\n", ent->log);
457 if (ent->pid_cmd_file != NULL) {
458 free(ent->pid_cmd_file);
459 ent->pid_cmd_file = NULL;
462 if (ent->r_reason != NULL) {
464 ent->r_reason = NULL;
467 if (ent->trim_at != NULL) {
468 ptime_free(ent->trim_at);
476 free_clist(struct cflist *list)
478 struct conf_entry *ent;
480 while (!STAILQ_EMPTY(list)) {
481 ent = STAILQ_FIRST(list);
482 STAILQ_REMOVE_HEAD(list, cf_nextp);
491 do_entry(struct conf_entry * ent)
493 #define REASON_MAX 80
495 fk_entry free_or_keep;
497 char temp_reason[REASON_MAX];
500 free_or_keep = FREE_ENT;
502 printf("%s <%d%s>: ", ent->log, ent->numlogs,
503 compress_type[ent->compress].flag);
504 ent->fsize = sizefile(ent->log);
505 oversized = ((ent->trsize > 0) && (ent->fsize >= ent->trsize));
506 modtime = age_old_log(ent->log);
508 ent->firstcreate = 0;
509 if (ent->fsize < 0) {
511 * If either the C flag or the -C option was specified,
512 * and if we won't be creating the file, then have the
513 * verbose message include a hint as to why the file
514 * will not be created.
516 temp_reason[0] = '\0';
518 ent->firstcreate = 1;
519 else if ((ent->flags & CE_CREATE) && createlogs)
520 ent->firstcreate = 1;
521 else if (ent->flags & CE_CREATE)
522 strlcpy(temp_reason, " (no -C option)", REASON_MAX);
524 strlcpy(temp_reason, " (no C flag)", REASON_MAX);
526 if (ent->firstcreate) {
528 printf("does not exist -> will create.\n");
530 } else if (verbose) {
531 printf("does not exist, skipped%s.\n", temp_reason);
534 if (ent->flags & CE_TRIMAT && !force && !rotatereq &&
536 diffsecs = ptimeget_diff(timenow, ent->trim_at);
537 if (diffsecs < 0.0) {
538 /* trim_at is some time in the future. */
540 ptime_adjust4dst(ent->trim_at,
542 printf("--> will trim at %s",
543 ptimeget_ctime(ent->trim_at));
545 return (free_or_keep);
546 } else if (diffsecs >= 3600.0) {
548 * trim_at is more than an hour in the past,
549 * so find the next valid trim_at time, and
550 * tell the user what that will be.
552 if (verbose && dbg_at_times)
553 printf("\n\t--> prev trim at %s\t",
554 ptimeget_ctime(ent->trim_at));
556 ptimeset_nxtime(ent->trim_at);
557 printf("--> will trim at %s",
558 ptimeget_ctime(ent->trim_at));
560 return (free_or_keep);
561 } else if (verbose && noaction && dbg_at_times) {
563 * If we are just debugging at-times, then
564 * a detailed message is helpful. Also
565 * skip "doing" any commands, since they
566 * would all be turned off by no-action.
568 printf("\n\t--> timematch at %s",
569 ptimeget_ctime(ent->trim_at));
570 return (free_or_keep);
571 } else if (verbose && ent->hours <= 0) {
572 printf("--> time is up\n");
575 if (verbose && (ent->trsize > 0))
576 printf("size (Kb): %d [%d] ", ent->fsize, ent->trsize);
577 if (verbose && (ent->hours > 0))
578 printf(" age (hr): %d [%d] ", modtime, ent->hours);
581 * Figure out if this logfile needs to be rotated.
583 temp_reason[0] = '\0';
586 snprintf(temp_reason, REASON_MAX, " due to -R from %s",
590 snprintf(temp_reason, REASON_MAX, " due to -F request");
591 } else if (oversized) {
593 snprintf(temp_reason, REASON_MAX, " due to size>%dK",
595 } else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) {
597 } else if ((ent->hours > 0) && ((modtime >= ent->hours) ||
603 * If the file needs to be rotated, then rotate it.
605 if (ent->rotate && !norotate) {
606 if (temp_reason[0] != '\0')
607 ent->r_reason = strdup(temp_reason);
609 printf("--> trimming log....\n");
610 if (noaction && !verbose)
611 printf("%s <%d%s>: trimming\n", ent->log,
613 compress_type[ent->compress].flag);
614 free_or_keep = do_rotate(ent);
617 printf("--> skipping\n");
620 return (free_or_keep);
625 parse_args(int argc, char **argv)
630 timenow = ptime_init(NULL);
631 ptimeset_time(timenow, time(NULL));
632 strlcpy(daytime, ptimeget_ctime(timenow) + 4, DAYTIME_LEN);
633 ptimeget_ctime_rfc5424(timenow, daytime_rfc5424, DAYTIME_RFC5424_LEN);
635 /* Let's get our hostname */
636 (void)gethostname(hostname, sizeof(hostname));
637 hostname_shortlen = strcspn(hostname, ".");
639 /* Parse command line options. */
640 while ((ch = getopt(argc, argv, "a:d:f:nrst:vCD:FNPR:S:")) != -1)
644 archdirname = optarg;
662 if (optarg[0] == '\0' ||
663 strcmp(optarg, "DEFAULT") == 0)
664 timefnamefmt = strdup(DEFAULT_TIMEFNAME_FMT);
666 timefnamefmt = strdup(optarg);
672 /* Useful for things like rc.diskless... */
677 * Set some debugging option. The specific option
678 * depends on the value of optarg. These options
679 * may come and go without notice or documentation.
681 if (parse_doption(optarg))
696 requestor = strdup(optarg);
699 path_syslogpid = optarg;
701 case 'm': /* Used by OpenBSD for "monitor mode" */
707 if (force && norotate) {
708 warnx("Only one of -F and -N may be specified.");
714 if (optind == argc) {
715 warnx("At least one filename must be given when -R is specified.");
719 /* Make sure "requestor" value is safe for a syslog message. */
720 for (p = requestor; *p != '\0'; p++) {
721 if (!isprintch(*p) && (*p != '\t'))
728 * Note that the 'daytime' variable is not changed.
729 * That is only used in messages that track when a
730 * logfile is rotated, and if a file *is* rotated,
731 * then it will still rotated at the "real now" time.
734 timenow = dbg_timenow;
735 fprintf(stderr, "Debug: Running as if TimeNow is %s",
736 ptimeget_ctime(dbg_timenow));
742 * These debugging options are mainly meant for developer use, such
743 * as writing regression-tests. They would not be needed by users
744 * during normal operation of newsyslog...
747 parse_doption(const char *doption)
749 const char TN[] = "TN=";
752 if (strncmp(doption, TN, sizeof(TN) - 1) == 0) {
754 * The "TimeNow" debugging option. This might be off
755 * by an hour when crossing a timezone change.
757 dbg_timenow = ptime_init(NULL);
758 res = ptime_relparse(dbg_timenow, PTM_PARSE_ISO8601,
759 time(NULL), doption + sizeof(TN) - 1);
761 warnx("Non-existent time specified on -D %s", doption);
762 return (0); /* failure */
763 } else if (res < 0) {
764 warnx("Malformed time given on -D %s", doption);
765 return (0); /* failure */
767 return (1); /* successfully parsed */
771 if (strcmp(doption, "ats") == 0) {
773 return (1); /* successfully parsed */
776 /* XXX - This check could probably be dropped. */
777 if ((strcmp(doption, "neworder") == 0) || (strcmp(doption, "oldorder")
779 warnx("NOTE: newsyslog always uses 'neworder'.");
780 return (1); /* successfully parsed */
783 warnx("Unknown -D (debug) option: '%s'", doption);
784 return (0); /* failure */
792 "usage: newsyslog [-CFNPnrsv] [-a directory] [-d directory] [-f config_file]\n"
793 " [-S pidfile] [-t timefmt] [[-R tagname] file ...]\n");
798 * Parse a configuration file and return a linked list of all the logs
799 * which should be processed.
801 static struct cflist *
802 get_worklist(char **files)
806 struct cflist *cmdlist, *filelist, *globlist;
807 struct conf_entry *defconf, *dupent, *ent;
808 struct ilist inclist;
809 struct include_entry *inc;
813 STAILQ_INIT(&inclist);
815 filelist = malloc(sizeof(struct cflist));
816 if (filelist == NULL)
817 err(1, "malloc of filelist");
818 STAILQ_INIT(filelist);
819 globlist = malloc(sizeof(struct cflist));
820 if (globlist == NULL)
821 err(1, "malloc of globlist");
822 STAILQ_INIT(globlist);
824 inc = malloc(sizeof(struct include_entry));
826 err(1, "malloc of inc");
828 if (inc->file == NULL)
829 inc->file = _PATH_CONF;
830 STAILQ_INSERT_TAIL(&inclist, inc, inc_nextp);
832 STAILQ_FOREACH(inc, &inclist, inc_nextp) {
833 if (strcmp(inc->file, "-") != 0)
834 f = fopen(inc->file, "r");
837 inc->file = "<stdin>";
840 err(1, "%s", inc->file);
843 printf("Processing %s\n", inc->file);
844 parse_file(f, filelist, globlist, &defconf, &inclist);
849 * All config-file information has been read in and turned into
850 * a filelist and a globlist. If there were no specific files
851 * given on the run command, then the only thing left to do is to
852 * call a routine which finds all files matched by the globlist
853 * and adds them to the filelist. Then return the worklist.
855 if (*files == NULL) {
856 expand_globs(filelist, globlist);
857 free_clist(globlist);
864 * If newsyslog was given a specific list of files to process,
865 * it may be that some of those files were not listed in any
866 * config file. Those unlisted files should get the default
867 * rotation action. First, create the default-rotation action
868 * if none was found in a system config file.
870 if (defconf == NULL) {
871 defconf = init_entry(DEFAULT_MARKER, NULL);
872 defconf->numlogs = 3;
873 defconf->trsize = 50;
874 defconf->permissions = S_IRUSR|S_IWUSR;
878 * If newsyslog was run with a list of specific filenames,
879 * then create a new worklist which has only those files in
880 * it, picking up the rotation-rules for those files from
881 * the original filelist.
883 * XXX - Note that this will copy multiple rules for a single
884 * logfile, if multiple entries are an exact match for
885 * that file. That matches the historic behavior, but do
886 * we want to continue to allow it? If so, it should
887 * probably be handled more intelligently.
889 cmdlist = malloc(sizeof(struct cflist));
891 err(1, "malloc of cmdlist");
892 STAILQ_INIT(cmdlist);
894 for (given = files; *given; ++given) {
896 * First try to find exact-matches for this given file.
899 STAILQ_FOREACH(ent, filelist, cf_nextp) {
900 if (strcmp(ent->log, *given) == 0) {
902 dupent = init_entry(*given, ent);
903 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
908 printf("\t+ Matched entry %s\n", *given);
913 * There was no exact-match for this given file, so look
914 * for a "glob" entry which does match.
918 printf("\t+ Checking globs for %s\n", *given);
919 STAILQ_FOREACH(ent, globlist, cf_nextp) {
920 fnres = fnmatch(ent->log, *given, FNM_PATHNAME);
922 printf("\t+ = %d for pattern %s\n", fnres,
926 dupent = init_entry(*given, ent);
927 /* This new entry is not a glob! */
928 dupent->flags &= ~CE_GLOB;
929 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
930 /* Only allow a match to one glob-entry */
936 printf("\t+ Matched %s via %s\n", *given,
942 * This given file was not found in any config file, so
943 * add a worklist item based on the default entry.
946 printf("\t+ No entry matched %s (will use %s)\n",
947 *given, DEFAULT_MARKER);
948 dupent = init_entry(*given, defconf);
949 /* Mark that it was *not* found in a config file */
951 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
955 * Free all the entries in the original work list, the list of
956 * glob entries, and the default entry.
958 free_clist(filelist);
959 free_clist(globlist);
962 /* And finally, return a worklist which matches the given files. */
967 * Expand the list of entries with filename patterns, and add all files
968 * which match those glob-entries onto the worklist.
971 expand_globs(struct cflist *work_p, struct cflist *glob_p)
976 struct conf_entry *dupent, *ent, *globent;
981 * The worklist contains all fully-specified (non-GLOB) names.
983 * Now expand the list of filename-pattern (GLOB) entries into
984 * a second list, which (by definition) will only match files
985 * that already exist. Do not add a glob-related entry for any
986 * file which already exists in the fully-specified list.
988 STAILQ_FOREACH(globent, glob_p, cf_nextp) {
989 gres = glob(globent->log, GLOB_NOCHECK, NULL, &pglob);
991 warn("cannot expand pattern (%d): %s", gres,
997 printf("\t+ Expanding pattern %s\n", globent->log);
998 for (i = 0; i < pglob.gl_matchc; i++) {
999 mfname = pglob.gl_pathv[i];
1001 /* See if this file already has a specific entry. */
1003 STAILQ_FOREACH(ent, work_p, cf_nextp) {
1004 if (strcmp(mfname, ent->log) == 0) {
1012 /* Make sure the named matched is a file. */
1013 gres = lstat(mfname, &st_fm);
1015 /* Error on a file that glob() matched?!? */
1016 warn("Skipping %s - lstat() error", mfname);
1019 if (!S_ISREG(st_fm.st_mode)) {
1020 /* We only rotate files! */
1022 printf("\t+ . skipping %s (!file)\n",
1028 printf("\t+ . add file %s\n", mfname);
1029 dupent = init_entry(mfname, globent);
1030 /* This new entry is not a glob! */
1031 dupent->flags &= ~CE_GLOB;
1033 /* Add to the worklist. */
1034 STAILQ_INSERT_TAIL(work_p, dupent, cf_nextp);
1038 printf("\t+ Done with pattern %s\n", globent->log);
1043 * Parse a configuration file and update a linked list of all the logs to
1047 parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
1048 struct conf_entry **defconf_p, struct ilist *inclist)
1050 char line[BUFSIZ], *parse, *q;
1051 char *cp, *errline, *group;
1052 struct conf_entry *working;
1056 int eol, ptm_opts, res, special;
1060 while (fgets(line, BUFSIZ, cf)) {
1061 if ((line[0] == '\n') || (line[0] == '#') ||
1062 (strlen(line) == 0))
1064 if (errline != NULL)
1066 errline = strdup(line);
1067 for (cp = line + 1; *cp != '\0'; cp++) {
1070 if (*(cp - 1) == '\\') {
1079 q = parse = missing_field(sob(line), errline);
1082 warnx("malformed line (missing fields):\n%s",
1089 * Allow people to set debug options via the config file.
1090 * (NOTE: debug options are undocumented, and may disappear
1091 * at any time, etc).
1093 if (strcasecmp(DEBUG_MARKER, q) == 0) {
1094 q = parse = missing_field(sob(parse + 1), errline);
1097 warnx("debug line specifies no option:\n%s",
1104 } else if (strcasecmp(INCLUDE_MARKER, q) == 0) {
1106 printf("Found: %s", errline);
1107 q = parse = missing_field(sob(parse + 1), errline);
1110 warnx("include line missing argument:\n%s",
1118 res = glob(q, GLOB_NOCHECK, NULL, &pglob);
1120 warn("cannot expand pattern (%d): %s",
1126 printf("\t+ Expanding pattern %s\n", q);
1128 for (i = 0; i < pglob.gl_matchc; i++)
1129 add_to_queue(pglob.gl_pathv[i],
1133 add_to_queue(q, inclist);
1137 #define badline(msg, ...) do { \
1138 warnx(msg, __VA_ARGS__); \
1143 working = init_entry(q, NULL);
1144 if (strcasecmp(DEFAULT_MARKER, q) == 0) {
1146 if (*defconf_p != NULL)
1147 badline("Ignoring duplicate entry for %s!", q);
1148 *defconf_p = working;
1151 q = parse = missing_field(sob(parse + 1), errline);
1154 badline("malformed line (missing fields):\n%s",
1157 if ((group = strchr(q, ':')) != NULL ||
1158 (group = strrchr(q, '.')) != NULL) {
1161 if (!(isnumberstr(q))) {
1162 if ((pwd = getpwnam(q)) == NULL)
1164 "error in config file; unknown user:\n%s",
1166 working->uid = pwd->pw_uid;
1168 working->uid = atoi(q);
1170 working->uid = (uid_t)-1;
1174 if (!(isnumberstr(q))) {
1175 if ((grp = getgrnam(q)) == NULL)
1177 "error in config file; unknown group:\n%s",
1179 working->gid = grp->gr_gid;
1181 working->gid = atoi(q);
1183 working->gid = (gid_t)-1;
1185 q = parse = missing_field(sob(parse + 1), errline);
1188 badline("malformed line (missing fields):\n%s",
1192 working->uid = (uid_t)-1;
1193 working->gid = (gid_t)-1;
1196 if (!sscanf(q, "%o", &working->permissions))
1197 badline("error in config file; bad permissions:\n%s",
1199 if ((working->permissions & ~DEFFILEMODE) != 0) {
1200 warnx("File mode bits 0%o changed to 0%o in line:\n%s",
1201 working->permissions,
1202 working->permissions & DEFFILEMODE, errline);
1203 working->permissions &= DEFFILEMODE;
1206 q = parse = missing_field(sob(parse + 1), errline);
1209 badline("malformed line (missing fields):\n%s",
1212 if (!sscanf(q, "%d", &working->numlogs) || working->numlogs < 0)
1213 badline("error in config file; bad value for count of logs to save:\n%s",
1216 q = parse = missing_field(sob(parse + 1), errline);
1219 badline("malformed line (missing fields):\n%s",
1223 working->trsize = atoi(q);
1224 else if (strcmp(q, "*") == 0)
1225 working->trsize = -1;
1227 warnx("Invalid value of '%s' for 'size' in line:\n%s",
1229 working->trsize = -1;
1233 working->compress = COMPRESS_NONE;
1234 q = parse = missing_field(sob(parse + 1), errline);
1242 ul = strtoul(q, &ep, 10);
1245 else if (*ep == '*')
1246 working->hours = -1;
1247 else if (ul > INT_MAX)
1248 badline("interval is too large:\n%s", errline);
1250 working->hours = ul;
1252 if (*ep == '\0' || strcmp(ep, "*") == 0)
1254 if (*ep != '@' && *ep != '$')
1255 badline("malformed interval/at:\n%s", errline);
1257 working->flags |= CE_TRIMAT;
1258 working->trim_at = ptime_init(NULL);
1259 ptm_opts = PTM_PARSE_ISO8601;
1261 ptm_opts = PTM_PARSE_DWM;
1262 ptm_opts |= PTM_PARSE_MATCHDOM;
1263 res = ptime_relparse(working->trim_at, ptm_opts,
1264 ptimeget_secs(timenow), ep + 1);
1266 badline("nonexistent time for 'at' value:\n%s",
1269 badline("malformed 'at' value:\n%s", errline);
1276 q = parse = sob(parse + 1); /* Optional field */
1283 for (; q && *q && !isspacech(*q); q++) {
1284 switch (tolowerch(*q)) {
1286 working->flags |= CE_BINARY;
1289 working->flags |= CE_CREATE;
1292 working->flags |= CE_NODUMP;
1295 working->flags |= CE_GLOB;
1298 working->compress = COMPRESS_BZIP2;
1301 working->flags |= CE_NOSIGNAL;
1304 working->flags |= CE_PLAIN0;
1307 working->flags |= CE_PID2CMD;
1310 working->flags |= CE_RFC5424;
1313 working->flags |= CE_SIGNALGROUP;
1316 /* Deprecated flag - keep for compatibility purposes */
1319 working->compress = COMPRESS_XZ;
1322 working->compress = COMPRESS_ZSTD;
1325 working->compress = COMPRESS_GZIP;
1329 case 'f': /* Used by OpenBSD for "CE_FOLLOW" */
1330 case 'm': /* Used by OpenBSD for "CE_MONITOR" */
1332 badline("illegal flag in config file -- %c",
1340 q = parse = sob(parse + 1); /* Optional field */
1347 working->pid_cmd_file = NULL;
1350 working->pid_cmd_file = strdup(q);
1351 else if (isalnum(*q))
1355 "illegal pid file or signal in config file:\n%s",
1362 q = parse = sob(parse + 1); /* Optional field */
1367 working->sig = SIGHUP;
1370 working->sig = parse_signal(q);
1371 if (working->sig < 1 || working->sig >= sys_nsig) {
1373 "illegal signal in config file:\n%s",
1379 * Finish figuring out what pid-file to use (if any) in
1380 * later processing if this logfile needs to be rotated.
1382 if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) {
1384 * This config-entry specified 'n' for nosignal,
1385 * see if it also specified an explicit pid_cmd_file.
1386 * This would be a pretty pointless combination.
1388 if (working->pid_cmd_file != NULL) {
1389 warnx("Ignoring '%s' because flag 'n' was specified in line:\n%s",
1390 working->pid_cmd_file, errline);
1391 free(working->pid_cmd_file);
1392 working->pid_cmd_file = NULL;
1394 } else if (working->pid_cmd_file == NULL) {
1396 * This entry did not specify the 'n' flag, which
1397 * means it should signal syslogd unless it had
1398 * specified some other pid-file (and obviously the
1399 * syslog pid-file will not be for a process-group).
1400 * Also, we should only try to notify syslog if we
1403 if (working->flags & CE_SIGNALGROUP) {
1404 warnx("Ignoring flag 'U' in line:\n%s",
1406 working->flags &= ~CE_SIGNALGROUP;
1409 working->pid_cmd_file = strdup(path_syslogpid);
1413 * Add this entry to the appropriate list of entries, unless
1414 * it was some kind of special entry (eg: <default>).
1417 ; /* Do not add to any list */
1418 } else if (working->flags & CE_GLOB) {
1419 STAILQ_INSERT_TAIL(glob_p, working, cf_nextp);
1421 STAILQ_INSERT_TAIL(work_p, working, cf_nextp);
1425 free_entry(working);
1427 } /* while (fgets(line, BUFSIZ, cf)) */
1428 if (errline != NULL)
1433 missing_field(char *p, char *errline)
1437 errx(1, "missing field in config file:\n%s", errline);
1442 * In our sort we return it in the reverse of what qsort normally
1443 * would do, as we want the newest files first. If we have two
1444 * entries with the same time we don't really care about order.
1446 * Support function for qsort() in delete_oldest_timelog().
1449 oldlog_entry_compare(const void *a, const void *b)
1451 const struct oldlog_entry *ola = a, *olb = b;
1453 if (ola->t > olb->t)
1455 else if (ola->t < olb->t)
1462 * Check whether the file corresponding to dp is an archive of the logfile
1463 * logfname, based on the timefnamefmt format string. Return true and fill out
1464 * tm if this is the case; otherwise return false.
1467 validate_old_timelog(int fd, const struct dirent *dp, const char *logfname,
1471 size_t logfname_len;
1475 logfname_len = strlen(logfname);
1477 if (dp->d_type != DT_REG) {
1479 * Some filesystems (e.g. NFS) don't fill out the d_type field
1480 * and leave it set to DT_UNKNOWN; in this case we must obtain
1481 * the file type ourselves.
1483 if (dp->d_type != DT_UNKNOWN ||
1484 fstatat(fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) != 0 ||
1485 !S_ISREG(sb.st_mode))
1488 /* Ignore everything but files with our logfile prefix. */
1489 if (strncmp(dp->d_name, logfname, logfname_len) != 0)
1491 /* Ignore the actual non-rotated logfile. */
1492 if (dp->d_namlen == logfname_len)
1496 * Make sure we created have found a logfile, so the
1497 * postfix is valid, IE format is: '.<time>(.[bgx]z)?'.
1499 if (dp->d_name[logfname_len] != '.') {
1501 printf("Ignoring %s which has unexpected "
1502 "extension '%s'\n", dp->d_name,
1503 &dp->d_name[logfname_len]);
1506 memset(tm, 0, sizeof(*tm));
1507 if ((s = strptime(&dp->d_name[logfname_len + 1],
1508 timefnamefmt, tm)) == NULL) {
1510 * We could special case "old" sequentially named logfiles here,
1511 * but we do not as that would require special handling to
1512 * decide which one was the oldest compared to "new" time based
1516 printf("Ignoring %s which does not "
1517 "match time format\n", dp->d_name);
1521 for (c = 0; c < COMPRESS_TYPES; c++)
1522 if (strcmp(s, compress_type[c].suffix) == 0)
1527 printf("Ignoring %s which has unexpected extension '%s'\n",
1534 * Delete the oldest logfiles, when using time based filenames.
1537 delete_oldest_timelog(const struct conf_entry *ent, const char *archive_dir)
1539 char *basebuf, *dirbuf, errbuf[80];
1540 const char *base, *dir;
1541 int dir_fd, i, logcnt, max_logcnt;
1542 struct oldlog_entry *oldlogs;
1547 oldlogs = malloc(MAX_OLDLOGS * sizeof(struct oldlog_entry));
1548 max_logcnt = MAX_OLDLOGS;
1551 if (archive_dir != NULL && archive_dir[0] != '\0') {
1555 if ((dirbuf = strdup(ent->log)) == NULL)
1557 dir = dirname(dirbuf);
1560 if ((basebuf = strdup(ent->log)) == NULL)
1562 base = basename(basebuf);
1563 if (strcmp(base, "/") == 0)
1564 errx(1, "Invalid log filename - became '/'");
1567 printf("Searching for old logs in %s\n", dir);
1569 /* First we create a 'list' of all archived logfiles */
1570 if ((dirp = opendir(dir)) == NULL)
1571 err(1, "Cannot open log directory '%s'", dir);
1572 dir_fd = dirfd(dirp);
1573 while ((dp = readdir(dirp)) != NULL) {
1574 if (validate_old_timelog(dir_fd, dp, base, &tm) == 0)
1578 * We should now have old an old rotated logfile, so
1579 * add it to the 'list'.
1581 if ((oldlogs[logcnt].t = timegm(&tm)) == -1)
1582 err(1, "Could not convert time string to time value");
1583 if ((oldlogs[logcnt].fname = strdup(dp->d_name)) == NULL)
1588 * It is very unlikely we ever run out of space in the
1589 * logfile array from the default size, but lets
1590 * handle it anyway...
1592 if (logcnt >= max_logcnt) {
1594 /* Detect integer overflow */
1595 if (max_logcnt < logcnt)
1596 errx(1, "Too many old logfiles found");
1597 oldlogs = realloc(oldlogs,
1598 max_logcnt * sizeof(struct oldlog_entry));
1599 if (oldlogs == NULL)
1600 err(1, "realloc()");
1604 /* Second, if needed we delete oldest archived logfiles */
1605 if (logcnt > 0 && logcnt >= ent->numlogs && ent->numlogs > 1) {
1606 oldlogs = realloc(oldlogs, logcnt *
1607 sizeof(struct oldlog_entry));
1608 if (oldlogs == NULL)
1609 err(1, "realloc()");
1612 * We now sort the logs in the order of newest to
1613 * oldest. That way we can simply skip over the
1614 * number of records we want to keep.
1616 qsort(oldlogs, logcnt, sizeof(struct oldlog_entry),
1617 oldlog_entry_compare);
1618 for (i = ent->numlogs - 1; i < logcnt; i++) {
1620 printf("\trm -f %s/%s\n", dir,
1622 else if (unlinkat(dir_fd, oldlogs[i].fname, 0) != 0) {
1623 snprintf(errbuf, sizeof(errbuf),
1624 "Could not delete old logfile '%s'",
1629 } else if (verbose > 1)
1630 printf("No old logs to delete for logfile %s\n", ent->log);
1632 /* Third, cleanup */
1634 for (i = 0; i < logcnt; i++) {
1635 assert(oldlogs[i].fname != NULL);
1636 free(oldlogs[i].fname);
1644 * Generate a log filename, when using classic filenames.
1647 gen_classiclog_fname(char *fname, size_t fname_sz, const char *archive_dir,
1648 const char *namepart, int numlogs_c)
1651 if (archive_dir[0] != '\0')
1652 (void) snprintf(fname, fname_sz, "%s/%s.%d", archive_dir,
1653 namepart, numlogs_c);
1655 (void) snprintf(fname, fname_sz, "%s.%d", namepart, numlogs_c);
1659 * Delete a rotated logfile, when using classic filenames.
1662 delete_classiclog(const char *archive_dir, const char *namepart, int numlog_c)
1664 char file1[MAXPATHLEN], zfile1[MAXPATHLEN];
1667 gen_classiclog_fname(file1, sizeof(file1), archive_dir, namepart,
1670 for (c = 0; c < COMPRESS_TYPES; c++) {
1671 (void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1672 compress_type[c].suffix);
1674 printf("\trm -f %s\n", zfile1);
1676 (void) unlink(zfile1);
1681 * Only add to the queue if the file hasn't already been added. This is
1682 * done to prevent circular include loops.
1685 add_to_queue(const char *fname, struct ilist *inclist)
1687 struct include_entry *inc;
1689 STAILQ_FOREACH(inc, inclist, inc_nextp) {
1690 if (strcmp(fname, inc->file) == 0) {
1691 warnx("duplicate include detected: %s", fname);
1696 inc = malloc(sizeof(struct include_entry));
1698 err(1, "malloc of inc");
1699 inc->file = strdup(fname);
1702 printf("\t+ Adding %s to the processing queue.\n", fname);
1704 STAILQ_INSERT_TAIL(inclist, inc, inc_nextp);
1708 * Search for logfile and return its compression suffix (if supported)
1709 * The suffix detection is first-match in the order of compress_types
1711 * Note: if logfile without suffix exists (uncompressed, COMPRESS_NONE)
1712 * a zero-length string is returned
1715 get_logfile_suffix(const char *logfile)
1718 char zfile[MAXPATHLEN];
1721 for (c = 0; c < COMPRESS_TYPES; c++) {
1722 (void) strlcpy(zfile, logfile, MAXPATHLEN);
1723 (void) strlcat(zfile, compress_type[c].suffix, MAXPATHLEN);
1724 if (lstat(zfile, &st) == 0)
1725 return (compress_type[c].suffix);
1731 do_rotate(const struct conf_entry *ent)
1733 char dirpart[MAXPATHLEN], namepart[MAXPATHLEN];
1734 char file1[MAXPATHLEN], file2[MAXPATHLEN];
1735 char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN];
1736 const char *logfile_suffix;
1737 char datetimestr[30];
1738 int flags, numlogs_c;
1739 fk_entry free_or_keep;
1740 struct sigwork_entry *swork;
1746 free_or_keep = FREE_ENT;
1751 /* build complete name of archive directory into dirpart */
1752 if (*archdirname == '/') { /* absolute */
1753 strlcpy(dirpart, archdirname, sizeof(dirpart));
1754 } else { /* relative */
1755 /* get directory part of logfile */
1756 strlcpy(dirpart, ent->log, sizeof(dirpart));
1757 if ((p = strrchr(dirpart, '/')) == NULL)
1761 strlcat(dirpart, archdirname, sizeof(dirpart));
1764 /* check if archive directory exists, if not, create it */
1765 if (lstat(dirpart, &st))
1766 createdir(ent, dirpart);
1768 /* get filename part of logfile */
1769 if ((p = strrchr(ent->log, '/')) == NULL)
1770 strlcpy(namepart, ent->log, sizeof(namepart));
1772 strlcpy(namepart, p + 1, sizeof(namepart));
1775 * Tell utility functions we are not using an archive
1779 strlcpy(namepart, ent->log, sizeof(namepart));
1782 /* Delete old logs */
1783 if (timefnamefmt != NULL)
1784 delete_oldest_timelog(ent, dirpart);
1787 * Handle cleaning up after legacy newsyslog where we
1788 * kept ent->numlogs + 1 files. This code can go away
1789 * at some point in the future.
1791 delete_classiclog(dirpart, namepart, ent->numlogs);
1793 if (ent->numlogs > 0)
1794 delete_classiclog(dirpart, namepart, ent->numlogs - 1);
1798 if (timefnamefmt != NULL) {
1799 /* If time functions fails we can't really do any sensible */
1800 if (time(&now) == (time_t)-1 ||
1801 localtime_r(&now, &tm) == NULL)
1802 bzero(&tm, sizeof(tm));
1804 strftime(datetimestr, sizeof(datetimestr), timefnamefmt, &tm);
1806 (void) snprintf(file1, sizeof(file1), "%s/%s.%s",
1807 dirpart, namepart, datetimestr);
1809 (void) snprintf(file1, sizeof(file1), "%s.%s",
1810 ent->log, datetimestr);
1812 /* Don't run the code to move down logs */
1815 gen_classiclog_fname(file1, sizeof(file1), dirpart, namepart,
1817 numlogs_c = ent->numlogs - 2; /* copy for countdown */
1820 /* Move down log files */
1821 for (; numlogs_c >= 0; numlogs_c--) {
1822 (void) strlcpy(file2, file1, sizeof(file2));
1824 gen_classiclog_fname(file1, sizeof(file1), dirpart, namepart,
1827 logfile_suffix = get_logfile_suffix(file1);
1828 if (logfile_suffix == NULL)
1830 (void) strlcpy(zfile1, file1, MAXPATHLEN);
1831 (void) strlcpy(zfile2, file2, MAXPATHLEN);
1832 (void) strlcat(zfile1, logfile_suffix, MAXPATHLEN);
1833 (void) strlcat(zfile2, logfile_suffix, MAXPATHLEN);
1836 printf("\tmv %s %s\n", zfile1, zfile2);
1838 /* XXX - Ought to be checking for failure! */
1839 (void)rename(zfile1, zfile2);
1841 change_attrs(zfile2, ent);
1842 if (ent->compress && strlen(logfile_suffix) == 0) {
1843 /* compress old rotation */
1844 struct zipwork_entry *zwork;
1847 sz = sizeof(*zwork) + strlen(zfile2) + 1;
1848 zwork = calloc(1, sz);
1852 zwork->zw_conf = ent;
1853 zwork->zw_fsize = sizefile(zfile2);
1854 strcpy(zwork->zw_fname, zfile2);
1860 if (ent->numlogs > 0) {
1863 * Note that savelog() may succeed with using link()
1864 * for the archtodir case, but there is no good way
1865 * of knowing if it will when doing "noaction", so
1866 * here we claim that it will have to do a copy...
1869 printf("\tcp %s %s\n", ent->log, file1);
1871 printf("\tln %s %s\n", ent->log, file1);
1872 printf("\ttouch %s\t\t"
1873 "# Update mtime for 'when'-interval processing\n",
1876 if (!(flags & CE_BINARY)) {
1877 /* Report the trimming to the old log */
1878 log_trim(ent->log, ent);
1880 savelog(ent->log, file1);
1882 * Interval-based rotations are done using the mtime of
1883 * the most recently archived log, so make sure it gets
1884 * updated during a rotation.
1886 utimes(file1, NULL);
1888 change_attrs(file1, ent);
1891 /* Create the new log file and move it into place */
1893 printf("Start new log...\n");
1897 * Save all signalling and file-compression to be done after log
1898 * files from all entries have been rotated. This way any one
1899 * process will not be sent the same signal multiple times when
1900 * multiple log files had to be rotated.
1903 if (ent->pid_cmd_file != NULL)
1904 swork = save_sigwork(ent);
1905 if (ent->numlogs > 0 && ent->compress > COMPRESS_NONE) {
1906 if (!(ent->flags & CE_PLAIN0) ||
1907 strcmp(&file1[strlen(file1) - 2], ".0") != 0) {
1909 * The zipwork_entry will include a pointer to this
1910 * conf_entry, so the conf_entry should not be freed.
1912 free_or_keep = KEEP_ENT;
1913 save_zipwork(ent, swork, ent->fsize, file1);
1917 return (free_or_keep);
1921 do_sigwork(struct sigwork_entry *swork)
1923 struct sigwork_entry *nextsig;
1927 if (swork->sw_runcmd == 0 && (!(swork->sw_pidok) || swork->sw_pid == 0))
1928 return; /* no work to do... */
1931 * If nosignal (-s) was specified, then do not signal any process.
1932 * Note that a nosignal request triggers a warning message if the
1933 * rotated logfile needs to be compressed, *unless* -R was also
1934 * specified. We assume that an `-sR' request came from a process
1935 * which writes to the logfile, and as such, we assume that process
1936 * has already made sure the logfile is not presently in use. This
1937 * just sets swork->sw_pidok to a special value, and do_zipwork
1938 * will print any necessary warning(s).
1942 swork->sw_pidok = -1;
1947 * Compute the pause between consecutive signals. Use a longer
1948 * sleep time if we will be sending two signals to the same
1949 * daemon or process-group.
1952 nextsig = SLIST_NEXT(swork, sw_nextp);
1953 if (nextsig != NULL) {
1954 if (swork->sw_pid == nextsig->sw_pid)
1961 if (swork->sw_runcmd)
1962 printf("\tsh -c '%s %d'\n", swork->sw_fname,
1965 printf("\tkill -%d %d \t\t# %s\n", swork->sw_signum,
1966 (int)swork->sw_pid, swork->sw_fname);
1968 printf("\tsleep %d\n", secs);
1973 if (swork->sw_runcmd) {
1974 asprintf(&tmp, "%s %d", swork->sw_fname, swork->sw_signum);
1976 warn("can't allocate memory to run %s",
1981 printf("Run command: %s\n", tmp);
1984 warnx("%s: returned non-zero exit code: %d",
1991 kres = kill(swork->sw_pid, swork->sw_signum);
1994 * Assume that "no such process" (ESRCH) is something
1995 * to warn about, but is not an error. Presumably the
1996 * process which writes to the rotated log file(s) is
1997 * gone, in which case we should have no problem with
1998 * compressing the rotated log file(s).
2001 swork->sw_pidok = 0;
2002 warn("can't notify %s, pid %d = %s", swork->sw_pidtype,
2003 (int)swork->sw_pid, swork->sw_fname);
2006 printf("Notified %s pid %d = %s\n", swork->sw_pidtype,
2007 (int)swork->sw_pid, swork->sw_fname);
2010 printf("Pause %d second(s) between signals\n",
2018 do_zipwork(struct zipwork_entry *zwork)
2020 const struct compress_types *ct;
2021 struct sbuf *command;
2023 int c, errsav, fcount, zstatus;
2024 const char **args, *pgm_name, *pgm_path;
2027 assert(zwork != NULL);
2028 assert(zwork->zw_conf != NULL);
2029 assert(zwork->zw_conf->compress > COMPRESS_NONE);
2030 assert(zwork->zw_conf->compress < COMPRESS_TYPES);
2032 if (zwork->zw_swork != NULL && zwork->zw_swork->sw_runcmd == 0 &&
2033 zwork->zw_swork->sw_pidok <= 0) {
2035 "log %s not compressed because daemon(s) not notified",
2037 change_attrs(zwork->zw_fname, zwork->zw_conf);
2041 ct = &compress_type[zwork->zw_conf->compress];
2044 * execv will be called with the array [ program, flags ... ,
2045 * filename, NULL ] so allocate nflags+3 elements for the array.
2047 args = calloc(ct->nflags + 3, sizeof(*args));
2051 pgm_path = ct->path;
2052 pgm_name = strrchr(pgm_path, '/');
2053 if (pgm_name == NULL)
2054 pgm_name = pgm_path;
2058 /* Build the argument array. */
2060 for (c = 0; c < ct->nflags; c++)
2061 args[c + 1] = ct->flags[c];
2062 args[c + 1] = zwork->zw_fname;
2064 /* Also create a space-delimited version if we need to print it. */
2065 if ((command = sbuf_new_auto()) == NULL)
2066 errx(1, "sbuf_new");
2067 sbuf_cpy(command, pgm_path);
2068 for (c = 1; args[c] != NULL; c++) {
2069 sbuf_putc(command, ' ');
2070 sbuf_cat(command, args[c]);
2072 if (sbuf_finish(command) == -1)
2073 err(1, "sbuf_finish");
2075 /* Determine the filename of the compressed file. */
2076 asprintf(&zresult, "%s%s", zwork->zw_fname, ct->suffix);
2077 if (zresult == NULL)
2078 errx(1, "asprintf");
2081 printf("Executing: %s\n", sbuf_data(command));
2084 printf("\t%s %s\n", pgm_name, zwork->zw_fname);
2085 change_attrs(zresult, zwork->zw_conf);
2091 while (pidzip < 0) {
2093 * The fork failed. If the failure was due to a temporary
2094 * problem, then wait a short time and try it again.
2097 warn("fork() for `%s %s'", pgm_name, zwork->zw_fname);
2098 if (errsav != EAGAIN || fcount > 5)
2099 errx(1, "Exiting...");
2105 /* The child process executes the compression command */
2106 execv(pgm_path, __DECONST(char *const*, args));
2107 err(1, "execv(`%s')", sbuf_data(command));
2110 wpid = waitpid(pidzip, &zstatus, 0);
2112 /* XXX - should this be a fatal error? */
2113 warn("%s: waitpid(%d)", pgm_path, pidzip);
2116 if (!WIFEXITED(zstatus)) {
2117 warnx("`%s' did not terminate normally", sbuf_data(command));
2120 if (WEXITSTATUS(zstatus)) {
2121 warnx("`%s' terminated with a non-zero status (%d)",
2122 sbuf_data(command), WEXITSTATUS(zstatus));
2126 /* Compression was successful, set file attributes on the result. */
2127 change_attrs(zresult, zwork->zw_conf);
2130 sbuf_delete(command);
2136 * Save information on any process we need to signal. Any single
2137 * process may need to be sent different signal-values for different
2138 * log files, but usually a single signal-value will cause the process
2139 * to close and re-open all of its log files.
2141 static struct sigwork_entry *
2142 save_sigwork(const struct conf_entry *ent)
2144 struct sigwork_entry *sprev, *stmp;
2150 SLIST_FOREACH(stmp, &swhead, sw_nextp) {
2151 ndiff = strcmp(ent->pid_cmd_file, stmp->sw_fname);
2155 if (ent->sig == stmp->sw_signum)
2157 if (ent->sig > stmp->sw_signum) {
2164 if (stmp != NULL && ndiff == 0)
2167 tmpsiz = sizeof(struct sigwork_entry) + strlen(ent->pid_cmd_file) + 1;
2168 stmp = malloc(tmpsiz);
2170 stmp->sw_runcmd = 0;
2171 /* If this is a command to run we just set the flag and run command */
2172 if (ent->flags & CE_PID2CMD) {
2175 stmp->sw_runcmd = 1;
2177 set_swpid(stmp, ent);
2179 stmp->sw_signum = ent->sig;
2180 strcpy(stmp->sw_fname, ent->pid_cmd_file);
2182 SLIST_INSERT_HEAD(&swhead, stmp, sw_nextp);
2184 SLIST_INSERT_AFTER(sprev, stmp, sw_nextp);
2189 * Save information on any file we need to compress. We may see the same
2190 * file multiple times, so check the full list to avoid duplicates. The
2191 * list itself is sorted smallest-to-largest, because that's the order we
2192 * want to compress the files. If the partition is very low on disk space,
2193 * then the smallest files are the most likely to compress, and compressing
2194 * them first will free up more space for the larger files.
2196 static struct zipwork_entry *
2197 save_zipwork(const struct conf_entry *ent, const struct sigwork_entry *swork,
2198 int zsize, const char *zipfname)
2200 struct zipwork_entry *zprev, *ztmp;
2204 /* Compute the size if the caller did not know it. */
2206 zsize = sizefile(zipfname);
2210 SLIST_FOREACH(ztmp, &zwhead, zw_nextp) {
2211 ndiff = strcmp(zipfname, ztmp->zw_fname);
2214 if (zsize > ztmp->zw_fsize)
2217 if (ztmp != NULL && ndiff == 0)
2220 tmpsiz = sizeof(struct zipwork_entry) + strlen(zipfname) + 1;
2221 ztmp = malloc(tmpsiz);
2222 ztmp->zw_conf = ent;
2223 ztmp->zw_swork = swork;
2224 ztmp->zw_fsize = zsize;
2225 strcpy(ztmp->zw_fname, zipfname);
2227 SLIST_INSERT_HEAD(&zwhead, ztmp, zw_nextp);
2229 SLIST_INSERT_AFTER(zprev, ztmp, zw_nextp);
2233 /* Send a signal to the pid specified by pidfile */
2235 set_swpid(struct sigwork_entry *swork, const struct conf_entry *ent)
2238 long minok, maxok, rval;
2239 char *endp, *linep, line[BUFSIZ];
2243 swork->sw_pidok = 0;
2245 swork->sw_pidtype = "daemon";
2246 if (ent->flags & CE_SIGNALGROUP) {
2248 * If we are expected to signal a process-group when
2249 * rotating this logfile, then the value read in should
2250 * be the negative of a valid process ID.
2254 swork->sw_pidtype = "process-group";
2257 f = fopen(ent->pid_cmd_file, "r");
2259 if (errno == ENOENT && enforcepid == 0) {
2261 * Warn if the PID file doesn't exist, but do
2262 * not consider it an error. Most likely it
2263 * means the process has been terminated,
2264 * so it should be safe to rotate any log
2265 * files that the process would have been using.
2267 swork->sw_pidok = 1;
2268 warnx("pid file doesn't exist: %s", ent->pid_cmd_file);
2270 warn("can't open pid file: %s", ent->pid_cmd_file);
2274 if (fgets(line, BUFSIZ, f) == NULL) {
2276 * Warn if the PID file is empty, but do not consider
2277 * it an error. Most likely it means the process has
2278 * has terminated, so it should be safe to rotate any
2279 * log files that the process would have been using.
2281 if (feof(f) && enforcepid == 0) {
2282 swork->sw_pidok = 1;
2283 warnx("pid/cmd file is empty: %s", ent->pid_cmd_file);
2285 warn("can't read from pid file: %s", ent->pid_cmd_file);
2293 while (*linep == ' ')
2295 rval = strtol(linep, &endp, 10);
2296 if (*endp != '\0' && !isspacech(*endp)) {
2297 warnx("pid file does not start with a valid number: %s",
2299 } else if (rval < minok || rval > maxok) {
2300 warnx("bad value '%ld' for process number in %s",
2301 rval, ent->pid_cmd_file);
2303 warnx("\t(expecting value between %ld and %ld)",
2306 swork->sw_pidok = 1;
2307 swork->sw_pid = rval;
2313 /* Log the fact that the logs were turned over */
2315 log_trim(const char *logname, const struct conf_entry *log_ent)
2320 if ((f = fopen(logname, "a")) == NULL)
2323 if (log_ent->def_cfg)
2324 xtra = " using <default> rule";
2325 if (log_ent->flags & CE_RFC5424) {
2326 if (log_ent->firstcreate) {
2327 fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s\n",
2328 LOG_MAKEPRI(LOG_USER, LOG_INFO),
2329 daytime_rfc5424, hostname, getpid(),
2330 "logfile first created", xtra);
2331 } else if (log_ent->r_reason != NULL) {
2332 fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s%s\n",
2333 LOG_MAKEPRI(LOG_USER, LOG_INFO),
2334 daytime_rfc5424, hostname, getpid(),
2335 "logfile turned over", log_ent->r_reason, xtra);
2337 fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s\n",
2338 LOG_MAKEPRI(LOG_USER, LOG_INFO),
2339 daytime_rfc5424, hostname, getpid(),
2340 "logfile turned over", xtra);
2343 if (log_ent->firstcreate)
2345 "%s %.*s newsyslog[%d]: logfile first created%s\n",
2346 daytime, (int)hostname_shortlen, hostname, getpid(),
2348 else if (log_ent->r_reason != NULL)
2350 "%s %.*s newsyslog[%d]: logfile turned over%s%s\n",
2351 daytime, (int)hostname_shortlen, hostname, getpid(),
2352 log_ent->r_reason, xtra);
2355 "%s %.*s newsyslog[%d]: logfile turned over%s\n",
2356 daytime, (int)hostname_shortlen, hostname, getpid(),
2359 if (fclose(f) == EOF)
2360 err(1, "log_trim: fclose");
2364 /* Return size in kilobytes of a file */
2366 sizefile(const char *file)
2370 if (stat(file, &sb) < 0)
2372 return (kbytes(sb.st_size));
2376 * Return the mtime of the most recent archive of the logfile, using timestamp
2380 mtime_old_timelog(const char *file)
2388 char *logfname, *logfnamebuf, *dir, *dirbuf;
2392 if ((dirbuf = strdup(file)) == NULL) {
2393 warn("strdup() of '%s'", file);
2396 dir = dirname(dirbuf);
2397 if ((logfnamebuf = strdup(file)) == NULL) {
2398 warn("strdup() of '%s'", file);
2402 logfname = basename(logfnamebuf);
2403 if (logfname[0] == '/') {
2404 warnx("Invalid log filename '%s'", logfname);
2408 if ((dirp = opendir(dir)) == NULL) {
2409 warn("Cannot open log directory '%s'", dir);
2412 dir_fd = dirfd(dirp);
2413 /* Open the archive dir and find the most recent archive of logfname. */
2414 while ((dp = readdir(dirp)) != NULL) {
2415 if (validate_old_timelog(dir_fd, dp, logfname, &tm) == 0)
2418 if (fstatat(dir_fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
2419 warn("Cannot stat '%s'", file);
2422 if (t < sb.st_mtime)
2433 /* Return the age in hours of the most recent archive of the logfile. */
2435 age_old_log(const char *file)
2438 const char *logfile_suffix;
2439 static unsigned int suffix_maxlen = 0;
2445 if (suffix_maxlen == 0) {
2446 for (c = 0; c < COMPRESS_TYPES; c++)
2447 suffix_maxlen = MAX(suffix_maxlen,
2448 strlen(compress_type[c].suffix));
2451 tmpsiz = MAXPATHLEN + sizeof(".0") + suffix_maxlen + 1;
2452 tmp = alloca(tmpsiz);
2457 /* build name of archive directory into tmp */
2458 if (*archdirname == '/') { /* absolute */
2459 strlcpy(tmp, archdirname, tmpsiz);
2460 } else { /* relative */
2461 /* get directory part of logfile */
2462 strlcpy(tmp, file, tmpsiz);
2463 if ((p = strrchr(tmp, '/')) == NULL)
2467 strlcat(tmp, archdirname, tmpsiz);
2470 strlcat(tmp, "/", tmpsiz);
2472 /* get filename part of logfile */
2473 if ((p = strrchr(file, '/')) == NULL)
2474 strlcat(tmp, file, tmpsiz);
2476 strlcat(tmp, p + 1, tmpsiz);
2478 (void) strlcpy(tmp, file, tmpsiz);
2481 if (timefnamefmt != NULL) {
2482 mtime = mtime_old_timelog(tmp);
2486 strlcat(tmp, ".0", tmpsiz);
2487 logfile_suffix = get_logfile_suffix(tmp);
2488 if (logfile_suffix == NULL)
2490 (void) strlcat(tmp, logfile_suffix, tmpsiz);
2491 if (stat(tmp, &sb) < 0)
2493 mtime = sb.st_mtime;
2496 return ((int)(ptimeget_secs(timenow) - mtime + 1800) / 3600);
2499 /* Skip Over Blanks */
2503 while (p && *p && isspace(*p))
2508 /* Skip Over Non-Blanks */
2512 while (p && *p && !isspace(*p))
2517 /* Check if string is actually a number */
2519 isnumberstr(const char *string)
2522 if (!isdigitch(*string++))
2528 /* Check if string contains a glob */
2530 isglobstr(const char *string)
2534 while ((chr = *string++)) {
2535 if (chr == '*' || chr == '?' || chr == '[')
2542 * Save the active log file under a new name. A link to the new name
2543 * is the quick-and-easy way to do this. If that fails (which it will
2544 * if the destination is on another partition), then make a copy of
2545 * the file to the new location.
2548 savelog(char *from, char *to)
2553 res = link(from, to);
2557 if ((src = fopen(from, "r")) == NULL)
2558 err(1, "can't fopen %s for reading", from);
2559 if ((dst = fopen(to, "w")) == NULL)
2560 err(1, "can't fopen %s for writing", to);
2562 while ((c = getc(src)) != EOF) {
2563 if ((putc(c, dst)) == EOF)
2564 err(1, "error writing to %s", to);
2568 err(1, "error reading from %s", from);
2569 if ((fclose(src)) != 0)
2570 err(1, "can't fclose %s", to);
2571 if ((fclose(dst)) != 0)
2572 err(1, "can't fclose %s", from);
2575 /* create one or more directory components of a path */
2577 createdir(const struct conf_entry *ent, char *dirpart)
2581 char mkdirpath[MAXPATHLEN];
2589 if (*s != '/' && *s != '\0')
2592 res = lstat(mkdirpath, &st);
2595 printf("\tmkdir %s\n", mkdirpath);
2597 res = mkdir(mkdirpath, 0755);
2599 err(1, "Error on mkdir(\"%s\") for -a",
2607 if (ent->firstcreate)
2608 printf("Created directory '%s' for new %s\n",
2611 printf("Created directory '%s' for -a\n", dirpart);
2616 * Create a new log file, destroying any currently-existing version
2617 * of the log file in the process. If the caller wants a backup copy
2618 * of the file to exist, they should call 'link(logfile,logbackup)'
2619 * before calling this routine.
2622 createlog(const struct conf_entry *ent)
2626 char *realfile, *slash, tempfile[MAXPATHLEN];
2629 realfile = ent->log;
2632 * If this log file is being created for the first time (-C option),
2633 * then it may also be true that the parent directory does not exist
2634 * yet. Check, and create that directory if it is missing.
2636 if (ent->firstcreate) {
2637 strlcpy(tempfile, realfile, sizeof(tempfile));
2638 slash = strrchr(tempfile, '/');
2639 if (slash != NULL) {
2641 failed = stat(tempfile, &st);
2642 if (failed && errno != ENOENT)
2643 err(1, "Error on stat(%s)", tempfile);
2645 createdir(ent, tempfile);
2646 else if (!S_ISDIR(st.st_mode))
2647 errx(1, "%s exists but is not a directory",
2653 * First create an unused filename, so it can be chown'ed and
2654 * chmod'ed before it is moved into the real location. mkstemp
2655 * will create the file mode=600 & owned by us. Note that all
2656 * temp files will have a suffix of '.z<something>'.
2658 strlcpy(tempfile, realfile, sizeof(tempfile));
2659 strlcat(tempfile, ".zXXXXXX", sizeof(tempfile));
2661 printf("\tmktemp %s\n", tempfile);
2663 fd = mkstemp(tempfile);
2665 err(1, "can't mkstemp logfile %s", tempfile);
2668 * Add status message to what will become the new log file.
2670 if (!(ent->flags & CE_BINARY)) {
2671 if (log_trim(tempfile, ent))
2672 err(1, "can't add status message to log");
2676 /* Change the owner/group, if we are supposed to */
2677 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2679 printf("\tchown %u:%u %s\n", ent->uid, ent->gid,
2682 failed = fchown(fd, ent->uid, ent->gid);
2684 err(1, "can't fchown temp file %s", tempfile);
2688 /* Turn on NODUMP if it was requested in the config-file. */
2689 if (ent->flags & CE_NODUMP) {
2691 printf("\tchflags nodump %s\n", tempfile);
2693 failed = fchflags(fd, UF_NODUMP);
2695 warn("log_trim: fchflags(NODUMP)");
2701 * Note that if the real logfile still exists, and if the call
2702 * to rename() fails, then "neither the old file nor the new
2703 * file shall be changed or created" (to quote the standard).
2704 * If the call succeeds, then the file will be replaced without
2705 * any window where some other process might find that the file
2707 * XXX - ? It may be that for some error conditions, we could
2708 * retry by first removing the realfile and then renaming.
2711 printf("\tchmod %o %s\n", ent->permissions, tempfile);
2712 printf("\tmv %s %s\n", tempfile, realfile);
2714 failed = fchmod(fd, ent->permissions);
2716 err(1, "can't fchmod temp file '%s'", tempfile);
2717 failed = rename(tempfile, realfile);
2719 err(1, "can't mv %s to %s", tempfile, realfile);
2727 * Change the attributes of a given filename to what was specified in
2728 * the newsyslog.conf entry. This routine is only called for files
2729 * that newsyslog expects that it has created, and thus it is a fatal
2730 * error if this routine finds that the file does not exist.
2733 change_attrs(const char *fname, const struct conf_entry *ent)
2738 printf("\tchmod %o %s\n", ent->permissions, fname);
2740 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
2741 printf("\tchown %u:%u %s\n",
2742 ent->uid, ent->gid, fname);
2744 if (ent->flags & CE_NODUMP)
2745 printf("\tchflags nodump %s\n", fname);
2749 failed = chmod(fname, ent->permissions);
2752 err(1, "chmod(%s) in change_attrs", fname);
2753 warn("change_attrs couldn't chmod(%s)", fname);
2756 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2757 failed = chown(fname, ent->uid, ent->gid);
2759 warn("can't chown %s", fname);
2762 if (ent->flags & CE_NODUMP) {
2763 failed = chflags(fname, UF_NODUMP);
2765 warn("can't chflags %s NODUMP", fname);
2770 * Parse a signal number or signal name. Returns the signal number parsed or -1
2774 parse_signal(const char *str)
2779 sig = strtonum(str, 1, sys_nsig - 1, &errstr);
2783 if (strncasecmp(str, "SIG", 3) == 0)
2786 for (i = 1; i < sys_nsig; i++) {
2787 if (strcasecmp(str, sys_signame[i]) == 0)