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)
382 static struct conf_entry *
383 init_entry(const char *fname, struct conf_entry *src_entry)
385 struct conf_entry *tempwork;
388 printf("\t--> [creating entry for %s]\n", fname);
390 tempwork = malloc(sizeof(struct conf_entry));
391 if (tempwork == NULL)
392 err(1, "malloc of conf_entry for %s", fname);
394 if (destdir == NULL || fname[0] != '/')
395 tempwork->log = strdup(fname);
397 asprintf(&tempwork->log, "%s%s", destdir, fname);
398 if (tempwork->log == NULL)
399 err(1, "strdup for %s", fname);
401 if (src_entry != NULL) {
402 tempwork->pid_cmd_file = NULL;
403 if (src_entry->pid_cmd_file)
404 tempwork->pid_cmd_file = strdup(src_entry->pid_cmd_file);
405 tempwork->r_reason = NULL;
406 tempwork->firstcreate = 0;
407 tempwork->rotate = 0;
408 tempwork->fsize = -1;
409 tempwork->uid = src_entry->uid;
410 tempwork->gid = src_entry->gid;
411 tempwork->numlogs = src_entry->numlogs;
412 tempwork->trsize = src_entry->trsize;
413 tempwork->hours = src_entry->hours;
414 tempwork->trim_at = NULL;
415 if (src_entry->trim_at != NULL)
416 tempwork->trim_at = ptime_init(src_entry->trim_at);
417 tempwork->permissions = src_entry->permissions;
418 tempwork->flags = src_entry->flags;
419 tempwork->compress = src_entry->compress;
420 tempwork->sig = src_entry->sig;
421 tempwork->def_cfg = src_entry->def_cfg;
423 /* Initialize as a "do-nothing" entry */
424 tempwork->pid_cmd_file = NULL;
425 tempwork->r_reason = NULL;
426 tempwork->firstcreate = 0;
427 tempwork->rotate = 0;
428 tempwork->fsize = -1;
429 tempwork->uid = (uid_t)-1;
430 tempwork->gid = (gid_t)-1;
431 tempwork->numlogs = 1;
432 tempwork->trsize = -1;
433 tempwork->hours = -1;
434 tempwork->trim_at = NULL;
435 tempwork->permissions = 0;
437 tempwork->compress = COMPRESS_NONE;
438 tempwork->sig = SIGHUP;
439 tempwork->def_cfg = 0;
446 free_entry(struct conf_entry *ent)
452 if (ent->log != NULL) {
454 printf("\t--> [freeing entry for %s]\n", ent->log);
459 if (ent->pid_cmd_file != NULL) {
460 free(ent->pid_cmd_file);
461 ent->pid_cmd_file = NULL;
464 if (ent->r_reason != NULL) {
466 ent->r_reason = NULL;
469 if (ent->trim_at != NULL) {
470 ptime_free(ent->trim_at);
478 free_clist(struct cflist *list)
480 struct conf_entry *ent;
482 while (!STAILQ_EMPTY(list)) {
483 ent = STAILQ_FIRST(list);
484 STAILQ_REMOVE_HEAD(list, cf_nextp);
493 do_entry(struct conf_entry * ent)
495 #define REASON_MAX 80
497 fk_entry free_or_keep;
499 char temp_reason[REASON_MAX];
502 free_or_keep = FREE_ENT;
504 printf("%s <%d%s>: ", ent->log, ent->numlogs,
505 compress_type[ent->compress].flag);
506 ent->fsize = sizefile(ent->log);
507 oversized = ((ent->trsize > 0) && (ent->fsize >= ent->trsize));
508 modtime = age_old_log(ent->log);
510 ent->firstcreate = 0;
511 if (ent->fsize < 0) {
513 * If either the C flag or the -C option was specified,
514 * and if we won't be creating the file, then have the
515 * verbose message include a hint as to why the file
516 * will not be created.
518 temp_reason[0] = '\0';
520 ent->firstcreate = 1;
521 else if ((ent->flags & CE_CREATE) && createlogs)
522 ent->firstcreate = 1;
523 else if (ent->flags & CE_CREATE)
524 strlcpy(temp_reason, " (no -C option)", REASON_MAX);
526 strlcpy(temp_reason, " (no C flag)", REASON_MAX);
528 if (ent->firstcreate) {
530 printf("does not exist -> will create.\n");
532 } else if (verbose) {
533 printf("does not exist, skipped%s.\n", temp_reason);
536 if (ent->flags & CE_TRIMAT && !force && !rotatereq &&
538 diffsecs = ptimeget_diff(timenow, ent->trim_at);
539 if (diffsecs < 0.0) {
540 /* trim_at is some time in the future. */
542 ptime_adjust4dst(ent->trim_at,
544 printf("--> will trim at %s",
545 ptimeget_ctime(ent->trim_at));
547 return (free_or_keep);
548 } else if (diffsecs >= 3600.0) {
550 * trim_at is more than an hour in the past,
551 * so find the next valid trim_at time, and
552 * tell the user what that will be.
554 if (verbose && dbg_at_times)
555 printf("\n\t--> prev trim at %s\t",
556 ptimeget_ctime(ent->trim_at));
558 ptimeset_nxtime(ent->trim_at);
559 printf("--> will trim at %s",
560 ptimeget_ctime(ent->trim_at));
562 return (free_or_keep);
563 } else if (verbose && noaction && dbg_at_times) {
565 * If we are just debugging at-times, then
566 * a detailed message is helpful. Also
567 * skip "doing" any commands, since they
568 * would all be turned off by no-action.
570 printf("\n\t--> timematch at %s",
571 ptimeget_ctime(ent->trim_at));
572 return (free_or_keep);
573 } else if (verbose && ent->hours <= 0) {
574 printf("--> time is up\n");
577 if (verbose && (ent->trsize > 0))
578 printf("size (Kb): %d [%d] ", ent->fsize, ent->trsize);
579 if (verbose && (ent->hours > 0))
580 printf(" age (hr): %d [%d] ", modtime, ent->hours);
583 * Figure out if this logfile needs to be rotated.
585 temp_reason[0] = '\0';
588 snprintf(temp_reason, REASON_MAX, " due to -R from %s",
592 snprintf(temp_reason, REASON_MAX, " due to -F request");
593 } else if (oversized) {
595 snprintf(temp_reason, REASON_MAX, " due to size>%dK",
597 } else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) {
599 } else if ((ent->hours > 0) && ((modtime >= ent->hours) ||
605 * If the file needs to be rotated, then rotate it.
607 if (ent->rotate && !norotate) {
608 if (temp_reason[0] != '\0')
609 ent->r_reason = strdup(temp_reason);
611 printf("--> trimming log....\n");
612 if (noaction && !verbose)
613 printf("%s <%d%s>: trimming\n", ent->log,
615 compress_type[ent->compress].flag);
616 free_or_keep = do_rotate(ent);
619 printf("--> skipping\n");
622 return (free_or_keep);
627 parse_args(int argc, char **argv)
632 timenow = ptime_init(NULL);
633 ptimeset_time(timenow, time(NULL));
634 strlcpy(daytime, ptimeget_ctime(timenow) + 4, DAYTIME_LEN);
635 ptimeget_ctime_rfc5424(timenow, daytime_rfc5424, DAYTIME_RFC5424_LEN);
637 /* Let's get our hostname */
638 (void)gethostname(hostname, sizeof(hostname));
639 hostname_shortlen = strcspn(hostname, ".");
641 /* Parse command line options. */
642 while ((ch = getopt(argc, argv, "a:d:f:nrst:vCD:FNPR:S:")) != -1)
646 archdirname = optarg;
664 if (optarg[0] == '\0' ||
665 strcmp(optarg, "DEFAULT") == 0)
666 timefnamefmt = strdup(DEFAULT_TIMEFNAME_FMT);
668 timefnamefmt = strdup(optarg);
674 /* Useful for things like rc.diskless... */
679 * Set some debugging option. The specific option
680 * depends on the value of optarg. These options
681 * may come and go without notice or documentation.
683 if (parse_doption(optarg))
698 requestor = strdup(optarg);
701 path_syslogpid = optarg;
703 case 'm': /* Used by OpenBSD for "monitor mode" */
709 if (force && norotate) {
710 warnx("Only one of -F and -N may be specified.");
716 if (optind == argc) {
717 warnx("At least one filename must be given when -R is specified.");
721 /* Make sure "requestor" value is safe for a syslog message. */
722 for (p = requestor; *p != '\0'; p++) {
723 if (!isprintch(*p) && (*p != '\t'))
730 * Note that the 'daytime' variable is not changed.
731 * That is only used in messages that track when a
732 * logfile is rotated, and if a file *is* rotated,
733 * then it will still rotated at the "real now" time.
736 timenow = dbg_timenow;
737 fprintf(stderr, "Debug: Running as if TimeNow is %s",
738 ptimeget_ctime(dbg_timenow));
744 * These debugging options are mainly meant for developer use, such
745 * as writing regression-tests. They would not be needed by users
746 * during normal operation of newsyslog...
749 parse_doption(const char *doption)
751 const char TN[] = "TN=";
754 if (strncmp(doption, TN, sizeof(TN) - 1) == 0) {
756 * The "TimeNow" debugging option. This might be off
757 * by an hour when crossing a timezone change.
759 dbg_timenow = ptime_init(NULL);
760 res = ptime_relparse(dbg_timenow, PTM_PARSE_ISO8601,
761 time(NULL), doption + sizeof(TN) - 1);
763 warnx("Non-existent time specified on -D %s", doption);
764 return (0); /* failure */
765 } else if (res < 0) {
766 warnx("Malformed time given on -D %s", doption);
767 return (0); /* failure */
769 return (1); /* successfully parsed */
773 if (strcmp(doption, "ats") == 0) {
775 return (1); /* successfully parsed */
778 /* XXX - This check could probably be dropped. */
779 if ((strcmp(doption, "neworder") == 0) || (strcmp(doption, "oldorder")
781 warnx("NOTE: newsyslog always uses 'neworder'.");
782 return (1); /* successfully parsed */
785 warnx("Unknown -D (debug) option: '%s'", doption);
786 return (0); /* failure */
794 "usage: newsyslog [-CFNPnrsv] [-a directory] [-d directory] [-f config_file]\n"
795 " [-S pidfile] [-t timefmt] [[-R tagname] file ...]\n");
796 /* Free global dynamically-allocated storage. */
803 * Parse a configuration file and return a linked list of all the logs
804 * which should be processed.
806 static struct cflist *
807 get_worklist(char **files)
811 struct cflist *cmdlist, *filelist, *globlist;
812 struct conf_entry *defconf, *dupent, *ent;
813 struct ilist inclist;
814 struct include_entry *inc;
818 STAILQ_INIT(&inclist);
820 filelist = malloc(sizeof(struct cflist));
821 if (filelist == NULL)
822 err(1, "malloc of filelist");
823 STAILQ_INIT(filelist);
824 globlist = malloc(sizeof(struct cflist));
825 if (globlist == NULL)
826 err(1, "malloc of globlist");
827 STAILQ_INIT(globlist);
829 inc = malloc(sizeof(struct include_entry));
831 err(1, "malloc of inc");
833 if (inc->file == NULL)
834 inc->file = _PATH_CONF;
835 STAILQ_INSERT_TAIL(&inclist, inc, inc_nextp);
837 STAILQ_FOREACH(inc, &inclist, inc_nextp) {
838 if (strcmp(inc->file, "-") != 0)
839 f = fopen(inc->file, "r");
842 inc->file = "<stdin>";
845 err(1, "%s", inc->file);
848 printf("Processing %s\n", inc->file);
849 parse_file(f, filelist, globlist, &defconf, &inclist);
854 * All config-file information has been read in and turned into
855 * a filelist and a globlist. If there were no specific files
856 * given on the run command, then the only thing left to do is to
857 * call a routine which finds all files matched by the globlist
858 * and adds them to the filelist. Then return the worklist.
860 if (*files == NULL) {
861 expand_globs(filelist, globlist);
862 free_clist(globlist);
869 * If newsyslog was given a specific list of files to process,
870 * it may be that some of those files were not listed in any
871 * config file. Those unlisted files should get the default
872 * rotation action. First, create the default-rotation action
873 * if none was found in a system config file.
875 if (defconf == NULL) {
876 defconf = init_entry(DEFAULT_MARKER, NULL);
877 defconf->numlogs = 3;
878 defconf->trsize = 50;
879 defconf->permissions = S_IRUSR|S_IWUSR;
883 * If newsyslog was run with a list of specific filenames,
884 * then create a new worklist which has only those files in
885 * it, picking up the rotation-rules for those files from
886 * the original filelist.
888 * XXX - Note that this will copy multiple rules for a single
889 * logfile, if multiple entries are an exact match for
890 * that file. That matches the historic behavior, but do
891 * we want to continue to allow it? If so, it should
892 * probably be handled more intelligently.
894 cmdlist = malloc(sizeof(struct cflist));
896 err(1, "malloc of cmdlist");
897 STAILQ_INIT(cmdlist);
899 for (given = files; *given; ++given) {
901 * First try to find exact-matches for this given file.
904 STAILQ_FOREACH(ent, filelist, cf_nextp) {
905 if (strcmp(ent->log, *given) == 0) {
907 dupent = init_entry(*given, ent);
908 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
913 printf("\t+ Matched entry %s\n", *given);
918 * There was no exact-match for this given file, so look
919 * for a "glob" entry which does match.
923 printf("\t+ Checking globs for %s\n", *given);
924 STAILQ_FOREACH(ent, globlist, cf_nextp) {
925 fnres = fnmatch(ent->log, *given, FNM_PATHNAME);
927 printf("\t+ = %d for pattern %s\n", fnres,
931 dupent = init_entry(*given, ent);
932 /* This new entry is not a glob! */
933 dupent->flags &= ~CE_GLOB;
934 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
935 /* Only allow a match to one glob-entry */
941 printf("\t+ Matched %s via %s\n", *given,
947 * This given file was not found in any config file, so
948 * add a worklist item based on the default entry.
951 printf("\t+ No entry matched %s (will use %s)\n",
952 *given, DEFAULT_MARKER);
953 dupent = init_entry(*given, defconf);
954 /* Mark that it was *not* found in a config file */
956 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
960 * Free all the entries in the original work list, the list of
961 * glob entries, and the default entry.
963 free_clist(filelist);
964 free_clist(globlist);
967 /* And finally, return a worklist which matches the given files. */
972 * Expand the list of entries with filename patterns, and add all files
973 * which match those glob-entries onto the worklist.
976 expand_globs(struct cflist *work_p, struct cflist *glob_p)
981 struct conf_entry *dupent, *ent, *globent;
986 * The worklist contains all fully-specified (non-GLOB) names.
988 * Now expand the list of filename-pattern (GLOB) entries into
989 * a second list, which (by definition) will only match files
990 * that already exist. Do not add a glob-related entry for any
991 * file which already exists in the fully-specified list.
993 STAILQ_FOREACH(globent, glob_p, cf_nextp) {
994 gres = glob(globent->log, GLOB_NOCHECK, NULL, &pglob);
996 warn("cannot expand pattern (%d): %s", gres,
1002 printf("\t+ Expanding pattern %s\n", globent->log);
1003 for (i = 0; i < pglob.gl_matchc; i++) {
1004 mfname = pglob.gl_pathv[i];
1006 /* See if this file already has a specific entry. */
1008 STAILQ_FOREACH(ent, work_p, cf_nextp) {
1009 if (strcmp(mfname, ent->log) == 0) {
1017 /* Make sure the named matched is a file. */
1018 gres = lstat(mfname, &st_fm);
1020 /* Error on a file that glob() matched?!? */
1021 warn("Skipping %s - lstat() error", mfname);
1024 if (!S_ISREG(st_fm.st_mode)) {
1025 /* We only rotate files! */
1027 printf("\t+ . skipping %s (!file)\n",
1033 printf("\t+ . add file %s\n", mfname);
1034 dupent = init_entry(mfname, globent);
1035 /* This new entry is not a glob! */
1036 dupent->flags &= ~CE_GLOB;
1038 /* Add to the worklist. */
1039 STAILQ_INSERT_TAIL(work_p, dupent, cf_nextp);
1043 printf("\t+ Done with pattern %s\n", globent->log);
1048 * Parse a configuration file and update a linked list of all the logs to
1052 parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
1053 struct conf_entry **defconf_p, struct ilist *inclist)
1055 char line[BUFSIZ], *parse, *q;
1056 char *cp, *errline, *group;
1057 struct conf_entry *working;
1061 int eol, ptm_opts, res, special;
1065 while (fgets(line, BUFSIZ, cf)) {
1066 if ((line[0] == '\n') || (line[0] == '#') ||
1067 (strlen(line) == 0))
1069 if (errline != NULL)
1071 errline = strdup(line);
1072 for (cp = line + 1; *cp != '\0'; cp++) {
1075 if (*(cp - 1) == '\\') {
1084 q = parse = missing_field(sob(line), errline);
1087 errx(1, "malformed line (missing fields):\n%s",
1092 * Allow people to set debug options via the config file.
1093 * (NOTE: debug options are undocumented, and may disappear
1094 * at any time, etc).
1096 if (strcasecmp(DEBUG_MARKER, q) == 0) {
1097 q = parse = missing_field(sob(parse + 1), errline);
1100 warnx("debug line specifies no option:\n%s",
1107 } else if (strcasecmp(INCLUDE_MARKER, q) == 0) {
1109 printf("Found: %s", errline);
1110 q = parse = missing_field(sob(parse + 1), errline);
1113 warnx("include line missing argument:\n%s",
1121 res = glob(q, GLOB_NOCHECK, NULL, &pglob);
1123 warn("cannot expand pattern (%d): %s",
1129 printf("\t+ Expanding pattern %s\n", q);
1131 for (i = 0; i < pglob.gl_matchc; i++)
1132 add_to_queue(pglob.gl_pathv[i],
1136 add_to_queue(q, inclist);
1141 working = init_entry(q, NULL);
1142 if (strcasecmp(DEFAULT_MARKER, q) == 0) {
1144 if (*defconf_p != NULL) {
1145 warnx("Ignoring duplicate entry for %s!", q);
1146 free_entry(working);
1149 *defconf_p = working;
1152 q = parse = missing_field(sob(parse + 1), errline);
1155 errx(1, "malformed line (missing fields):\n%s",
1158 if ((group = strchr(q, ':')) != NULL ||
1159 (group = strrchr(q, '.')) != NULL) {
1162 if (!(isnumberstr(q))) {
1163 if ((pwd = getpwnam(q)) == NULL)
1165 "error in config file; unknown user:\n%s",
1167 working->uid = pwd->pw_uid;
1169 working->uid = atoi(q);
1171 working->uid = (uid_t)-1;
1175 if (!(isnumberstr(q))) {
1176 if ((grp = getgrnam(q)) == NULL)
1178 "error in config file; unknown group:\n%s",
1180 working->gid = grp->gr_gid;
1182 working->gid = atoi(q);
1184 working->gid = (gid_t)-1;
1186 q = parse = missing_field(sob(parse + 1), errline);
1189 errx(1, "malformed line (missing fields):\n%s",
1193 working->uid = (uid_t)-1;
1194 working->gid = (gid_t)-1;
1197 if (!sscanf(q, "%o", &working->permissions))
1198 errx(1, "error in config file; bad permissions:\n%s",
1200 if ((working->permissions & ~DEFFILEMODE) != 0) {
1201 warnx("File mode bits 0%o changed to 0%o in line:\n%s",
1202 working->permissions,
1203 working->permissions & DEFFILEMODE, errline);
1204 working->permissions &= DEFFILEMODE;
1207 q = parse = missing_field(sob(parse + 1), errline);
1210 errx(1, "malformed line (missing fields):\n%s",
1213 if (!sscanf(q, "%d", &working->numlogs) || working->numlogs < 0)
1214 errx(1, "error in config file; bad value for count of logs to save:\n%s",
1217 q = parse = missing_field(sob(parse + 1), errline);
1220 errx(1, "malformed line (missing fields):\n%s",
1224 working->trsize = atoi(q);
1225 else if (strcmp(q, "*") == 0)
1226 working->trsize = -1;
1228 warnx("Invalid value of '%s' for 'size' in line:\n%s",
1230 working->trsize = -1;
1234 working->compress = COMPRESS_NONE;
1235 q = parse = missing_field(sob(parse + 1), errline);
1243 ul = strtoul(q, &ep, 10);
1246 else if (*ep == '*')
1247 working->hours = -1;
1248 else if (ul > INT_MAX)
1249 errx(1, "interval is too large:\n%s", errline);
1251 working->hours = ul;
1253 if (*ep == '\0' || strcmp(ep, "*") == 0)
1255 if (*ep != '@' && *ep != '$')
1256 errx(1, "malformed interval/at:\n%s", errline);
1258 working->flags |= CE_TRIMAT;
1259 working->trim_at = ptime_init(NULL);
1260 ptm_opts = PTM_PARSE_ISO8601;
1262 ptm_opts = PTM_PARSE_DWM;
1263 ptm_opts |= PTM_PARSE_MATCHDOM;
1264 res = ptime_relparse(working->trim_at, ptm_opts,
1265 ptimeget_secs(timenow), ep + 1);
1267 errx(1, "nonexistent time for 'at' value:\n%s",
1270 errx(1, "malformed 'at' value:\n%s", errline);
1277 q = parse = sob(parse + 1); /* Optional field */
1284 for (; q && *q && !isspacech(*q); q++) {
1285 switch (tolowerch(*q)) {
1287 working->flags |= CE_BINARY;
1290 working->flags |= CE_CREATE;
1293 working->flags |= CE_NODUMP;
1296 working->flags |= CE_GLOB;
1299 working->compress = COMPRESS_BZIP2;
1302 working->flags |= CE_NOSIGNAL;
1305 working->flags |= CE_PLAIN0;
1308 working->flags |= CE_PID2CMD;
1311 working->flags |= CE_RFC5424;
1314 working->flags |= CE_SIGNALGROUP;
1317 /* Deprecated flag - keep for compatibility purposes */
1320 working->compress = COMPRESS_XZ;
1323 working->compress = COMPRESS_ZSTD;
1326 working->compress = COMPRESS_GZIP;
1330 case 'f': /* Used by OpenBSD for "CE_FOLLOW" */
1331 case 'm': /* Used by OpenBSD for "CE_MONITOR" */
1333 errx(1, "illegal flag in config file -- %c",
1341 q = parse = sob(parse + 1); /* Optional field */
1348 working->pid_cmd_file = NULL;
1351 working->pid_cmd_file = strdup(q);
1352 else if (isalnum(*q))
1356 "illegal pid file or signal in config file:\n%s",
1363 q = parse = sob(parse + 1); /* Optional field */
1368 working->sig = SIGHUP;
1371 working->sig = parse_signal(q);
1372 if (working->sig < 1 || working->sig >= sys_nsig) {
1374 "illegal signal in config file:\n%s",
1380 * Finish figuring out what pid-file to use (if any) in
1381 * later processing if this logfile needs to be rotated.
1383 if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) {
1385 * This config-entry specified 'n' for nosignal,
1386 * see if it also specified an explicit pid_cmd_file.
1387 * This would be a pretty pointless combination.
1389 if (working->pid_cmd_file != NULL) {
1390 warnx("Ignoring '%s' because flag 'n' was specified in line:\n%s",
1391 working->pid_cmd_file, errline);
1392 free(working->pid_cmd_file);
1393 working->pid_cmd_file = NULL;
1395 } else if (working->pid_cmd_file == NULL) {
1397 * This entry did not specify the 'n' flag, which
1398 * means it should signal syslogd unless it had
1399 * specified some other pid-file (and obviously the
1400 * syslog pid-file will not be for a process-group).
1401 * Also, we should only try to notify syslog if we
1404 if (working->flags & CE_SIGNALGROUP) {
1405 warnx("Ignoring flag 'U' in line:\n%s",
1407 working->flags &= ~CE_SIGNALGROUP;
1410 working->pid_cmd_file = strdup(path_syslogpid);
1414 * Add this entry to the appropriate list of entries, unless
1415 * it was some kind of special entry (eg: <default>).
1418 ; /* Do not add to any list */
1419 } else if (working->flags & CE_GLOB) {
1420 STAILQ_INSERT_TAIL(glob_p, working, cf_nextp);
1422 STAILQ_INSERT_TAIL(work_p, working, cf_nextp);
1425 if (errline != NULL)
1430 missing_field(char *p, char *errline)
1434 errx(1, "missing field in config file:\n%s", errline);
1439 * In our sort we return it in the reverse of what qsort normally
1440 * would do, as we want the newest files first. If we have two
1441 * entries with the same time we don't really care about order.
1443 * Support function for qsort() in delete_oldest_timelog().
1446 oldlog_entry_compare(const void *a, const void *b)
1448 const struct oldlog_entry *ola = a, *olb = b;
1450 if (ola->t > olb->t)
1452 else if (ola->t < olb->t)
1459 * Check whether the file corresponding to dp is an archive of the logfile
1460 * logfname, based on the timefnamefmt format string. Return true and fill out
1461 * tm if this is the case; otherwise return false.
1464 validate_old_timelog(int fd, const struct dirent *dp, const char *logfname,
1468 size_t logfname_len;
1472 logfname_len = strlen(logfname);
1474 if (dp->d_type != DT_REG) {
1476 * Some filesystems (e.g. NFS) don't fill out the d_type field
1477 * and leave it set to DT_UNKNOWN; in this case we must obtain
1478 * the file type ourselves.
1480 if (dp->d_type != DT_UNKNOWN ||
1481 fstatat(fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) != 0 ||
1482 !S_ISREG(sb.st_mode))
1485 /* Ignore everything but files with our logfile prefix. */
1486 if (strncmp(dp->d_name, logfname, logfname_len) != 0)
1488 /* Ignore the actual non-rotated logfile. */
1489 if (dp->d_namlen == logfname_len)
1493 * Make sure we created have found a logfile, so the
1494 * postfix is valid, IE format is: '.<time>(.[bgx]z)?'.
1496 if (dp->d_name[logfname_len] != '.') {
1498 printf("Ignoring %s which has unexpected "
1499 "extension '%s'\n", dp->d_name,
1500 &dp->d_name[logfname_len]);
1503 memset(tm, 0, sizeof(*tm));
1504 if ((s = strptime(&dp->d_name[logfname_len + 1],
1505 timefnamefmt, tm)) == NULL) {
1507 * We could special case "old" sequentially named logfiles here,
1508 * but we do not as that would require special handling to
1509 * decide which one was the oldest compared to "new" time based
1513 printf("Ignoring %s which does not "
1514 "match time format\n", dp->d_name);
1518 for (c = 0; c < COMPRESS_TYPES; c++)
1519 if (strcmp(s, compress_type[c].suffix) == 0)
1524 printf("Ignoring %s which has unexpected extension '%s'\n",
1531 * Delete the oldest logfiles, when using time based filenames.
1534 delete_oldest_timelog(const struct conf_entry *ent, const char *archive_dir)
1536 char *basebuf, *dirbuf, errbuf[80];
1537 const char *base, *dir;
1538 int dir_fd, i, logcnt, max_logcnt;
1539 struct oldlog_entry *oldlogs;
1544 oldlogs = malloc(MAX_OLDLOGS * sizeof(struct oldlog_entry));
1545 max_logcnt = MAX_OLDLOGS;
1548 if (archive_dir != NULL && archive_dir[0] != '\0') {
1552 if ((dirbuf = strdup(ent->log)) == NULL)
1554 dir = dirname(dirbuf);
1557 if ((basebuf = strdup(ent->log)) == NULL)
1559 base = basename(basebuf);
1560 if (strcmp(base, "/") == 0)
1561 errx(1, "Invalid log filename - became '/'");
1564 printf("Searching for old logs in %s\n", dir);
1566 /* First we create a 'list' of all archived logfiles */
1567 if ((dirp = opendir(dir)) == NULL)
1568 err(1, "Cannot open log directory '%s'", dir);
1569 dir_fd = dirfd(dirp);
1570 while ((dp = readdir(dirp)) != NULL) {
1571 if (validate_old_timelog(dir_fd, dp, base, &tm) == 0)
1575 * We should now have old an old rotated logfile, so
1576 * add it to the 'list'.
1578 if ((oldlogs[logcnt].t = timegm(&tm)) == -1)
1579 err(1, "Could not convert time string to time value");
1580 if ((oldlogs[logcnt].fname = strdup(dp->d_name)) == NULL)
1585 * It is very unlikely we ever run out of space in the
1586 * logfile array from the default size, but lets
1587 * handle it anyway...
1589 if (logcnt >= max_logcnt) {
1591 /* Detect integer overflow */
1592 if (max_logcnt < logcnt)
1593 errx(1, "Too many old logfiles found");
1594 oldlogs = realloc(oldlogs,
1595 max_logcnt * sizeof(struct oldlog_entry));
1596 if (oldlogs == NULL)
1597 err(1, "realloc()");
1601 /* Second, if needed we delete oldest archived logfiles */
1602 if (logcnt > 0 && logcnt >= ent->numlogs && ent->numlogs > 1) {
1603 oldlogs = realloc(oldlogs, logcnt *
1604 sizeof(struct oldlog_entry));
1605 if (oldlogs == NULL)
1606 err(1, "realloc()");
1609 * We now sort the logs in the order of newest to
1610 * oldest. That way we can simply skip over the
1611 * number of records we want to keep.
1613 qsort(oldlogs, logcnt, sizeof(struct oldlog_entry),
1614 oldlog_entry_compare);
1615 for (i = ent->numlogs - 1; i < logcnt; i++) {
1617 printf("\trm -f %s/%s\n", dir,
1619 else if (unlinkat(dir_fd, oldlogs[i].fname, 0) != 0) {
1620 snprintf(errbuf, sizeof(errbuf),
1621 "Could not delete old logfile '%s'",
1626 } else if (verbose > 1)
1627 printf("No old logs to delete for logfile %s\n", ent->log);
1629 /* Third, cleanup */
1631 for (i = 0; i < logcnt; i++) {
1632 assert(oldlogs[i].fname != NULL);
1633 free(oldlogs[i].fname);
1641 * Generate a log filename, when using classic filenames.
1644 gen_classiclog_fname(char *fname, size_t fname_sz, const char *archive_dir,
1645 const char *namepart, int numlogs_c)
1648 if (archive_dir[0] != '\0')
1649 (void) snprintf(fname, fname_sz, "%s/%s.%d", archive_dir,
1650 namepart, numlogs_c);
1652 (void) snprintf(fname, fname_sz, "%s.%d", namepart, numlogs_c);
1656 * Delete a rotated logfile, when using classic filenames.
1659 delete_classiclog(const char *archive_dir, const char *namepart, int numlog_c)
1661 char file1[MAXPATHLEN], zfile1[MAXPATHLEN];
1664 gen_classiclog_fname(file1, sizeof(file1), archive_dir, namepart,
1667 for (c = 0; c < COMPRESS_TYPES; c++) {
1668 (void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1669 compress_type[c].suffix);
1671 printf("\trm -f %s\n", zfile1);
1673 (void) unlink(zfile1);
1678 * Only add to the queue if the file hasn't already been added. This is
1679 * done to prevent circular include loops.
1682 add_to_queue(const char *fname, struct ilist *inclist)
1684 struct include_entry *inc;
1686 STAILQ_FOREACH(inc, inclist, inc_nextp) {
1687 if (strcmp(fname, inc->file) == 0) {
1688 warnx("duplicate include detected: %s", fname);
1693 inc = malloc(sizeof(struct include_entry));
1695 err(1, "malloc of inc");
1696 inc->file = strdup(fname);
1699 printf("\t+ Adding %s to the processing queue.\n", fname);
1701 STAILQ_INSERT_TAIL(inclist, inc, inc_nextp);
1705 * Search for logfile and return its compression suffix (if supported)
1706 * The suffix detection is first-match in the order of compress_types
1708 * Note: if logfile without suffix exists (uncompressed, COMPRESS_NONE)
1709 * a zero-length string is returned
1712 get_logfile_suffix(const char *logfile)
1715 char zfile[MAXPATHLEN];
1718 for (c = 0; c < COMPRESS_TYPES; c++) {
1719 (void) strlcpy(zfile, logfile, MAXPATHLEN);
1720 (void) strlcat(zfile, compress_type[c].suffix, MAXPATHLEN);
1721 if (lstat(zfile, &st) == 0)
1722 return (compress_type[c].suffix);
1728 do_rotate(const struct conf_entry *ent)
1730 char dirpart[MAXPATHLEN], namepart[MAXPATHLEN];
1731 char file1[MAXPATHLEN], file2[MAXPATHLEN];
1732 char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN];
1733 const char *logfile_suffix;
1734 char datetimestr[30];
1735 int flags, numlogs_c;
1736 fk_entry free_or_keep;
1737 struct sigwork_entry *swork;
1743 free_or_keep = FREE_ENT;
1748 /* build complete name of archive directory into dirpart */
1749 if (*archdirname == '/') { /* absolute */
1750 strlcpy(dirpart, archdirname, sizeof(dirpart));
1751 } else { /* relative */
1752 /* get directory part of logfile */
1753 strlcpy(dirpart, ent->log, sizeof(dirpart));
1754 if ((p = strrchr(dirpart, '/')) == NULL)
1758 strlcat(dirpart, archdirname, sizeof(dirpart));
1761 /* check if archive directory exists, if not, create it */
1762 if (lstat(dirpart, &st))
1763 createdir(ent, dirpart);
1765 /* get filename part of logfile */
1766 if ((p = strrchr(ent->log, '/')) == NULL)
1767 strlcpy(namepart, ent->log, sizeof(namepart));
1769 strlcpy(namepart, p + 1, sizeof(namepart));
1772 * Tell utility functions we are not using an archive
1776 strlcpy(namepart, ent->log, sizeof(namepart));
1779 /* Delete old logs */
1780 if (timefnamefmt != NULL)
1781 delete_oldest_timelog(ent, dirpart);
1784 * Handle cleaning up after legacy newsyslog where we
1785 * kept ent->numlogs + 1 files. This code can go away
1786 * at some point in the future.
1788 delete_classiclog(dirpart, namepart, ent->numlogs);
1790 if (ent->numlogs > 0)
1791 delete_classiclog(dirpart, namepart, ent->numlogs - 1);
1795 if (timefnamefmt != NULL) {
1796 /* If time functions fails we can't really do any sensible */
1797 if (time(&now) == (time_t)-1 ||
1798 localtime_r(&now, &tm) == NULL)
1799 bzero(&tm, sizeof(tm));
1801 strftime(datetimestr, sizeof(datetimestr), timefnamefmt, &tm);
1803 (void) snprintf(file1, sizeof(file1), "%s/%s.%s",
1804 dirpart, namepart, datetimestr);
1806 (void) snprintf(file1, sizeof(file1), "%s.%s",
1807 ent->log, datetimestr);
1809 /* Don't run the code to move down logs */
1812 gen_classiclog_fname(file1, sizeof(file1), dirpart, namepart,
1814 numlogs_c = ent->numlogs - 2; /* copy for countdown */
1817 /* Move down log files */
1818 for (; numlogs_c >= 0; numlogs_c--) {
1819 (void) strlcpy(file2, file1, sizeof(file2));
1821 gen_classiclog_fname(file1, sizeof(file1), dirpart, namepart,
1824 logfile_suffix = get_logfile_suffix(file1);
1825 if (logfile_suffix == NULL)
1827 (void) strlcpy(zfile1, file1, MAXPATHLEN);
1828 (void) strlcpy(zfile2, file2, MAXPATHLEN);
1829 (void) strlcat(zfile1, logfile_suffix, MAXPATHLEN);
1830 (void) strlcat(zfile2, logfile_suffix, MAXPATHLEN);
1833 printf("\tmv %s %s\n", zfile1, zfile2);
1835 /* XXX - Ought to be checking for failure! */
1836 (void)rename(zfile1, zfile2);
1837 change_attrs(zfile2, ent);
1838 if (ent->compress && !strlen(logfile_suffix)) {
1839 /* compress old rotation */
1840 struct zipwork_entry zwork;
1842 memset(&zwork, 0, sizeof(zwork));
1843 zwork.zw_conf = ent;
1844 zwork.zw_fsize = sizefile(zfile2);
1845 strcpy(zwork.zw_fname, zfile2);
1851 if (ent->numlogs > 0) {
1854 * Note that savelog() may succeed with using link()
1855 * for the archtodir case, but there is no good way
1856 * of knowing if it will when doing "noaction", so
1857 * here we claim that it will have to do a copy...
1860 printf("\tcp %s %s\n", ent->log, file1);
1862 printf("\tln %s %s\n", ent->log, file1);
1863 printf("\ttouch %s\t\t"
1864 "# Update mtime for 'when'-interval processing\n",
1867 if (!(flags & CE_BINARY)) {
1868 /* Report the trimming to the old log */
1869 log_trim(ent->log, ent);
1871 savelog(ent->log, file1);
1873 * Interval-based rotations are done using the mtime of
1874 * the most recently archived log, so make sure it gets
1875 * updated during a rotation.
1877 utimes(file1, NULL);
1879 change_attrs(file1, ent);
1882 /* Create the new log file and move it into place */
1884 printf("Start new log...\n");
1888 * Save all signalling and file-compression to be done after log
1889 * files from all entries have been rotated. This way any one
1890 * process will not be sent the same signal multiple times when
1891 * multiple log files had to be rotated.
1894 if (ent->pid_cmd_file != NULL)
1895 swork = save_sigwork(ent);
1896 if (ent->numlogs > 0 && ent->compress > COMPRESS_NONE) {
1897 if (!(ent->flags & CE_PLAIN0) ||
1898 strcmp(&file1[strlen(file1) - 2], ".0") != 0) {
1900 * The zipwork_entry will include a pointer to this
1901 * conf_entry, so the conf_entry should not be freed.
1903 free_or_keep = KEEP_ENT;
1904 save_zipwork(ent, swork, ent->fsize, file1);
1908 return (free_or_keep);
1912 do_sigwork(struct sigwork_entry *swork)
1914 struct sigwork_entry *nextsig;
1918 if (swork->sw_runcmd == 0 && (!(swork->sw_pidok) || swork->sw_pid == 0))
1919 return; /* no work to do... */
1922 * If nosignal (-s) was specified, then do not signal any process.
1923 * Note that a nosignal request triggers a warning message if the
1924 * rotated logfile needs to be compressed, *unless* -R was also
1925 * specified. We assume that an `-sR' request came from a process
1926 * which writes to the logfile, and as such, we assume that process
1927 * has already made sure the logfile is not presently in use. This
1928 * just sets swork->sw_pidok to a special value, and do_zipwork
1929 * will print any necessary warning(s).
1933 swork->sw_pidok = -1;
1938 * Compute the pause between consecutive signals. Use a longer
1939 * sleep time if we will be sending two signals to the same
1940 * daemon or process-group.
1943 nextsig = SLIST_NEXT(swork, sw_nextp);
1944 if (nextsig != NULL) {
1945 if (swork->sw_pid == nextsig->sw_pid)
1952 if (swork->sw_runcmd)
1953 printf("\tsh -c '%s %d'\n", swork->sw_fname,
1956 printf("\tkill -%d %d \t\t# %s\n", swork->sw_signum,
1957 (int)swork->sw_pid, swork->sw_fname);
1959 printf("\tsleep %d\n", secs);
1964 if (swork->sw_runcmd) {
1965 asprintf(&tmp, "%s %d", swork->sw_fname, swork->sw_signum);
1967 warn("can't allocate memory to run %s",
1972 printf("Run command: %s\n", tmp);
1975 warnx("%s: returned non-zero exit code: %d",
1982 kres = kill(swork->sw_pid, swork->sw_signum);
1985 * Assume that "no such process" (ESRCH) is something
1986 * to warn about, but is not an error. Presumably the
1987 * process which writes to the rotated log file(s) is
1988 * gone, in which case we should have no problem with
1989 * compressing the rotated log file(s).
1992 swork->sw_pidok = 0;
1993 warn("can't notify %s, pid %d = %s", swork->sw_pidtype,
1994 (int)swork->sw_pid, swork->sw_fname);
1997 printf("Notified %s pid %d = %s\n", swork->sw_pidtype,
1998 (int)swork->sw_pid, swork->sw_fname);
2001 printf("Pause %d second(s) between signals\n",
2009 do_zipwork(struct zipwork_entry *zwork)
2011 const struct compress_types *ct;
2012 struct sbuf *command;
2014 int c, errsav, fcount, zstatus;
2015 const char **args, *pgm_name, *pgm_path;
2018 assert(zwork != NULL);
2019 assert(zwork->zw_conf != NULL);
2020 assert(zwork->zw_conf->compress > COMPRESS_NONE);
2021 assert(zwork->zw_conf->compress < COMPRESS_TYPES);
2023 if (zwork->zw_swork != NULL && zwork->zw_swork->sw_runcmd == 0 &&
2024 zwork->zw_swork->sw_pidok <= 0) {
2026 "log %s not compressed because daemon(s) not notified",
2028 change_attrs(zwork->zw_fname, zwork->zw_conf);
2032 ct = &compress_type[zwork->zw_conf->compress];
2035 * execv will be called with the array [ program, flags ... ,
2036 * filename, NULL ] so allocate nflags+3 elements for the array.
2038 args = calloc(ct->nflags + 3, sizeof(*args));
2042 pgm_path = ct->path;
2043 pgm_name = strrchr(pgm_path, '/');
2044 if (pgm_name == NULL)
2045 pgm_name = pgm_path;
2049 /* Build the argument array. */
2051 for (c = 0; c < ct->nflags; c++)
2052 args[c + 1] = ct->flags[c];
2053 args[c + 1] = zwork->zw_fname;
2055 /* Also create a space-delimited version if we need to print it. */
2056 if ((command = sbuf_new_auto()) == NULL)
2057 errx(1, "sbuf_new");
2058 sbuf_cpy(command, pgm_path);
2059 for (c = 1; args[c] != NULL; c++) {
2060 sbuf_putc(command, ' ');
2061 sbuf_cat(command, args[c]);
2063 if (sbuf_finish(command) == -1)
2064 err(1, "sbuf_finish");
2066 /* Determine the filename of the compressed file. */
2067 asprintf(&zresult, "%s%s", zwork->zw_fname, ct->suffix);
2068 if (zresult == NULL)
2069 errx(1, "asprintf");
2072 printf("Executing: %s\n", sbuf_data(command));
2075 printf("\t%s %s\n", pgm_name, zwork->zw_fname);
2076 change_attrs(zresult, zwork->zw_conf);
2082 while (pidzip < 0) {
2084 * The fork failed. If the failure was due to a temporary
2085 * problem, then wait a short time and try it again.
2088 warn("fork() for `%s %s'", pgm_name, zwork->zw_fname);
2089 if (errsav != EAGAIN || fcount > 5)
2090 errx(1, "Exiting...");
2096 /* The child process executes the compression command */
2097 execv(pgm_path, __DECONST(char *const*, args));
2098 err(1, "execv(`%s')", sbuf_data(command));
2101 wpid = waitpid(pidzip, &zstatus, 0);
2103 /* XXX - should this be a fatal error? */
2104 warn("%s: waitpid(%d)", pgm_path, pidzip);
2107 if (!WIFEXITED(zstatus)) {
2108 warnx("`%s' did not terminate normally", sbuf_data(command));
2111 if (WEXITSTATUS(zstatus)) {
2112 warnx("`%s' terminated with a non-zero status (%d)",
2113 sbuf_data(command), WEXITSTATUS(zstatus));
2117 /* Compression was successful, set file attributes on the result. */
2118 change_attrs(zresult, zwork->zw_conf);
2121 sbuf_delete(command);
2127 * Save information on any process we need to signal. Any single
2128 * process may need to be sent different signal-values for different
2129 * log files, but usually a single signal-value will cause the process
2130 * to close and re-open all of its log files.
2132 static struct sigwork_entry *
2133 save_sigwork(const struct conf_entry *ent)
2135 struct sigwork_entry *sprev, *stmp;
2141 SLIST_FOREACH(stmp, &swhead, sw_nextp) {
2142 ndiff = strcmp(ent->pid_cmd_file, stmp->sw_fname);
2146 if (ent->sig == stmp->sw_signum)
2148 if (ent->sig > stmp->sw_signum) {
2155 if (stmp != NULL && ndiff == 0)
2158 tmpsiz = sizeof(struct sigwork_entry) + strlen(ent->pid_cmd_file) + 1;
2159 stmp = malloc(tmpsiz);
2161 stmp->sw_runcmd = 0;
2162 /* If this is a command to run we just set the flag and run command */
2163 if (ent->flags & CE_PID2CMD) {
2166 stmp->sw_runcmd = 1;
2168 set_swpid(stmp, ent);
2170 stmp->sw_signum = ent->sig;
2171 strcpy(stmp->sw_fname, ent->pid_cmd_file);
2173 SLIST_INSERT_HEAD(&swhead, stmp, sw_nextp);
2175 SLIST_INSERT_AFTER(sprev, stmp, sw_nextp);
2180 * Save information on any file we need to compress. We may see the same
2181 * file multiple times, so check the full list to avoid duplicates. The
2182 * list itself is sorted smallest-to-largest, because that's the order we
2183 * want to compress the files. If the partition is very low on disk space,
2184 * then the smallest files are the most likely to compress, and compressing
2185 * them first will free up more space for the larger files.
2187 static struct zipwork_entry *
2188 save_zipwork(const struct conf_entry *ent, const struct sigwork_entry *swork,
2189 int zsize, const char *zipfname)
2191 struct zipwork_entry *zprev, *ztmp;
2195 /* Compute the size if the caller did not know it. */
2197 zsize = sizefile(zipfname);
2201 SLIST_FOREACH(ztmp, &zwhead, zw_nextp) {
2202 ndiff = strcmp(zipfname, ztmp->zw_fname);
2205 if (zsize > ztmp->zw_fsize)
2208 if (ztmp != NULL && ndiff == 0)
2211 tmpsiz = sizeof(struct zipwork_entry) + strlen(zipfname) + 1;
2212 ztmp = malloc(tmpsiz);
2213 ztmp->zw_conf = ent;
2214 ztmp->zw_swork = swork;
2215 ztmp->zw_fsize = zsize;
2216 strcpy(ztmp->zw_fname, zipfname);
2218 SLIST_INSERT_HEAD(&zwhead, ztmp, zw_nextp);
2220 SLIST_INSERT_AFTER(zprev, ztmp, zw_nextp);
2224 /* Send a signal to the pid specified by pidfile */
2226 set_swpid(struct sigwork_entry *swork, const struct conf_entry *ent)
2229 long minok, maxok, rval;
2230 char *endp, *linep, line[BUFSIZ];
2234 swork->sw_pidok = 0;
2236 swork->sw_pidtype = "daemon";
2237 if (ent->flags & CE_SIGNALGROUP) {
2239 * If we are expected to signal a process-group when
2240 * rotating this logfile, then the value read in should
2241 * be the negative of a valid process ID.
2245 swork->sw_pidtype = "process-group";
2248 f = fopen(ent->pid_cmd_file, "r");
2250 if (errno == ENOENT && enforcepid == 0) {
2252 * Warn if the PID file doesn't exist, but do
2253 * not consider it an error. Most likely it
2254 * means the process has been terminated,
2255 * so it should be safe to rotate any log
2256 * files that the process would have been using.
2258 swork->sw_pidok = 1;
2259 warnx("pid file doesn't exist: %s", ent->pid_cmd_file);
2261 warn("can't open pid file: %s", ent->pid_cmd_file);
2265 if (fgets(line, BUFSIZ, f) == NULL) {
2267 * Warn if the PID file is empty, but do not consider
2268 * it an error. Most likely it means the process has
2269 * has terminated, so it should be safe to rotate any
2270 * log files that the process would have been using.
2272 if (feof(f) && enforcepid == 0) {
2273 swork->sw_pidok = 1;
2274 warnx("pid/cmd file is empty: %s", ent->pid_cmd_file);
2276 warn("can't read from pid file: %s", ent->pid_cmd_file);
2284 while (*linep == ' ')
2286 rval = strtol(linep, &endp, 10);
2287 if (*endp != '\0' && !isspacech(*endp)) {
2288 warnx("pid file does not start with a valid number: %s",
2290 } else if (rval < minok || rval > maxok) {
2291 warnx("bad value '%ld' for process number in %s",
2292 rval, ent->pid_cmd_file);
2294 warnx("\t(expecting value between %ld and %ld)",
2297 swork->sw_pidok = 1;
2298 swork->sw_pid = rval;
2304 /* Log the fact that the logs were turned over */
2306 log_trim(const char *logname, const struct conf_entry *log_ent)
2311 if ((f = fopen(logname, "a")) == NULL)
2314 if (log_ent->def_cfg)
2315 xtra = " using <default> rule";
2316 if (log_ent->flags & CE_RFC5424) {
2317 if (log_ent->firstcreate) {
2318 fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s\n",
2319 LOG_MAKEPRI(LOG_USER, LOG_INFO),
2320 daytime_rfc5424, hostname, getpid(),
2321 "logfile first created", xtra);
2322 } else if (log_ent->r_reason != NULL) {
2323 fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s%s\n",
2324 LOG_MAKEPRI(LOG_USER, LOG_INFO),
2325 daytime_rfc5424, hostname, getpid(),
2326 "logfile turned over", log_ent->r_reason, xtra);
2328 fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s\n",
2329 LOG_MAKEPRI(LOG_USER, LOG_INFO),
2330 daytime_rfc5424, hostname, getpid(),
2331 "logfile turned over", xtra);
2334 if (log_ent->firstcreate)
2336 "%s %.*s newsyslog[%d]: logfile first created%s\n",
2337 daytime, (int)hostname_shortlen, hostname, getpid(),
2339 else if (log_ent->r_reason != NULL)
2341 "%s %.*s newsyslog[%d]: logfile turned over%s%s\n",
2342 daytime, (int)hostname_shortlen, hostname, getpid(),
2343 log_ent->r_reason, xtra);
2346 "%s %.*s newsyslog[%d]: logfile turned over%s\n",
2347 daytime, (int)hostname_shortlen, hostname, getpid(),
2350 if (fclose(f) == EOF)
2351 err(1, "log_trim: fclose");
2355 /* Return size in kilobytes of a file */
2357 sizefile(const char *file)
2361 if (stat(file, &sb) < 0)
2363 return (kbytes(sb.st_size));
2367 * Return the mtime of the most recent archive of the logfile, using timestamp
2371 mtime_old_timelog(const char *file)
2379 char *logfname, *logfnamebuf, *dir, *dirbuf;
2383 if ((dirbuf = strdup(file)) == NULL) {
2384 warn("strdup() of '%s'", file);
2387 dir = dirname(dirbuf);
2388 if ((logfnamebuf = strdup(file)) == NULL) {
2389 warn("strdup() of '%s'", file);
2393 logfname = basename(logfnamebuf);
2394 if (logfname[0] == '/') {
2395 warnx("Invalid log filename '%s'", logfname);
2399 if ((dirp = opendir(dir)) == NULL) {
2400 warn("Cannot open log directory '%s'", dir);
2403 dir_fd = dirfd(dirp);
2404 /* Open the archive dir and find the most recent archive of logfname. */
2405 while ((dp = readdir(dirp)) != NULL) {
2406 if (validate_old_timelog(dir_fd, dp, logfname, &tm) == 0)
2409 if (fstatat(dir_fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
2410 warn("Cannot stat '%s'", file);
2413 if (t < sb.st_mtime)
2424 /* Return the age in hours of the most recent archive of the logfile. */
2426 age_old_log(const char *file)
2429 const char *logfile_suffix;
2430 static unsigned int suffix_maxlen = 0;
2436 if (suffix_maxlen == 0) {
2437 for (c = 0; c < COMPRESS_TYPES; c++)
2438 suffix_maxlen = MAX(suffix_maxlen,
2439 strlen(compress_type[c].suffix));
2442 tmpsiz = MAXPATHLEN + sizeof(".0") + suffix_maxlen + 1;
2443 tmp = alloca(tmpsiz);
2448 /* build name of archive directory into tmp */
2449 if (*archdirname == '/') { /* absolute */
2450 strlcpy(tmp, archdirname, tmpsiz);
2451 } else { /* relative */
2452 /* get directory part of logfile */
2453 strlcpy(tmp, file, tmpsiz);
2454 if ((p = strrchr(tmp, '/')) == NULL)
2458 strlcat(tmp, archdirname, tmpsiz);
2461 strlcat(tmp, "/", tmpsiz);
2463 /* get filename part of logfile */
2464 if ((p = strrchr(file, '/')) == NULL)
2465 strlcat(tmp, file, tmpsiz);
2467 strlcat(tmp, p + 1, tmpsiz);
2469 (void) strlcpy(tmp, file, tmpsiz);
2472 if (timefnamefmt != NULL) {
2473 mtime = mtime_old_timelog(tmp);
2477 strlcat(tmp, ".0", tmpsiz);
2478 logfile_suffix = get_logfile_suffix(tmp);
2479 if (logfile_suffix == NULL)
2481 (void) strlcat(tmp, logfile_suffix, tmpsiz);
2482 if (stat(tmp, &sb) < 0)
2484 mtime = sb.st_mtime;
2487 return ((int)(ptimeget_secs(timenow) - mtime + 1800) / 3600);
2490 /* Skip Over Blanks */
2494 while (p && *p && isspace(*p))
2499 /* Skip Over Non-Blanks */
2503 while (p && *p && !isspace(*p))
2508 /* Check if string is actually a number */
2510 isnumberstr(const char *string)
2513 if (!isdigitch(*string++))
2519 /* Check if string contains a glob */
2521 isglobstr(const char *string)
2525 while ((chr = *string++)) {
2526 if (chr == '*' || chr == '?' || chr == '[')
2533 * Save the active log file under a new name. A link to the new name
2534 * is the quick-and-easy way to do this. If that fails (which it will
2535 * if the destination is on another partition), then make a copy of
2536 * the file to the new location.
2539 savelog(char *from, char *to)
2544 res = link(from, to);
2548 if ((src = fopen(from, "r")) == NULL)
2549 err(1, "can't fopen %s for reading", from);
2550 if ((dst = fopen(to, "w")) == NULL)
2551 err(1, "can't fopen %s for writing", to);
2553 while ((c = getc(src)) != EOF) {
2554 if ((putc(c, dst)) == EOF)
2555 err(1, "error writing to %s", to);
2559 err(1, "error reading from %s", from);
2560 if ((fclose(src)) != 0)
2561 err(1, "can't fclose %s", to);
2562 if ((fclose(dst)) != 0)
2563 err(1, "can't fclose %s", from);
2566 /* create one or more directory components of a path */
2568 createdir(const struct conf_entry *ent, char *dirpart)
2572 char mkdirpath[MAXPATHLEN];
2580 if (*s != '/' && *s != '\0')
2583 res = lstat(mkdirpath, &st);
2586 printf("\tmkdir %s\n", mkdirpath);
2588 res = mkdir(mkdirpath, 0755);
2590 err(1, "Error on mkdir(\"%s\") for -a",
2598 if (ent->firstcreate)
2599 printf("Created directory '%s' for new %s\n",
2602 printf("Created directory '%s' for -a\n", dirpart);
2607 * Create a new log file, destroying any currently-existing version
2608 * of the log file in the process. If the caller wants a backup copy
2609 * of the file to exist, they should call 'link(logfile,logbackup)'
2610 * before calling this routine.
2613 createlog(const struct conf_entry *ent)
2617 char *realfile, *slash, tempfile[MAXPATHLEN];
2620 realfile = ent->log;
2623 * If this log file is being created for the first time (-C option),
2624 * then it may also be true that the parent directory does not exist
2625 * yet. Check, and create that directory if it is missing.
2627 if (ent->firstcreate) {
2628 strlcpy(tempfile, realfile, sizeof(tempfile));
2629 slash = strrchr(tempfile, '/');
2630 if (slash != NULL) {
2632 failed = stat(tempfile, &st);
2633 if (failed && errno != ENOENT)
2634 err(1, "Error on stat(%s)", tempfile);
2636 createdir(ent, tempfile);
2637 else if (!S_ISDIR(st.st_mode))
2638 errx(1, "%s exists but is not a directory",
2644 * First create an unused filename, so it can be chown'ed and
2645 * chmod'ed before it is moved into the real location. mkstemp
2646 * will create the file mode=600 & owned by us. Note that all
2647 * temp files will have a suffix of '.z<something>'.
2649 strlcpy(tempfile, realfile, sizeof(tempfile));
2650 strlcat(tempfile, ".zXXXXXX", sizeof(tempfile));
2652 printf("\tmktemp %s\n", tempfile);
2654 fd = mkstemp(tempfile);
2656 err(1, "can't mkstemp logfile %s", tempfile);
2659 * Add status message to what will become the new log file.
2661 if (!(ent->flags & CE_BINARY)) {
2662 if (log_trim(tempfile, ent))
2663 err(1, "can't add status message to log");
2667 /* Change the owner/group, if we are supposed to */
2668 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2670 printf("\tchown %u:%u %s\n", ent->uid, ent->gid,
2673 failed = fchown(fd, ent->uid, ent->gid);
2675 err(1, "can't fchown temp file %s", tempfile);
2679 /* Turn on NODUMP if it was requested in the config-file. */
2680 if (ent->flags & CE_NODUMP) {
2682 printf("\tchflags nodump %s\n", tempfile);
2684 failed = fchflags(fd, UF_NODUMP);
2686 warn("log_trim: fchflags(NODUMP)");
2692 * Note that if the real logfile still exists, and if the call
2693 * to rename() fails, then "neither the old file nor the new
2694 * file shall be changed or created" (to quote the standard).
2695 * If the call succeeds, then the file will be replaced without
2696 * any window where some other process might find that the file
2698 * XXX - ? It may be that for some error conditions, we could
2699 * retry by first removing the realfile and then renaming.
2702 printf("\tchmod %o %s\n", ent->permissions, tempfile);
2703 printf("\tmv %s %s\n", tempfile, realfile);
2705 failed = fchmod(fd, ent->permissions);
2707 err(1, "can't fchmod temp file '%s'", tempfile);
2708 failed = rename(tempfile, realfile);
2710 err(1, "can't mv %s to %s", tempfile, realfile);
2718 * Change the attributes of a given filename to what was specified in
2719 * the newsyslog.conf entry. This routine is only called for files
2720 * that newsyslog expects that it has created, and thus it is a fatal
2721 * error if this routine finds that the file does not exist.
2724 change_attrs(const char *fname, const struct conf_entry *ent)
2729 printf("\tchmod %o %s\n", ent->permissions, fname);
2731 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
2732 printf("\tchown %u:%u %s\n",
2733 ent->uid, ent->gid, fname);
2735 if (ent->flags & CE_NODUMP)
2736 printf("\tchflags nodump %s\n", fname);
2740 failed = chmod(fname, ent->permissions);
2743 err(1, "chmod(%s) in change_attrs", fname);
2744 warn("change_attrs couldn't chmod(%s)", fname);
2747 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2748 failed = chown(fname, ent->uid, ent->gid);
2750 warn("can't chown %s", fname);
2753 if (ent->flags & CE_NODUMP) {
2754 failed = chflags(fname, UF_NODUMP);
2756 warn("can't chflags %s NODUMP", fname);
2761 * Parse a signal number or signal name. Returns the signal number parsed or -1
2765 parse_signal(const char *str)
2770 sig = strtonum(str, 1, sys_nsig - 1, &errstr);
2774 if (strncasecmp(str, "SIG", 3) == 0)
2777 for (i = 1; i < sys_nsig; i++) {
2778 if (strcasecmp(str, sys_signame[i]) == 0)