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 */
117 #define CE_NOEMPTY 0x2000 /* Do not rotate the file when its size */
119 #define MIN_PID 5 /* Don't touch pids lower than this */
120 #define MAX_PID 99999 /* was lower, see /usr/include/sys/proc.h */
122 #define kbytes(size) (((size) + 1023) >> 10)
124 #define DEFAULT_MARKER "<default>"
125 #define DEBUG_MARKER "<debug>"
126 #define INCLUDE_MARKER "<include>"
127 #define DEFAULT_TIMEFNAME_FMT "%Y%m%dT%H%M%S"
129 #define MAX_OLDLOGS 65536 /* Default maximum number of old logfiles */
131 struct compress_types {
132 const char *flag; /* Flag in configuration file */
133 const char *suffix; /* Compression suffix */
134 const char *path; /* Path to compression program */
135 const char **flags; /* Compression program flags */
136 int nflags; /* Program flags count */
139 static const char *gzip_flags[] = { "-f" };
140 #define bzip2_flags gzip_flags
141 #define xz_flags gzip_flags
142 static const char *zstd_flags[] = { "-q", "--rm" };
144 static const struct compress_types compress_type[COMPRESS_TYPES] = {
145 { "", "", "", NULL, 0 },
146 { "Z", ".gz", _PATH_GZIP, gzip_flags, nitems(gzip_flags) },
147 { "J", ".bz2", _PATH_BZIP2, bzip2_flags, nitems(bzip2_flags) },
148 { "X", ".xz", _PATH_XZ, xz_flags, nitems(xz_flags) },
149 { "Y", ".zst", _PATH_ZSTD, zstd_flags, nitems(zstd_flags) }
153 STAILQ_ENTRY(conf_entry) cf_nextp;
154 char *log; /* Name of the log */
155 char *pid_cmd_file; /* PID or command file */
156 char *r_reason; /* The reason this file is being rotated */
157 int firstcreate; /* Creating log for the first time (-C). */
158 int rotate; /* Non-zero if this file should be rotated */
159 int fsize; /* size found for the log file */
160 uid_t uid; /* Owner of log */
161 gid_t gid; /* Group of log */
162 int numlogs; /* Number of logs to keep */
163 int trsize; /* Size cutoff to trigger trimming the log */
164 int hours; /* Hours between log trimming */
165 struct ptime_data *trim_at; /* Specific time to do trimming */
166 unsigned int permissions; /* File permissions on the log */
167 int flags; /* CE_BINARY */
168 int compress; /* Compression */
169 int sig; /* Signal to send */
170 int def_cfg; /* Using the <default> rule for this file */
173 struct sigwork_entry {
174 SLIST_ENTRY(sigwork_entry) sw_nextp;
175 int sw_signum; /* the signal to send */
176 int sw_pidok; /* true if pid value is valid */
177 pid_t sw_pid; /* the process id from the PID file */
178 const char *sw_pidtype; /* "daemon" or "process group" */
179 int sw_runcmd; /* run command or send PID to signal */
180 char sw_fname[1]; /* file the PID was read from or shell cmd */
183 struct zipwork_entry {
184 SLIST_ENTRY(zipwork_entry) zw_nextp;
185 const struct conf_entry *zw_conf; /* for chown/perm/flag info */
186 const struct sigwork_entry *zw_swork; /* to know success of signal */
187 int zw_fsize; /* size of the file to compress */
188 char zw_fname[1]; /* the file to compress */
191 struct include_entry {
192 STAILQ_ENTRY(include_entry) inc_nextp;
193 const char *file; /* Name of file to process */
196 struct oldlog_entry {
197 char *fname; /* Filename of the log file */
198 time_t t; /* Parsed timestamp of the logfile */
205 STAILQ_HEAD(cflist, conf_entry);
206 static SLIST_HEAD(swlisthead, sigwork_entry) swhead =
207 SLIST_HEAD_INITIALIZER(swhead);
208 static SLIST_HEAD(zwlisthead, zipwork_entry) zwhead =
209 SLIST_HEAD_INITIALIZER(zwhead);
210 STAILQ_HEAD(ilist, include_entry);
212 int dbg_at_times; /* -D Show details of 'trim_at' code */
214 static int archtodir = 0; /* Archive old logfiles to other directory */
215 static int createlogs; /* Create (non-GLOB) logfiles which do not */
216 /* already exist. 1=='for entries with */
217 /* C flag', 2=='for all entries'. */
218 int verbose = 0; /* Print out what's going on */
219 static int needroot = 1; /* Root privs are necessary */
220 int noaction = 0; /* Don't do anything, just show it */
221 static int norotate = 0; /* Don't rotate */
222 static int nosignal; /* Do not send any signals */
223 static int enforcepid = 0; /* If PID file does not exist or empty, do nothing */
224 static int force = 0; /* Force the trim no matter what */
225 static int rotatereq = 0; /* -R = Always rotate the file(s) as given */
226 /* on the command (this also requires */
227 /* that a list of files *are* given on */
228 /* the run command). */
229 static char *requestor; /* The name given on a -R request */
230 static char *timefnamefmt = NULL;/* Use time based filenames instead of .0 */
231 static char *archdirname; /* Directory path to old logfiles archive */
232 static char *destdir = NULL; /* Directory to treat at root for logs */
233 static const char *conf; /* Configuration file to use */
235 struct ptime_data *dbg_timenow; /* A "timenow" value set via -D option */
236 static struct ptime_data *timenow; /* The time to use for checking at-fields */
238 #define DAYTIME_LEN 16
239 static char daytime[DAYTIME_LEN];/* The current time in human readable form,
240 * used for rotation-tracking messages. */
242 /* Another buffer to hold the current time in RFC5424 format. Fractional
243 * seconds are allowed by the RFC, but are not included in the
244 * rotation-tracking messages written by newsyslog and so are not accounted for
245 * in the length below.
247 #define DAYTIME_RFC5424_LEN sizeof("YYYY-MM-DDTHH:MM:SS+00:00")
248 static char daytime_rfc5424[DAYTIME_RFC5424_LEN];
250 static char hostname[MAXHOSTNAMELEN]; /* hostname */
251 static size_t hostname_shortlen;
253 static const char *path_syslogpid = _PATH_SYSLOGPID;
255 static struct cflist *get_worklist(char **files);
256 static void parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
257 struct conf_entry **defconf, struct ilist *inclist);
258 static void add_to_queue(const char *fname, struct ilist *inclist);
259 static char *sob(char *p);
260 static char *son(char *p);
261 static int isnumberstr(const char *);
262 static int isglobstr(const char *);
263 static char *missing_field(char *p, char *errline);
264 static void change_attrs(const char *, const struct conf_entry *);
265 static const char *get_logfile_suffix(const char *logfile);
266 static fk_entry do_entry(struct conf_entry *);
267 static fk_entry do_rotate(const struct conf_entry *);
268 static void do_sigwork(struct sigwork_entry *);
269 static void do_zipwork(struct zipwork_entry *);
270 static struct sigwork_entry *
271 save_sigwork(const struct conf_entry *);
272 static struct zipwork_entry *
273 save_zipwork(const struct conf_entry *, const struct
274 sigwork_entry *, int, const char *);
275 static void set_swpid(struct sigwork_entry *, const struct conf_entry *);
276 static int sizefile(const char *);
277 static void expand_globs(struct cflist *work_p, struct cflist *glob_p);
278 static void free_clist(struct cflist *list);
279 static void free_entry(struct conf_entry *ent);
280 static struct conf_entry *init_entry(const char *fname,
281 struct conf_entry *src_entry);
282 static void parse_args(int argc, char **argv);
283 static int parse_doption(const char *doption);
284 static void usage(void);
285 static int log_trim(const char *logname, const struct conf_entry *log_ent);
286 static int age_old_log(const char *file);
287 static void savelog(char *from, char *to);
288 static void createdir(const struct conf_entry *ent, char *dirpart);
289 static void createlog(const struct conf_entry *ent);
290 static int parse_signal(const char *str);
293 * All the following take a parameter of 'int', but expect values in the
294 * range of unsigned char. Define wrappers which take values of type 'char',
295 * whether signed or unsigned, and ensure they end up in the right range.
297 #define isdigitch(Anychar) isdigit((u_char)(Anychar))
298 #define isprintch(Anychar) isprint((u_char)(Anychar))
299 #define isspacech(Anychar) isspace((u_char)(Anychar))
300 #define tolowerch(Anychar) tolower((u_char)(Anychar))
303 main(int argc, char **argv)
305 struct cflist *worklist;
306 struct conf_entry *p;
307 struct sigwork_entry *stmp;
308 struct zipwork_entry *ztmp;
313 parse_args(argc, argv);
317 if (needroot && getuid() && geteuid())
318 errx(1, "must have root privs");
319 worklist = get_worklist(argv);
322 * Rotate all the files which need to be rotated. Note that
323 * some users have *hundreds* of entries in newsyslog.conf!
325 while (!STAILQ_EMPTY(worklist)) {
326 p = STAILQ_FIRST(worklist);
327 STAILQ_REMOVE_HEAD(worklist, cf_nextp);
328 if (do_entry(p) == FREE_ENT)
333 * Send signals to any processes which need a signal to tell
334 * them to close and re-open the log file(s) we have rotated.
335 * Note that zipwork_entries include pointers to these
336 * sigwork_entry's, so we can not free the entries here.
338 if (!SLIST_EMPTY(&swhead)) {
339 if (noaction || verbose)
340 printf("Signal all daemon process(es)...\n");
341 SLIST_FOREACH(stmp, &swhead, sw_nextp)
343 if (!(rotatereq && nosignal)) {
345 printf("\tsleep 10\n");
348 printf("Pause 10 seconds to allow "
349 "daemon(s) to close log file(s)\n");
355 * Compress all files that we're expected to compress, now
356 * that all processes should have closed the files which
359 if (!SLIST_EMPTY(&zwhead)) {
360 if (noaction || verbose)
361 printf("Compress all rotated log file(s)...\n");
362 while (!SLIST_EMPTY(&zwhead)) {
363 ztmp = SLIST_FIRST(&zwhead);
365 SLIST_REMOVE_HEAD(&zwhead, zw_nextp);
369 /* Now free all the sigwork entries. */
370 while (!SLIST_EMPTY(&swhead)) {
371 stmp = SLIST_FIRST(&swhead);
372 SLIST_REMOVE_HEAD(&swhead, sw_nextp);
376 while (wait(NULL) > 0 || errno == EINTR)
381 static struct conf_entry *
382 init_entry(const char *fname, struct conf_entry *src_entry)
384 struct conf_entry *tempwork;
387 printf("\t--> [creating entry for %s]\n", fname);
389 tempwork = malloc(sizeof(struct conf_entry));
390 if (tempwork == NULL)
391 err(1, "malloc of conf_entry for %s", fname);
393 if (destdir == NULL || fname[0] != '/')
394 tempwork->log = strdup(fname);
396 asprintf(&tempwork->log, "%s%s", destdir, fname);
397 if (tempwork->log == NULL)
398 err(1, "strdup for %s", fname);
400 if (src_entry != NULL) {
401 tempwork->pid_cmd_file = NULL;
402 if (src_entry->pid_cmd_file)
403 tempwork->pid_cmd_file = strdup(src_entry->pid_cmd_file);
404 tempwork->r_reason = NULL;
405 tempwork->firstcreate = 0;
406 tempwork->rotate = 0;
407 tempwork->fsize = -1;
408 tempwork->uid = src_entry->uid;
409 tempwork->gid = src_entry->gid;
410 tempwork->numlogs = src_entry->numlogs;
411 tempwork->trsize = src_entry->trsize;
412 tempwork->hours = src_entry->hours;
413 tempwork->trim_at = NULL;
414 if (src_entry->trim_at != NULL)
415 tempwork->trim_at = ptime_init(src_entry->trim_at);
416 tempwork->permissions = src_entry->permissions;
417 tempwork->flags = src_entry->flags;
418 tempwork->compress = src_entry->compress;
419 tempwork->sig = src_entry->sig;
420 tempwork->def_cfg = src_entry->def_cfg;
422 /* Initialize as a "do-nothing" entry */
423 tempwork->pid_cmd_file = NULL;
424 tempwork->r_reason = NULL;
425 tempwork->firstcreate = 0;
426 tempwork->rotate = 0;
427 tempwork->fsize = -1;
428 tempwork->uid = (uid_t)-1;
429 tempwork->gid = (gid_t)-1;
430 tempwork->numlogs = 1;
431 tempwork->trsize = -1;
432 tempwork->hours = -1;
433 tempwork->trim_at = NULL;
434 tempwork->permissions = 0;
436 tempwork->compress = COMPRESS_NONE;
437 tempwork->sig = SIGHUP;
438 tempwork->def_cfg = 0;
445 free_entry(struct conf_entry *ent)
451 if (ent->log != NULL) {
453 printf("\t--> [freeing entry for %s]\n", ent->log);
458 if (ent->pid_cmd_file != NULL) {
459 free(ent->pid_cmd_file);
460 ent->pid_cmd_file = NULL;
463 if (ent->r_reason != NULL) {
465 ent->r_reason = NULL;
468 if (ent->trim_at != NULL) {
469 ptime_free(ent->trim_at);
477 free_clist(struct cflist *list)
479 struct conf_entry *ent;
481 while (!STAILQ_EMPTY(list)) {
482 ent = STAILQ_FIRST(list);
483 STAILQ_REMOVE_HEAD(list, cf_nextp);
492 do_entry(struct conf_entry * ent)
494 #define REASON_MAX 80
496 fk_entry free_or_keep;
498 char temp_reason[REASON_MAX];
501 free_or_keep = FREE_ENT;
503 printf("%s <%d%s>: ", ent->log, ent->numlogs,
504 compress_type[ent->compress].flag);
505 ent->fsize = sizefile(ent->log);
506 oversized = ((ent->trsize > 0) && (ent->fsize >= ent->trsize));
507 modtime = age_old_log(ent->log);
509 ent->firstcreate = 0;
510 if (ent->fsize < 0) {
512 * If either the C flag or the -C option was specified,
513 * and if we won't be creating the file, then have the
514 * verbose message include a hint as to why the file
515 * will not be created.
517 temp_reason[0] = '\0';
519 ent->firstcreate = 1;
520 else if ((ent->flags & CE_CREATE) && createlogs)
521 ent->firstcreate = 1;
522 else if (ent->flags & CE_CREATE)
523 strlcpy(temp_reason, " (no -C option)", REASON_MAX);
525 strlcpy(temp_reason, " (no C flag)", REASON_MAX);
527 if (ent->firstcreate) {
529 printf("does not exist -> will create.\n");
531 } else if (verbose) {
532 printf("does not exist, skipped%s.\n", temp_reason);
535 if (ent->flags & CE_NOEMPTY && ent->fsize == 0) {
537 printf("--> Not rotating empty file\n");
538 return (free_or_keep);
540 if (ent->flags & CE_TRIMAT && !force && !rotatereq &&
542 diffsecs = ptimeget_diff(timenow, ent->trim_at);
543 if (diffsecs < 0.0) {
544 /* trim_at is some time in the future. */
546 ptime_adjust4dst(ent->trim_at,
548 printf("--> will trim at %s",
549 ptimeget_ctime(ent->trim_at));
551 return (free_or_keep);
552 } else if (diffsecs >= 3600.0) {
554 * trim_at is more than an hour in the past,
555 * so find the next valid trim_at time, and
556 * tell the user what that will be.
558 if (verbose && dbg_at_times)
559 printf("\n\t--> prev trim at %s\t",
560 ptimeget_ctime(ent->trim_at));
562 ptimeset_nxtime(ent->trim_at);
563 printf("--> will trim at %s",
564 ptimeget_ctime(ent->trim_at));
566 return (free_or_keep);
567 } else if (verbose && noaction && dbg_at_times) {
569 * If we are just debugging at-times, then
570 * a detailed message is helpful. Also
571 * skip "doing" any commands, since they
572 * would all be turned off by no-action.
574 printf("\n\t--> timematch at %s",
575 ptimeget_ctime(ent->trim_at));
576 return (free_or_keep);
577 } else if (verbose && ent->hours <= 0) {
578 printf("--> time is up\n");
581 if (verbose && (ent->trsize > 0))
582 printf("size (Kb): %d [%d] ", ent->fsize, ent->trsize);
583 if (verbose && (ent->hours > 0))
584 printf(" age (hr): %d [%d] ", modtime, ent->hours);
587 * Figure out if this logfile needs to be rotated.
589 temp_reason[0] = '\0';
592 snprintf(temp_reason, REASON_MAX, " due to -R from %s",
596 snprintf(temp_reason, REASON_MAX, " due to -F request");
597 } else if (oversized) {
599 snprintf(temp_reason, REASON_MAX, " due to size>%dK",
601 } else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) {
603 } else if ((ent->hours > 0) && ((modtime >= ent->hours) ||
609 * If the file needs to be rotated, then rotate it.
611 if (ent->rotate && !norotate) {
612 if (temp_reason[0] != '\0')
613 ent->r_reason = strdup(temp_reason);
615 printf("--> trimming log....\n");
616 if (noaction && !verbose)
617 printf("%s <%d%s>: trimming\n", ent->log,
619 compress_type[ent->compress].flag);
620 free_or_keep = do_rotate(ent);
623 printf("--> skipping\n");
626 return (free_or_keep);
631 parse_args(int argc, char **argv)
636 timenow = ptime_init(NULL);
637 ptimeset_time(timenow, time(NULL));
638 strlcpy(daytime, ptimeget_ctime(timenow) + 4, DAYTIME_LEN);
639 ptimeget_ctime_rfc5424(timenow, daytime_rfc5424, DAYTIME_RFC5424_LEN);
641 /* Let's get our hostname */
642 (void)gethostname(hostname, sizeof(hostname));
643 hostname_shortlen = strcspn(hostname, ".");
645 /* Parse command line options. */
646 while ((ch = getopt(argc, argv, "a:d:f:nrst:vCD:FNPR:S:")) != -1)
650 archdirname = optarg;
668 if (optarg[0] == '\0' ||
669 strcmp(optarg, "DEFAULT") == 0)
670 timefnamefmt = strdup(DEFAULT_TIMEFNAME_FMT);
672 timefnamefmt = strdup(optarg);
678 /* Useful for things like rc.diskless... */
683 * Set some debugging option. The specific option
684 * depends on the value of optarg. These options
685 * may come and go without notice or documentation.
687 if (parse_doption(optarg))
702 requestor = strdup(optarg);
705 path_syslogpid = optarg;
707 case 'm': /* Used by OpenBSD for "monitor mode" */
713 if (force && norotate) {
714 warnx("Only one of -F and -N may be specified.");
720 if (optind == argc) {
721 warnx("At least one filename must be given when -R is specified.");
725 /* Make sure "requestor" value is safe for a syslog message. */
726 for (p = requestor; *p != '\0'; p++) {
727 if (!isprintch(*p) && (*p != '\t'))
734 * Note that the 'daytime' variable is not changed.
735 * That is only used in messages that track when a
736 * logfile is rotated, and if a file *is* rotated,
737 * then it will still rotated at the "real now" time.
740 timenow = dbg_timenow;
741 fprintf(stderr, "Debug: Running as if TimeNow is %s",
742 ptimeget_ctime(dbg_timenow));
748 * These debugging options are mainly meant for developer use, such
749 * as writing regression-tests. They would not be needed by users
750 * during normal operation of newsyslog...
753 parse_doption(const char *doption)
755 const char TN[] = "TN=";
758 if (strncmp(doption, TN, sizeof(TN) - 1) == 0) {
760 * The "TimeNow" debugging option. This might be off
761 * by an hour when crossing a timezone change.
763 dbg_timenow = ptime_init(NULL);
764 res = ptime_relparse(dbg_timenow, PTM_PARSE_ISO8601,
765 time(NULL), doption + sizeof(TN) - 1);
767 warnx("Non-existent time specified on -D %s", doption);
768 return (0); /* failure */
769 } else if (res < 0) {
770 warnx("Malformed time given on -D %s", doption);
771 return (0); /* failure */
773 return (1); /* successfully parsed */
777 if (strcmp(doption, "ats") == 0) {
779 return (1); /* successfully parsed */
782 /* XXX - This check could probably be dropped. */
783 if ((strcmp(doption, "neworder") == 0) || (strcmp(doption, "oldorder")
785 warnx("NOTE: newsyslog always uses 'neworder'.");
786 return (1); /* successfully parsed */
789 warnx("Unknown -D (debug) option: '%s'", doption);
790 return (0); /* failure */
798 "usage: newsyslog [-CFNPnrsv] [-a directory] [-d directory] [-f config_file]\n"
799 " [-S pidfile] [-t timefmt] [[-R tagname] file ...]\n");
804 * Parse a configuration file and return a linked list of all the logs
805 * which should be processed.
807 static struct cflist *
808 get_worklist(char **files)
812 struct cflist *cmdlist, *filelist, *globlist;
813 struct conf_entry *defconf, *dupent, *ent;
814 struct ilist inclist;
815 struct include_entry *inc;
819 STAILQ_INIT(&inclist);
821 filelist = malloc(sizeof(struct cflist));
822 if (filelist == NULL)
823 err(1, "malloc of filelist");
824 STAILQ_INIT(filelist);
825 globlist = malloc(sizeof(struct cflist));
826 if (globlist == NULL)
827 err(1, "malloc of globlist");
828 STAILQ_INIT(globlist);
830 inc = malloc(sizeof(struct include_entry));
832 err(1, "malloc of inc");
834 if (inc->file == NULL)
835 inc->file = _PATH_CONF;
836 STAILQ_INSERT_TAIL(&inclist, inc, inc_nextp);
838 STAILQ_FOREACH(inc, &inclist, inc_nextp) {
839 if (strcmp(inc->file, "-") != 0)
840 f = fopen(inc->file, "r");
843 inc->file = "<stdin>";
846 err(1, "%s", inc->file);
849 printf("Processing %s\n", inc->file);
850 parse_file(f, filelist, globlist, &defconf, &inclist);
855 * All config-file information has been read in and turned into
856 * a filelist and a globlist. If there were no specific files
857 * given on the run command, then the only thing left to do is to
858 * call a routine which finds all files matched by the globlist
859 * and adds them to the filelist. Then return the worklist.
861 if (*files == NULL) {
862 expand_globs(filelist, globlist);
863 free_clist(globlist);
870 * If newsyslog was given a specific list of files to process,
871 * it may be that some of those files were not listed in any
872 * config file. Those unlisted files should get the default
873 * rotation action. First, create the default-rotation action
874 * if none was found in a system config file.
876 if (defconf == NULL) {
877 defconf = init_entry(DEFAULT_MARKER, NULL);
878 defconf->numlogs = 3;
879 defconf->trsize = 50;
880 defconf->permissions = S_IRUSR|S_IWUSR;
884 * If newsyslog was run with a list of specific filenames,
885 * then create a new worklist which has only those files in
886 * it, picking up the rotation-rules for those files from
887 * the original filelist.
889 * XXX - Note that this will copy multiple rules for a single
890 * logfile, if multiple entries are an exact match for
891 * that file. That matches the historic behavior, but do
892 * we want to continue to allow it? If so, it should
893 * probably be handled more intelligently.
895 cmdlist = malloc(sizeof(struct cflist));
897 err(1, "malloc of cmdlist");
898 STAILQ_INIT(cmdlist);
900 for (given = files; *given; ++given) {
902 * First try to find exact-matches for this given file.
905 STAILQ_FOREACH(ent, filelist, cf_nextp) {
906 if (strcmp(ent->log, *given) == 0) {
908 dupent = init_entry(*given, ent);
909 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
914 printf("\t+ Matched entry %s\n", *given);
919 * There was no exact-match for this given file, so look
920 * for a "glob" entry which does match.
924 printf("\t+ Checking globs for %s\n", *given);
925 STAILQ_FOREACH(ent, globlist, cf_nextp) {
926 fnres = fnmatch(ent->log, *given, FNM_PATHNAME);
928 printf("\t+ = %d for pattern %s\n", fnres,
932 dupent = init_entry(*given, ent);
933 /* This new entry is not a glob! */
934 dupent->flags &= ~CE_GLOB;
935 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
936 /* Only allow a match to one glob-entry */
942 printf("\t+ Matched %s via %s\n", *given,
948 * This given file was not found in any config file, so
949 * add a worklist item based on the default entry.
952 printf("\t+ No entry matched %s (will use %s)\n",
953 *given, DEFAULT_MARKER);
954 dupent = init_entry(*given, defconf);
955 /* Mark that it was *not* found in a config file */
957 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
961 * Free all the entries in the original work list, the list of
962 * glob entries, and the default entry.
964 free_clist(filelist);
965 free_clist(globlist);
968 /* And finally, return a worklist which matches the given files. */
973 * Expand the list of entries with filename patterns, and add all files
974 * which match those glob-entries onto the worklist.
977 expand_globs(struct cflist *work_p, struct cflist *glob_p)
982 struct conf_entry *dupent, *ent, *globent;
987 * The worklist contains all fully-specified (non-GLOB) names.
989 * Now expand the list of filename-pattern (GLOB) entries into
990 * a second list, which (by definition) will only match files
991 * that already exist. Do not add a glob-related entry for any
992 * file which already exists in the fully-specified list.
994 STAILQ_FOREACH(globent, glob_p, cf_nextp) {
995 gres = glob(globent->log, GLOB_NOCHECK, NULL, &pglob);
997 warn("cannot expand pattern (%d): %s", gres,
1003 printf("\t+ Expanding pattern %s\n", globent->log);
1004 for (i = 0; i < pglob.gl_matchc; i++) {
1005 mfname = pglob.gl_pathv[i];
1007 /* See if this file already has a specific entry. */
1009 STAILQ_FOREACH(ent, work_p, cf_nextp) {
1010 if (strcmp(mfname, ent->log) == 0) {
1018 /* Make sure the named matched is a file. */
1019 gres = lstat(mfname, &st_fm);
1021 /* Error on a file that glob() matched?!? */
1022 warn("Skipping %s - lstat() error", mfname);
1025 if (!S_ISREG(st_fm.st_mode)) {
1026 /* We only rotate files! */
1028 printf("\t+ . skipping %s (!file)\n",
1034 printf("\t+ . add file %s\n", mfname);
1035 dupent = init_entry(mfname, globent);
1036 /* This new entry is not a glob! */
1037 dupent->flags &= ~CE_GLOB;
1039 /* Add to the worklist. */
1040 STAILQ_INSERT_TAIL(work_p, dupent, cf_nextp);
1044 printf("\t+ Done with pattern %s\n", globent->log);
1049 * Parse a configuration file and update a linked list of all the logs to
1053 parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
1054 struct conf_entry **defconf_p, struct ilist *inclist)
1056 char line[BUFSIZ], *parse, *q;
1057 char *cp, *errline, *group;
1058 struct conf_entry *working;
1062 int eol, ptm_opts, res, special;
1066 while (fgets(line, BUFSIZ, cf)) {
1067 if ((line[0] == '\n') || (line[0] == '#') ||
1068 (strlen(line) == 0))
1070 if (errline != NULL)
1072 errline = strdup(line);
1073 for (cp = line + 1; *cp != '\0'; cp++) {
1076 if (*(cp - 1) == '\\') {
1085 q = parse = missing_field(sob(line), errline);
1088 warnx("malformed line (missing fields):\n%s",
1095 * Allow people to set debug options via the config file.
1096 * (NOTE: debug options are undocumented, and may disappear
1097 * at any time, etc).
1099 if (strcasecmp(DEBUG_MARKER, q) == 0) {
1100 q = parse = missing_field(sob(parse + 1), errline);
1103 warnx("debug line specifies no option:\n%s",
1110 } else if (strcasecmp(INCLUDE_MARKER, q) == 0) {
1112 printf("Found: %s", errline);
1113 q = parse = missing_field(sob(parse + 1), errline);
1116 warnx("include line missing argument:\n%s",
1124 res = glob(q, GLOB_NOCHECK, NULL, &pglob);
1126 warn("cannot expand pattern (%d): %s",
1132 printf("\t+ Expanding pattern %s\n", q);
1134 for (i = 0; i < pglob.gl_matchc; i++)
1135 add_to_queue(pglob.gl_pathv[i],
1139 add_to_queue(q, inclist);
1143 #define badline(msg, ...) do { \
1144 warnx(msg, __VA_ARGS__); \
1149 working = init_entry(q, NULL);
1150 if (strcasecmp(DEFAULT_MARKER, q) == 0) {
1152 if (*defconf_p != NULL)
1153 badline("Ignoring duplicate entry for %s!", q);
1154 *defconf_p = working;
1157 q = parse = missing_field(sob(parse + 1), errline);
1160 badline("malformed line (missing fields):\n%s",
1163 if ((group = strchr(q, ':')) != NULL ||
1164 (group = strrchr(q, '.')) != NULL) {
1167 if (!(isnumberstr(q))) {
1168 if ((pwd = getpwnam(q)) == NULL)
1170 "error in config file; unknown user:\n%s",
1172 working->uid = pwd->pw_uid;
1174 working->uid = atoi(q);
1176 working->uid = (uid_t)-1;
1180 if (!(isnumberstr(q))) {
1181 if ((grp = getgrnam(q)) == NULL)
1183 "error in config file; unknown group:\n%s",
1185 working->gid = grp->gr_gid;
1187 working->gid = atoi(q);
1189 working->gid = (gid_t)-1;
1191 q = parse = missing_field(sob(parse + 1), errline);
1194 badline("malformed line (missing fields):\n%s",
1198 working->uid = (uid_t)-1;
1199 working->gid = (gid_t)-1;
1202 if (!sscanf(q, "%o", &working->permissions))
1203 badline("error in config file; bad permissions:\n%s",
1205 if ((working->permissions & ~DEFFILEMODE) != 0) {
1206 warnx("File mode bits 0%o changed to 0%o in line:\n%s",
1207 working->permissions,
1208 working->permissions & DEFFILEMODE, errline);
1209 working->permissions &= DEFFILEMODE;
1212 q = parse = missing_field(sob(parse + 1), errline);
1215 badline("malformed line (missing fields):\n%s",
1218 if (!sscanf(q, "%d", &working->numlogs) || working->numlogs < 0)
1219 badline("error in config file; bad value for count of logs to save:\n%s",
1222 q = parse = missing_field(sob(parse + 1), errline);
1225 badline("malformed line (missing fields):\n%s",
1229 working->trsize = atoi(q);
1230 else if (strcmp(q, "*") == 0)
1231 working->trsize = -1;
1233 warnx("Invalid value of '%s' for 'size' in line:\n%s",
1235 working->trsize = -1;
1239 working->compress = COMPRESS_NONE;
1240 q = parse = missing_field(sob(parse + 1), errline);
1248 ul = strtoul(q, &ep, 10);
1251 else if (*ep == '*')
1252 working->hours = -1;
1253 else if (ul > INT_MAX)
1254 badline("interval is too large:\n%s", errline);
1256 working->hours = ul;
1258 if (*ep == '\0' || strcmp(ep, "*") == 0)
1260 if (*ep != '@' && *ep != '$')
1261 badline("malformed interval/at:\n%s", errline);
1263 working->flags |= CE_TRIMAT;
1264 working->trim_at = ptime_init(NULL);
1265 ptm_opts = PTM_PARSE_ISO8601;
1267 ptm_opts = PTM_PARSE_DWM;
1268 ptm_opts |= PTM_PARSE_MATCHDOM;
1269 res = ptime_relparse(working->trim_at, ptm_opts,
1270 ptimeget_secs(timenow), ep + 1);
1272 badline("nonexistent time for 'at' value:\n%s",
1275 badline("malformed 'at' value:\n%s", errline);
1282 q = parse = sob(parse + 1); /* Optional field */
1289 for (; q && *q && !isspacech(*q); q++) {
1290 switch (tolowerch(*q)) {
1292 working->flags |= CE_BINARY;
1295 working->flags |= CE_CREATE;
1298 working->flags |= CE_NODUMP;
1301 working->flags |= CE_NOEMPTY;
1304 working->flags |= CE_GLOB;
1307 working->compress = COMPRESS_BZIP2;
1310 working->flags |= CE_NOSIGNAL;
1313 working->flags |= CE_PLAIN0;
1316 working->flags |= CE_PID2CMD;
1319 working->flags |= CE_RFC5424;
1322 working->flags |= CE_SIGNALGROUP;
1325 /* Deprecated flag - keep for compatibility purposes */
1328 working->compress = COMPRESS_XZ;
1331 working->compress = COMPRESS_ZSTD;
1334 working->compress = COMPRESS_GZIP;
1338 case 'f': /* Used by OpenBSD for "CE_FOLLOW" */
1339 case 'm': /* Used by OpenBSD for "CE_MONITOR" */
1341 badline("illegal flag in config file -- %c",
1349 q = parse = sob(parse + 1); /* Optional field */
1356 working->pid_cmd_file = NULL;
1359 working->pid_cmd_file = strdup(q);
1360 else if (isalnum(*q))
1364 "illegal pid file or signal in config file:\n%s",
1371 q = parse = sob(parse + 1); /* Optional field */
1376 working->sig = SIGHUP;
1379 working->sig = parse_signal(q);
1380 if (working->sig < 1 || working->sig >= sys_nsig) {
1382 "illegal signal in config file:\n%s",
1388 * Finish figuring out what pid-file to use (if any) in
1389 * later processing if this logfile needs to be rotated.
1391 if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) {
1393 * This config-entry specified 'n' for nosignal,
1394 * see if it also specified an explicit pid_cmd_file.
1395 * This would be a pretty pointless combination.
1397 if (working->pid_cmd_file != NULL) {
1398 warnx("Ignoring '%s' because flag 'n' was specified in line:\n%s",
1399 working->pid_cmd_file, errline);
1400 free(working->pid_cmd_file);
1401 working->pid_cmd_file = NULL;
1403 } else if (working->pid_cmd_file == NULL) {
1405 * This entry did not specify the 'n' flag, which
1406 * means it should signal syslogd unless it had
1407 * specified some other pid-file (and obviously the
1408 * syslog pid-file will not be for a process-group).
1409 * Also, we should only try to notify syslog if we
1412 if (working->flags & CE_SIGNALGROUP) {
1413 warnx("Ignoring flag 'U' in line:\n%s",
1415 working->flags &= ~CE_SIGNALGROUP;
1418 working->pid_cmd_file = strdup(path_syslogpid);
1422 * Add this entry to the appropriate list of entries, unless
1423 * it was some kind of special entry (eg: <default>).
1426 ; /* Do not add to any list */
1427 } else if (working->flags & CE_GLOB) {
1428 STAILQ_INSERT_TAIL(glob_p, working, cf_nextp);
1430 STAILQ_INSERT_TAIL(work_p, working, cf_nextp);
1434 free_entry(working);
1436 } /* while (fgets(line, BUFSIZ, cf)) */
1437 if (errline != NULL)
1442 missing_field(char *p, char *errline)
1446 errx(1, "missing field in config file:\n%s", errline);
1451 * In our sort we return it in the reverse of what qsort normally
1452 * would do, as we want the newest files first. If we have two
1453 * entries with the same time we don't really care about order.
1455 * Support function for qsort() in delete_oldest_timelog().
1458 oldlog_entry_compare(const void *a, const void *b)
1460 const struct oldlog_entry *ola = a, *olb = b;
1462 if (ola->t > olb->t)
1464 else if (ola->t < olb->t)
1471 * Check whether the file corresponding to dp is an archive of the logfile
1472 * logfname, based on the timefnamefmt format string. Return true and fill out
1473 * tm if this is the case; otherwise return false.
1476 validate_old_timelog(int fd, const struct dirent *dp, const char *logfname,
1480 size_t logfname_len;
1484 logfname_len = strlen(logfname);
1486 if (dp->d_type != DT_REG) {
1488 * Some filesystems (e.g. NFS) don't fill out the d_type field
1489 * and leave it set to DT_UNKNOWN; in this case we must obtain
1490 * the file type ourselves.
1492 if (dp->d_type != DT_UNKNOWN ||
1493 fstatat(fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) != 0 ||
1494 !S_ISREG(sb.st_mode))
1497 /* Ignore everything but files with our logfile prefix. */
1498 if (strncmp(dp->d_name, logfname, logfname_len) != 0)
1500 /* Ignore the actual non-rotated logfile. */
1501 if (dp->d_namlen == logfname_len)
1505 * Make sure we created have found a logfile, so the
1506 * postfix is valid, IE format is: '.<time>(.[bgx]z)?'.
1508 if (dp->d_name[logfname_len] != '.') {
1510 printf("Ignoring %s which has unexpected "
1511 "extension '%s'\n", dp->d_name,
1512 &dp->d_name[logfname_len]);
1515 memset(tm, 0, sizeof(*tm));
1516 if ((s = strptime(&dp->d_name[logfname_len + 1],
1517 timefnamefmt, tm)) == NULL) {
1519 * We could special case "old" sequentially named logfiles here,
1520 * but we do not as that would require special handling to
1521 * decide which one was the oldest compared to "new" time based
1525 printf("Ignoring %s which does not "
1526 "match time format\n", dp->d_name);
1530 for (c = 0; c < COMPRESS_TYPES; c++)
1531 if (strcmp(s, compress_type[c].suffix) == 0)
1536 printf("Ignoring %s which has unexpected extension '%s'\n",
1543 * Delete the oldest logfiles, when using time based filenames.
1546 delete_oldest_timelog(const struct conf_entry *ent, const char *archive_dir)
1548 char *basebuf, *dirbuf, errbuf[80];
1549 const char *base, *dir;
1550 int dir_fd, i, logcnt, max_logcnt;
1551 struct oldlog_entry *oldlogs;
1556 oldlogs = malloc(MAX_OLDLOGS * sizeof(struct oldlog_entry));
1557 max_logcnt = MAX_OLDLOGS;
1560 if (archive_dir != NULL && archive_dir[0] != '\0') {
1564 if ((dirbuf = strdup(ent->log)) == NULL)
1566 dir = dirname(dirbuf);
1569 if ((basebuf = strdup(ent->log)) == NULL)
1571 base = basename(basebuf);
1572 if (strcmp(base, "/") == 0)
1573 errx(1, "Invalid log filename - became '/'");
1576 printf("Searching for old logs in %s\n", dir);
1578 /* First we create a 'list' of all archived logfiles */
1579 if ((dirp = opendir(dir)) == NULL)
1580 err(1, "Cannot open log directory '%s'", dir);
1581 dir_fd = dirfd(dirp);
1582 while ((dp = readdir(dirp)) != NULL) {
1583 if (validate_old_timelog(dir_fd, dp, base, &tm) == 0)
1587 * We should now have old an old rotated logfile, so
1588 * add it to the 'list'.
1590 if ((oldlogs[logcnt].t = timegm(&tm)) == -1)
1591 err(1, "Could not convert time string to time value");
1592 if ((oldlogs[logcnt].fname = strdup(dp->d_name)) == NULL)
1597 * It is very unlikely we ever run out of space in the
1598 * logfile array from the default size, but lets
1599 * handle it anyway...
1601 if (logcnt >= max_logcnt) {
1603 /* Detect integer overflow */
1604 if (max_logcnt < logcnt)
1605 errx(1, "Too many old logfiles found");
1606 oldlogs = realloc(oldlogs,
1607 max_logcnt * sizeof(struct oldlog_entry));
1608 if (oldlogs == NULL)
1609 err(1, "realloc()");
1613 /* Second, if needed we delete oldest archived logfiles */
1614 if (logcnt > 0 && logcnt >= ent->numlogs && ent->numlogs > 1) {
1615 oldlogs = realloc(oldlogs, logcnt *
1616 sizeof(struct oldlog_entry));
1617 if (oldlogs == NULL)
1618 err(1, "realloc()");
1621 * We now sort the logs in the order of newest to
1622 * oldest. That way we can simply skip over the
1623 * number of records we want to keep.
1625 qsort(oldlogs, logcnt, sizeof(struct oldlog_entry),
1626 oldlog_entry_compare);
1627 for (i = ent->numlogs - 1; i < logcnt; i++) {
1629 printf("\trm -f %s/%s\n", dir,
1631 else if (unlinkat(dir_fd, oldlogs[i].fname, 0) != 0) {
1632 snprintf(errbuf, sizeof(errbuf),
1633 "Could not delete old logfile '%s'",
1638 } else if (verbose > 1)
1639 printf("No old logs to delete for logfile %s\n", ent->log);
1641 /* Third, cleanup */
1643 for (i = 0; i < logcnt; i++) {
1644 assert(oldlogs[i].fname != NULL);
1645 free(oldlogs[i].fname);
1653 * Generate a log filename, when using classic filenames.
1656 gen_classiclog_fname(char *fname, size_t fname_sz, const char *archive_dir,
1657 const char *namepart, int numlogs_c)
1660 if (archive_dir[0] != '\0')
1661 (void) snprintf(fname, fname_sz, "%s/%s.%d", archive_dir,
1662 namepart, numlogs_c);
1664 (void) snprintf(fname, fname_sz, "%s.%d", namepart, numlogs_c);
1668 * Delete a rotated logfile, when using classic filenames.
1671 delete_classiclog(const char *archive_dir, const char *namepart, int numlog_c)
1673 char file1[MAXPATHLEN], zfile1[MAXPATHLEN];
1676 gen_classiclog_fname(file1, sizeof(file1), archive_dir, namepart,
1679 for (c = 0; c < COMPRESS_TYPES; c++) {
1680 (void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1681 compress_type[c].suffix);
1683 printf("\trm -f %s\n", zfile1);
1685 (void) unlink(zfile1);
1690 * Only add to the queue if the file hasn't already been added. This is
1691 * done to prevent circular include loops.
1694 add_to_queue(const char *fname, struct ilist *inclist)
1696 struct include_entry *inc;
1698 STAILQ_FOREACH(inc, inclist, inc_nextp) {
1699 if (strcmp(fname, inc->file) == 0) {
1700 warnx("duplicate include detected: %s", fname);
1705 inc = malloc(sizeof(struct include_entry));
1707 err(1, "malloc of inc");
1708 inc->file = strdup(fname);
1711 printf("\t+ Adding %s to the processing queue.\n", fname);
1713 STAILQ_INSERT_TAIL(inclist, inc, inc_nextp);
1717 * Search for logfile and return its compression suffix (if supported)
1718 * The suffix detection is first-match in the order of compress_types
1720 * Note: if logfile without suffix exists (uncompressed, COMPRESS_NONE)
1721 * a zero-length string is returned
1724 get_logfile_suffix(const char *logfile)
1727 char zfile[MAXPATHLEN];
1730 for (c = 0; c < COMPRESS_TYPES; c++) {
1731 (void) strlcpy(zfile, logfile, MAXPATHLEN);
1732 (void) strlcat(zfile, compress_type[c].suffix, MAXPATHLEN);
1733 if (lstat(zfile, &st) == 0)
1734 return (compress_type[c].suffix);
1740 do_rotate(const struct conf_entry *ent)
1742 char dirpart[MAXPATHLEN], namepart[MAXPATHLEN];
1743 char file1[MAXPATHLEN], file2[MAXPATHLEN];
1744 char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN];
1745 const char *logfile_suffix;
1746 char datetimestr[30];
1747 int flags, numlogs_c;
1748 fk_entry free_or_keep;
1749 struct sigwork_entry *swork;
1755 free_or_keep = FREE_ENT;
1760 /* build complete name of archive directory into dirpart */
1761 if (*archdirname == '/') { /* absolute */
1762 strlcpy(dirpart, archdirname, sizeof(dirpart));
1763 } else { /* relative */
1764 /* get directory part of logfile */
1765 strlcpy(dirpart, ent->log, sizeof(dirpart));
1766 if ((p = strrchr(dirpart, '/')) == NULL)
1770 strlcat(dirpart, archdirname, sizeof(dirpart));
1773 /* check if archive directory exists, if not, create it */
1774 if (lstat(dirpart, &st))
1775 createdir(ent, dirpart);
1777 /* get filename part of logfile */
1778 if ((p = strrchr(ent->log, '/')) == NULL)
1779 strlcpy(namepart, ent->log, sizeof(namepart));
1781 strlcpy(namepart, p + 1, sizeof(namepart));
1784 * Tell utility functions we are not using an archive
1788 strlcpy(namepart, ent->log, sizeof(namepart));
1791 /* Delete old logs */
1792 if (timefnamefmt != NULL)
1793 delete_oldest_timelog(ent, dirpart);
1796 * Handle cleaning up after legacy newsyslog where we
1797 * kept ent->numlogs + 1 files. This code can go away
1798 * at some point in the future.
1800 delete_classiclog(dirpart, namepart, ent->numlogs);
1802 if (ent->numlogs > 0)
1803 delete_classiclog(dirpart, namepart, ent->numlogs - 1);
1807 if (timefnamefmt != NULL) {
1808 /* If time functions fails we can't really do any sensible */
1809 if (time(&now) == (time_t)-1 ||
1810 localtime_r(&now, &tm) == NULL)
1811 bzero(&tm, sizeof(tm));
1813 strftime(datetimestr, sizeof(datetimestr), timefnamefmt, &tm);
1815 (void) snprintf(file1, sizeof(file1), "%s/%s.%s",
1816 dirpart, namepart, datetimestr);
1818 (void) snprintf(file1, sizeof(file1), "%s.%s",
1819 ent->log, datetimestr);
1821 /* Don't run the code to move down logs */
1824 gen_classiclog_fname(file1, sizeof(file1), dirpart, namepart,
1826 numlogs_c = ent->numlogs - 2; /* copy for countdown */
1829 /* Move down log files */
1830 for (; numlogs_c >= 0; numlogs_c--) {
1831 (void) strlcpy(file2, file1, sizeof(file2));
1833 gen_classiclog_fname(file1, sizeof(file1), dirpart, namepart,
1836 logfile_suffix = get_logfile_suffix(file1);
1837 if (logfile_suffix == NULL)
1839 (void) strlcpy(zfile1, file1, MAXPATHLEN);
1840 (void) strlcpy(zfile2, file2, MAXPATHLEN);
1841 (void) strlcat(zfile1, logfile_suffix, MAXPATHLEN);
1842 (void) strlcat(zfile2, logfile_suffix, MAXPATHLEN);
1845 printf("\tmv %s %s\n", zfile1, zfile2);
1847 /* XXX - Ought to be checking for failure! */
1848 (void)rename(zfile1, zfile2);
1850 change_attrs(zfile2, ent);
1851 if (ent->compress && strlen(logfile_suffix) == 0) {
1852 /* compress old rotation */
1853 struct zipwork_entry *zwork;
1856 sz = sizeof(*zwork) + strlen(zfile2) + 1;
1857 zwork = calloc(1, sz);
1861 zwork->zw_conf = ent;
1862 zwork->zw_fsize = sizefile(zfile2);
1863 strcpy(zwork->zw_fname, zfile2);
1869 if (ent->numlogs > 0) {
1872 * Note that savelog() may succeed with using link()
1873 * for the archtodir case, but there is no good way
1874 * of knowing if it will when doing "noaction", so
1875 * here we claim that it will have to do a copy...
1878 printf("\tcp %s %s\n", ent->log, file1);
1880 printf("\tln %s %s\n", ent->log, file1);
1881 printf("\ttouch %s\t\t"
1882 "# Update mtime for 'when'-interval processing\n",
1885 if (!(flags & CE_BINARY)) {
1886 /* Report the trimming to the old log */
1887 log_trim(ent->log, ent);
1889 savelog(ent->log, file1);
1891 * Interval-based rotations are done using the mtime of
1892 * the most recently archived log, so make sure it gets
1893 * updated during a rotation.
1895 utimes(file1, NULL);
1897 change_attrs(file1, ent);
1900 /* Create the new log file and move it into place */
1902 printf("Start new log...\n");
1906 * Save all signalling and file-compression to be done after log
1907 * files from all entries have been rotated. This way any one
1908 * process will not be sent the same signal multiple times when
1909 * multiple log files had to be rotated.
1912 if (ent->pid_cmd_file != NULL)
1913 swork = save_sigwork(ent);
1914 if (ent->numlogs > 0 && ent->compress > COMPRESS_NONE) {
1915 if (!(ent->flags & CE_PLAIN0) ||
1916 strcmp(&file1[strlen(file1) - 2], ".0") != 0) {
1918 * The zipwork_entry will include a pointer to this
1919 * conf_entry, so the conf_entry should not be freed.
1921 free_or_keep = KEEP_ENT;
1922 save_zipwork(ent, swork, ent->fsize, file1);
1926 return (free_or_keep);
1930 do_sigwork(struct sigwork_entry *swork)
1932 struct sigwork_entry *nextsig;
1936 if (swork->sw_runcmd == 0 && (!(swork->sw_pidok) || swork->sw_pid == 0))
1937 return; /* no work to do... */
1940 * If nosignal (-s) was specified, then do not signal any process.
1941 * Note that a nosignal request triggers a warning message if the
1942 * rotated logfile needs to be compressed, *unless* -R was also
1943 * specified. We assume that an `-sR' request came from a process
1944 * which writes to the logfile, and as such, we assume that process
1945 * has already made sure the logfile is not presently in use. This
1946 * just sets swork->sw_pidok to a special value, and do_zipwork
1947 * will print any necessary warning(s).
1951 swork->sw_pidok = -1;
1956 * Compute the pause between consecutive signals. Use a longer
1957 * sleep time if we will be sending two signals to the same
1958 * daemon or process-group.
1961 nextsig = SLIST_NEXT(swork, sw_nextp);
1962 if (nextsig != NULL) {
1963 if (swork->sw_pid == nextsig->sw_pid)
1970 if (swork->sw_runcmd)
1971 printf("\tsh -c '%s %d'\n", swork->sw_fname,
1974 printf("\tkill -%d %d \t\t# %s\n", swork->sw_signum,
1975 (int)swork->sw_pid, swork->sw_fname);
1977 printf("\tsleep %d\n", secs);
1982 if (swork->sw_runcmd) {
1983 asprintf(&tmp, "%s %d", swork->sw_fname, swork->sw_signum);
1985 warn("can't allocate memory to run %s",
1990 printf("Run command: %s\n", tmp);
1993 warnx("%s: returned non-zero exit code: %d",
2000 kres = kill(swork->sw_pid, swork->sw_signum);
2003 * Assume that "no such process" (ESRCH) is something
2004 * to warn about, but is not an error. Presumably the
2005 * process which writes to the rotated log file(s) is
2006 * gone, in which case we should have no problem with
2007 * compressing the rotated log file(s).
2010 swork->sw_pidok = 0;
2011 warn("can't notify %s, pid %d = %s", swork->sw_pidtype,
2012 (int)swork->sw_pid, swork->sw_fname);
2015 printf("Notified %s pid %d = %s\n", swork->sw_pidtype,
2016 (int)swork->sw_pid, swork->sw_fname);
2019 printf("Pause %d second(s) between signals\n",
2027 do_zipwork(struct zipwork_entry *zwork)
2029 const struct compress_types *ct;
2030 struct sbuf *command;
2032 int c, errsav, fcount, zstatus;
2033 const char **args, *pgm_name, *pgm_path;
2036 assert(zwork != NULL);
2037 assert(zwork->zw_conf != NULL);
2038 assert(zwork->zw_conf->compress > COMPRESS_NONE);
2039 assert(zwork->zw_conf->compress < COMPRESS_TYPES);
2041 if (zwork->zw_swork != NULL && zwork->zw_swork->sw_runcmd == 0 &&
2042 zwork->zw_swork->sw_pidok <= 0) {
2044 "log %s not compressed because daemon(s) not notified",
2046 change_attrs(zwork->zw_fname, zwork->zw_conf);
2050 ct = &compress_type[zwork->zw_conf->compress];
2053 * execv will be called with the array [ program, flags ... ,
2054 * filename, NULL ] so allocate nflags+3 elements for the array.
2056 args = calloc(ct->nflags + 3, sizeof(*args));
2060 pgm_path = ct->path;
2061 pgm_name = strrchr(pgm_path, '/');
2062 if (pgm_name == NULL)
2063 pgm_name = pgm_path;
2067 /* Build the argument array. */
2069 for (c = 0; c < ct->nflags; c++)
2070 args[c + 1] = ct->flags[c];
2071 args[c + 1] = zwork->zw_fname;
2073 /* Also create a space-delimited version if we need to print it. */
2074 if ((command = sbuf_new_auto()) == NULL)
2075 errx(1, "sbuf_new");
2076 sbuf_cpy(command, pgm_path);
2077 for (c = 1; args[c] != NULL; c++) {
2078 sbuf_putc(command, ' ');
2079 sbuf_cat(command, args[c]);
2081 if (sbuf_finish(command) == -1)
2082 err(1, "sbuf_finish");
2084 /* Determine the filename of the compressed file. */
2085 asprintf(&zresult, "%s%s", zwork->zw_fname, ct->suffix);
2086 if (zresult == NULL)
2087 errx(1, "asprintf");
2090 printf("Executing: %s\n", sbuf_data(command));
2093 printf("\t%s %s\n", pgm_name, zwork->zw_fname);
2094 change_attrs(zresult, zwork->zw_conf);
2100 while (pidzip < 0) {
2102 * The fork failed. If the failure was due to a temporary
2103 * problem, then wait a short time and try it again.
2106 warn("fork() for `%s %s'", pgm_name, zwork->zw_fname);
2107 if (errsav != EAGAIN || fcount > 5)
2108 errx(1, "Exiting...");
2114 /* The child process executes the compression command */
2115 execv(pgm_path, __DECONST(char *const*, args));
2116 err(1, "execv(`%s')", sbuf_data(command));
2119 wpid = waitpid(pidzip, &zstatus, 0);
2121 /* XXX - should this be a fatal error? */
2122 warn("%s: waitpid(%d)", pgm_path, pidzip);
2125 if (!WIFEXITED(zstatus)) {
2126 warnx("`%s' did not terminate normally", sbuf_data(command));
2129 if (WEXITSTATUS(zstatus)) {
2130 warnx("`%s' terminated with a non-zero status (%d)",
2131 sbuf_data(command), WEXITSTATUS(zstatus));
2135 /* Compression was successful, set file attributes on the result. */
2136 change_attrs(zresult, zwork->zw_conf);
2139 sbuf_delete(command);
2145 * Save information on any process we need to signal. Any single
2146 * process may need to be sent different signal-values for different
2147 * log files, but usually a single signal-value will cause the process
2148 * to close and re-open all of its log files.
2150 static struct sigwork_entry *
2151 save_sigwork(const struct conf_entry *ent)
2153 struct sigwork_entry *sprev, *stmp;
2159 SLIST_FOREACH(stmp, &swhead, sw_nextp) {
2160 ndiff = strcmp(ent->pid_cmd_file, stmp->sw_fname);
2164 if (ent->sig == stmp->sw_signum)
2166 if (ent->sig > stmp->sw_signum) {
2173 if (stmp != NULL && ndiff == 0)
2176 tmpsiz = sizeof(struct sigwork_entry) + strlen(ent->pid_cmd_file) + 1;
2177 stmp = malloc(tmpsiz);
2179 stmp->sw_runcmd = 0;
2180 /* If this is a command to run we just set the flag and run command */
2181 if (ent->flags & CE_PID2CMD) {
2184 stmp->sw_runcmd = 1;
2186 set_swpid(stmp, ent);
2188 stmp->sw_signum = ent->sig;
2189 strcpy(stmp->sw_fname, ent->pid_cmd_file);
2191 SLIST_INSERT_HEAD(&swhead, stmp, sw_nextp);
2193 SLIST_INSERT_AFTER(sprev, stmp, sw_nextp);
2198 * Save information on any file we need to compress. We may see the same
2199 * file multiple times, so check the full list to avoid duplicates. The
2200 * list itself is sorted smallest-to-largest, because that's the order we
2201 * want to compress the files. If the partition is very low on disk space,
2202 * then the smallest files are the most likely to compress, and compressing
2203 * them first will free up more space for the larger files.
2205 static struct zipwork_entry *
2206 save_zipwork(const struct conf_entry *ent, const struct sigwork_entry *swork,
2207 int zsize, const char *zipfname)
2209 struct zipwork_entry *zprev, *ztmp;
2213 /* Compute the size if the caller did not know it. */
2215 zsize = sizefile(zipfname);
2219 SLIST_FOREACH(ztmp, &zwhead, zw_nextp) {
2220 ndiff = strcmp(zipfname, ztmp->zw_fname);
2223 if (zsize > ztmp->zw_fsize)
2226 if (ztmp != NULL && ndiff == 0)
2229 tmpsiz = sizeof(struct zipwork_entry) + strlen(zipfname) + 1;
2230 ztmp = malloc(tmpsiz);
2231 ztmp->zw_conf = ent;
2232 ztmp->zw_swork = swork;
2233 ztmp->zw_fsize = zsize;
2234 strcpy(ztmp->zw_fname, zipfname);
2236 SLIST_INSERT_HEAD(&zwhead, ztmp, zw_nextp);
2238 SLIST_INSERT_AFTER(zprev, ztmp, zw_nextp);
2242 /* Send a signal to the pid specified by pidfile */
2244 set_swpid(struct sigwork_entry *swork, const struct conf_entry *ent)
2247 long minok, maxok, rval;
2248 char *endp, *linep, line[BUFSIZ];
2252 swork->sw_pidok = 0;
2254 swork->sw_pidtype = "daemon";
2255 if (ent->flags & CE_SIGNALGROUP) {
2257 * If we are expected to signal a process-group when
2258 * rotating this logfile, then the value read in should
2259 * be the negative of a valid process ID.
2263 swork->sw_pidtype = "process-group";
2266 f = fopen(ent->pid_cmd_file, "r");
2268 if (errno == ENOENT && enforcepid == 0) {
2270 * Warn if the PID file doesn't exist, but do
2271 * not consider it an error. Most likely it
2272 * means the process has been terminated,
2273 * so it should be safe to rotate any log
2274 * files that the process would have been using.
2276 swork->sw_pidok = 1;
2277 warnx("pid file doesn't exist: %s", ent->pid_cmd_file);
2279 warn("can't open pid file: %s", ent->pid_cmd_file);
2283 if (fgets(line, BUFSIZ, f) == NULL) {
2285 * Warn if the PID file is empty, but do not consider
2286 * it an error. Most likely it means the process has
2287 * has terminated, so it should be safe to rotate any
2288 * log files that the process would have been using.
2290 if (feof(f) && enforcepid == 0) {
2291 swork->sw_pidok = 1;
2292 warnx("pid/cmd file is empty: %s", ent->pid_cmd_file);
2294 warn("can't read from pid file: %s", ent->pid_cmd_file);
2302 while (*linep == ' ')
2304 rval = strtol(linep, &endp, 10);
2305 if (*endp != '\0' && !isspacech(*endp)) {
2306 warnx("pid file does not start with a valid number: %s",
2308 } else if (rval < minok || rval > maxok) {
2309 warnx("bad value '%ld' for process number in %s",
2310 rval, ent->pid_cmd_file);
2312 warnx("\t(expecting value between %ld and %ld)",
2315 swork->sw_pidok = 1;
2316 swork->sw_pid = rval;
2322 /* Log the fact that the logs were turned over */
2324 log_trim(const char *logname, const struct conf_entry *log_ent)
2329 if ((f = fopen(logname, "a")) == NULL)
2332 if (log_ent->def_cfg)
2333 xtra = " using <default> rule";
2334 if (log_ent->flags & CE_RFC5424) {
2335 if (log_ent->firstcreate) {
2336 fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s\n",
2337 LOG_MAKEPRI(LOG_USER, LOG_INFO),
2338 daytime_rfc5424, hostname, getpid(),
2339 "logfile first created", xtra);
2340 } else if (log_ent->r_reason != NULL) {
2341 fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s%s\n",
2342 LOG_MAKEPRI(LOG_USER, LOG_INFO),
2343 daytime_rfc5424, hostname, getpid(),
2344 "logfile turned over", log_ent->r_reason, xtra);
2346 fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s\n",
2347 LOG_MAKEPRI(LOG_USER, LOG_INFO),
2348 daytime_rfc5424, hostname, getpid(),
2349 "logfile turned over", xtra);
2352 if (log_ent->firstcreate)
2354 "%s %.*s newsyslog[%d]: logfile first created%s\n",
2355 daytime, (int)hostname_shortlen, hostname, getpid(),
2357 else if (log_ent->r_reason != NULL)
2359 "%s %.*s newsyslog[%d]: logfile turned over%s%s\n",
2360 daytime, (int)hostname_shortlen, hostname, getpid(),
2361 log_ent->r_reason, xtra);
2364 "%s %.*s newsyslog[%d]: logfile turned over%s\n",
2365 daytime, (int)hostname_shortlen, hostname, getpid(),
2368 if (fclose(f) == EOF)
2369 err(1, "log_trim: fclose");
2373 /* Return size in kilobytes of a file */
2375 sizefile(const char *file)
2379 if (stat(file, &sb) < 0)
2381 return (kbytes(sb.st_size));
2385 * Return the mtime of the most recent archive of the logfile, using timestamp
2389 mtime_old_timelog(const char *file)
2397 char *logfname, *logfnamebuf, *dir, *dirbuf;
2401 if ((dirbuf = strdup(file)) == NULL) {
2402 warn("strdup() of '%s'", file);
2405 dir = dirname(dirbuf);
2406 if ((logfnamebuf = strdup(file)) == NULL) {
2407 warn("strdup() of '%s'", file);
2411 logfname = basename(logfnamebuf);
2412 if (logfname[0] == '/') {
2413 warnx("Invalid log filename '%s'", logfname);
2417 if ((dirp = opendir(dir)) == NULL) {
2418 warn("Cannot open log directory '%s'", dir);
2421 dir_fd = dirfd(dirp);
2422 /* Open the archive dir and find the most recent archive of logfname. */
2423 while ((dp = readdir(dirp)) != NULL) {
2424 if (validate_old_timelog(dir_fd, dp, logfname, &tm) == 0)
2427 if (fstatat(dir_fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
2428 warn("Cannot stat '%s'", file);
2431 if (t < sb.st_mtime)
2442 /* Return the age in hours of the most recent archive of the logfile. */
2444 age_old_log(const char *file)
2447 const char *logfile_suffix;
2448 static unsigned int suffix_maxlen = 0;
2454 if (suffix_maxlen == 0) {
2455 for (c = 0; c < COMPRESS_TYPES; c++)
2456 suffix_maxlen = MAX(suffix_maxlen,
2457 strlen(compress_type[c].suffix));
2460 tmpsiz = MAXPATHLEN + sizeof(".0") + suffix_maxlen + 1;
2461 tmp = alloca(tmpsiz);
2466 /* build name of archive directory into tmp */
2467 if (*archdirname == '/') { /* absolute */
2468 strlcpy(tmp, archdirname, tmpsiz);
2469 } else { /* relative */
2470 /* get directory part of logfile */
2471 strlcpy(tmp, file, tmpsiz);
2472 if ((p = strrchr(tmp, '/')) == NULL)
2476 strlcat(tmp, archdirname, tmpsiz);
2479 strlcat(tmp, "/", tmpsiz);
2481 /* get filename part of logfile */
2482 if ((p = strrchr(file, '/')) == NULL)
2483 strlcat(tmp, file, tmpsiz);
2485 strlcat(tmp, p + 1, tmpsiz);
2487 (void) strlcpy(tmp, file, tmpsiz);
2490 if (timefnamefmt != NULL) {
2491 mtime = mtime_old_timelog(tmp);
2495 strlcat(tmp, ".0", tmpsiz);
2496 logfile_suffix = get_logfile_suffix(tmp);
2497 if (logfile_suffix == NULL)
2499 (void) strlcat(tmp, logfile_suffix, tmpsiz);
2500 if (stat(tmp, &sb) < 0)
2502 mtime = sb.st_mtime;
2505 return ((int)(ptimeget_secs(timenow) - mtime + 1800) / 3600);
2508 /* Skip Over Blanks */
2512 while (p && *p && isspace(*p))
2517 /* Skip Over Non-Blanks */
2521 while (p && *p && !isspace(*p))
2526 /* Check if string is actually a number */
2528 isnumberstr(const char *string)
2531 if (!isdigitch(*string++))
2537 /* Check if string contains a glob */
2539 isglobstr(const char *string)
2543 while ((chr = *string++)) {
2544 if (chr == '*' || chr == '?' || chr == '[')
2551 * Save the active log file under a new name. A link to the new name
2552 * is the quick-and-easy way to do this. If that fails (which it will
2553 * if the destination is on another partition), then make a copy of
2554 * the file to the new location.
2557 savelog(char *from, char *to)
2562 res = link(from, to);
2566 if ((src = fopen(from, "r")) == NULL)
2567 err(1, "can't fopen %s for reading", from);
2568 if ((dst = fopen(to, "w")) == NULL)
2569 err(1, "can't fopen %s for writing", to);
2571 while ((c = getc(src)) != EOF) {
2572 if ((putc(c, dst)) == EOF)
2573 err(1, "error writing to %s", to);
2577 err(1, "error reading from %s", from);
2578 if ((fclose(src)) != 0)
2579 err(1, "can't fclose %s", to);
2580 if ((fclose(dst)) != 0)
2581 err(1, "can't fclose %s", from);
2584 /* create one or more directory components of a path */
2586 createdir(const struct conf_entry *ent, char *dirpart)
2590 char mkdirpath[MAXPATHLEN];
2598 if (*s != '/' && *s != '\0')
2601 res = lstat(mkdirpath, &st);
2604 printf("\tmkdir %s\n", mkdirpath);
2606 res = mkdir(mkdirpath, 0755);
2608 err(1, "Error on mkdir(\"%s\") for -a",
2616 if (ent->firstcreate)
2617 printf("Created directory '%s' for new %s\n",
2620 printf("Created directory '%s' for -a\n", dirpart);
2625 * Create a new log file, destroying any currently-existing version
2626 * of the log file in the process. If the caller wants a backup copy
2627 * of the file to exist, they should call 'link(logfile,logbackup)'
2628 * before calling this routine.
2631 createlog(const struct conf_entry *ent)
2635 char *realfile, *slash, tempfile[MAXPATHLEN];
2638 realfile = ent->log;
2641 * If this log file is being created for the first time (-C option),
2642 * then it may also be true that the parent directory does not exist
2643 * yet. Check, and create that directory if it is missing.
2645 if (ent->firstcreate) {
2646 strlcpy(tempfile, realfile, sizeof(tempfile));
2647 slash = strrchr(tempfile, '/');
2648 if (slash != NULL) {
2650 failed = stat(tempfile, &st);
2651 if (failed && errno != ENOENT)
2652 err(1, "Error on stat(%s)", tempfile);
2654 createdir(ent, tempfile);
2655 else if (!S_ISDIR(st.st_mode))
2656 errx(1, "%s exists but is not a directory",
2662 * First create an unused filename, so it can be chown'ed and
2663 * chmod'ed before it is moved into the real location. mkstemp
2664 * will create the file mode=600 & owned by us. Note that all
2665 * temp files will have a suffix of '.z<something>'.
2667 strlcpy(tempfile, realfile, sizeof(tempfile));
2668 strlcat(tempfile, ".zXXXXXX", sizeof(tempfile));
2670 printf("\tmktemp %s\n", tempfile);
2672 fd = mkstemp(tempfile);
2674 err(1, "can't mkstemp logfile %s", tempfile);
2677 * Add status message to what will become the new log file.
2679 if (!(ent->flags & CE_BINARY)) {
2680 if (log_trim(tempfile, ent))
2681 err(1, "can't add status message to log");
2685 /* Change the owner/group, if we are supposed to */
2686 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2688 printf("\tchown %u:%u %s\n", ent->uid, ent->gid,
2691 failed = fchown(fd, ent->uid, ent->gid);
2693 err(1, "can't fchown temp file %s", tempfile);
2697 /* Turn on NODUMP if it was requested in the config-file. */
2698 if (ent->flags & CE_NODUMP) {
2700 printf("\tchflags nodump %s\n", tempfile);
2702 failed = fchflags(fd, UF_NODUMP);
2704 warn("log_trim: fchflags(NODUMP)");
2710 * Note that if the real logfile still exists, and if the call
2711 * to rename() fails, then "neither the old file nor the new
2712 * file shall be changed or created" (to quote the standard).
2713 * If the call succeeds, then the file will be replaced without
2714 * any window where some other process might find that the file
2716 * XXX - ? It may be that for some error conditions, we could
2717 * retry by first removing the realfile and then renaming.
2720 printf("\tchmod %o %s\n", ent->permissions, tempfile);
2721 printf("\tmv %s %s\n", tempfile, realfile);
2723 failed = fchmod(fd, ent->permissions);
2725 err(1, "can't fchmod temp file '%s'", tempfile);
2726 failed = rename(tempfile, realfile);
2728 err(1, "can't mv %s to %s", tempfile, realfile);
2736 * Change the attributes of a given filename to what was specified in
2737 * the newsyslog.conf entry. This routine is only called for files
2738 * that newsyslog expects that it has created, and thus it is a fatal
2739 * error if this routine finds that the file does not exist.
2742 change_attrs(const char *fname, const struct conf_entry *ent)
2747 printf("\tchmod %o %s\n", ent->permissions, fname);
2749 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
2750 printf("\tchown %u:%u %s\n",
2751 ent->uid, ent->gid, fname);
2753 if (ent->flags & CE_NODUMP)
2754 printf("\tchflags nodump %s\n", fname);
2758 failed = chmod(fname, ent->permissions);
2761 err(1, "chmod(%s) in change_attrs", fname);
2762 warn("change_attrs couldn't chmod(%s)", fname);
2765 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2766 failed = chown(fname, ent->uid, ent->gid);
2768 warn("can't chown %s", fname);
2771 if (ent->flags & CE_NODUMP) {
2772 failed = chflags(fname, UF_NODUMP);
2774 warn("can't chflags %s NODUMP", fname);
2779 * Parse a signal number or signal name. Returns the signal number parsed or -1
2783 parse_signal(const char *str)
2788 sig = strtonum(str, 1, sys_nsig - 1, &errstr);
2792 if (strncasecmp(str, "SIG", 3) == 0)
2795 for (i = 1; i < sys_nsig; i++) {
2796 if (strcasecmp(str, sys_signame[i]) == 0)