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>
86 #include "pathnames.h"
90 * Compression suffixes
92 #ifndef COMPRESS_SUFFIX_GZ
93 #define COMPRESS_SUFFIX_GZ ".gz"
96 #ifndef COMPRESS_SUFFIX_BZ2
97 #define COMPRESS_SUFFIX_BZ2 ".bz2"
100 #ifndef COMPRESS_SUFFIX_XZ
101 #define COMPRESS_SUFFIX_XZ ".xz"
104 #ifndef COMPRESS_SUFFIX_ZST
105 #define COMPRESS_SUFFIX_ZST ".zst"
108 #define COMPRESS_SUFFIX_MAXLEN MAX(MAX(sizeof(COMPRESS_SUFFIX_GZ),sizeof(COMPRESS_SUFFIX_BZ2)),sizeof(COMPRESS_SUFFIX_XZ))
113 #define COMPRESS_TYPES 5 /* Number of supported compression types */
115 #define COMPRESS_NONE 0
116 #define COMPRESS_GZIP 1
117 #define COMPRESS_BZIP2 2
118 #define COMPRESS_XZ 3
119 #define COMPRESS_ZSTD 4
122 * Bit-values for the 'flags' parsed from a config-file entry.
124 #define CE_BINARY 0x0008 /* Logfile is in binary, do not add status */
125 /* messages to logfile(s) when rotating. */
126 #define CE_NOSIGNAL 0x0010 /* There is no process to signal when */
127 /* trimming this file. */
128 #define CE_TRIMAT 0x0020 /* trim file at a specific time. */
129 #define CE_GLOB 0x0040 /* name of the log is file name pattern. */
130 #define CE_SIGNALGROUP 0x0080 /* Signal a process-group instead of a single */
131 /* process when trimming this file. */
132 #define CE_CREATE 0x0100 /* Create the log file if it does not exist. */
133 #define CE_NODUMP 0x0200 /* Set 'nodump' on newly created log file. */
134 #define CE_PID2CMD 0x0400 /* Replace PID file with a shell command.*/
136 #define CE_RFC5424 0x0800 /* Use RFC5424 format rotation message */
138 #define MIN_PID 5 /* Don't touch pids lower than this */
139 #define MAX_PID 99999 /* was lower, see /usr/include/sys/proc.h */
141 #define kbytes(size) (((size) + 1023) >> 10)
143 #define DEFAULT_MARKER "<default>"
144 #define DEBUG_MARKER "<debug>"
145 #define INCLUDE_MARKER "<include>"
146 #define DEFAULT_TIMEFNAME_FMT "%Y%m%dT%H%M%S"
148 #define MAX_OLDLOGS 65536 /* Default maximum number of old logfiles */
150 struct compress_types {
151 const char *flag; /* Flag in configuration file */
152 const char *suffix; /* Compression suffix */
153 const char *path; /* Path to compression program */
154 char **args; /* Comrpession arguments */
157 static char f_arg[] = "-f";
158 static char q_arg[] = "-q";
159 static char rm_arg[] = "--rm";
160 static char *gz_args[] ={ NULL, f_arg, NULL, NULL };
161 #define bzip2_args gz_args
162 #define xz_args gz_args
163 static char *zstd_args[] = { NULL, q_arg, rm_arg, NULL, NULL };
165 static const struct compress_types compress_type[COMPRESS_TYPES] = {
166 { "", "", "", NULL}, /* none */
167 { "Z", COMPRESS_SUFFIX_GZ, _PATH_GZIP, gz_args}, /* gzip */
168 { "J", COMPRESS_SUFFIX_BZ2, _PATH_BZIP2, bzip2_args}, /* bzip2 */
169 { "X", COMPRESS_SUFFIX_XZ, _PATH_XZ, xz_args }, /* xz */
170 { "Y", COMPRESS_SUFFIX_ZST, _PATH_ZSTD, zstd_args } /* zst */
174 STAILQ_ENTRY(conf_entry) cf_nextp;
175 char *log; /* Name of the log */
176 char *pid_cmd_file; /* PID or command file */
177 char *r_reason; /* The reason this file is being rotated */
178 int firstcreate; /* Creating log for the first time (-C). */
179 int rotate; /* Non-zero if this file should be rotated */
180 int fsize; /* size found for the log file */
181 uid_t uid; /* Owner of log */
182 gid_t gid; /* Group of log */
183 int numlogs; /* Number of logs to keep */
184 int trsize; /* Size cutoff to trigger trimming the log */
185 int hours; /* Hours between log trimming */
186 struct ptime_data *trim_at; /* Specific time to do trimming */
187 unsigned int permissions; /* File permissions on the log */
188 int flags; /* CE_BINARY */
189 int compress; /* Compression */
190 int sig; /* Signal to send */
191 int def_cfg; /* Using the <default> rule for this file */
194 struct sigwork_entry {
195 SLIST_ENTRY(sigwork_entry) sw_nextp;
196 int sw_signum; /* the signal to send */
197 int sw_pidok; /* true if pid value is valid */
198 pid_t sw_pid; /* the process id from the PID file */
199 const char *sw_pidtype; /* "daemon" or "process group" */
200 int sw_runcmd; /* run command or send PID to signal */
201 char sw_fname[1]; /* file the PID was read from or shell cmd */
204 struct zipwork_entry {
205 SLIST_ENTRY(zipwork_entry) zw_nextp;
206 const struct conf_entry *zw_conf; /* for chown/perm/flag info */
207 const struct sigwork_entry *zw_swork; /* to know success of signal */
208 int zw_fsize; /* size of the file to compress */
209 char zw_fname[1]; /* the file to compress */
212 struct include_entry {
213 STAILQ_ENTRY(include_entry) inc_nextp;
214 const char *file; /* Name of file to process */
217 struct oldlog_entry {
218 char *fname; /* Filename of the log file */
219 time_t t; /* Parsed timestamp of the logfile */
226 STAILQ_HEAD(cflist, conf_entry);
227 static SLIST_HEAD(swlisthead, sigwork_entry) swhead =
228 SLIST_HEAD_INITIALIZER(swhead);
229 static SLIST_HEAD(zwlisthead, zipwork_entry) zwhead =
230 SLIST_HEAD_INITIALIZER(zwhead);
231 STAILQ_HEAD(ilist, include_entry);
233 int dbg_at_times; /* -D Show details of 'trim_at' code */
235 static int archtodir = 0; /* Archive old logfiles to other directory */
236 static int createlogs; /* Create (non-GLOB) logfiles which do not */
237 /* already exist. 1=='for entries with */
238 /* C flag', 2=='for all entries'. */
239 int verbose = 0; /* Print out what's going on */
240 static int needroot = 1; /* Root privs are necessary */
241 int noaction = 0; /* Don't do anything, just show it */
242 static int norotate = 0; /* Don't rotate */
243 static int nosignal; /* Do not send any signals */
244 static int enforcepid = 0; /* If PID file does not exist or empty, do nothing */
245 static int force = 0; /* Force the trim no matter what */
246 static int rotatereq = 0; /* -R = Always rotate the file(s) as given */
247 /* on the command (this also requires */
248 /* that a list of files *are* given on */
249 /* the run command). */
250 static char *requestor; /* The name given on a -R request */
251 static char *timefnamefmt = NULL;/* Use time based filenames instead of .0 */
252 static char *archdirname; /* Directory path to old logfiles archive */
253 static char *destdir = NULL; /* Directory to treat at root for logs */
254 static const char *conf; /* Configuration file to use */
256 struct ptime_data *dbg_timenow; /* A "timenow" value set via -D option */
257 static struct ptime_data *timenow; /* The time to use for checking at-fields */
259 #define DAYTIME_LEN 16
260 static char daytime[DAYTIME_LEN];/* The current time in human readable form,
261 * used for rotation-tracking messages. */
263 /* Another buffer to hold the current time in RFC5424 format. Fractional
264 * seconds are allowed by the RFC, but are not included in the
265 * rotation-tracking messages written by newsyslog and so are not accounted for
266 * in the length below.
268 #define DAYTIME_RFC5424_LEN sizeof("YYYY-MM-DDTHH:MM:SS+00:00")
269 static char daytime_rfc5424[DAYTIME_RFC5424_LEN];
271 static char hostname[MAXHOSTNAMELEN]; /* hostname */
273 static const char *path_syslogpid = _PATH_SYSLOGPID;
275 static struct cflist *get_worklist(char **files);
276 static void parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
277 struct conf_entry *defconf_p, struct ilist *inclist);
278 static void add_to_queue(const char *fname, struct ilist *inclist);
279 static char *sob(char *p);
280 static char *son(char *p);
281 static int isnumberstr(const char *);
282 static int isglobstr(const char *);
283 static char *missing_field(char *p, char *errline);
284 static void change_attrs(const char *, const struct conf_entry *);
285 static const char *get_logfile_suffix(const char *logfile);
286 static fk_entry do_entry(struct conf_entry *);
287 static fk_entry do_rotate(const struct conf_entry *);
288 static void do_sigwork(struct sigwork_entry *);
289 static void do_zipwork(struct zipwork_entry *);
290 static struct sigwork_entry *
291 save_sigwork(const struct conf_entry *);
292 static struct zipwork_entry *
293 save_zipwork(const struct conf_entry *, const struct
294 sigwork_entry *, int, const char *);
295 static void set_swpid(struct sigwork_entry *, const struct conf_entry *);
296 static int sizefile(const char *);
297 static void expand_globs(struct cflist *work_p, struct cflist *glob_p);
298 static void free_clist(struct cflist *list);
299 static void free_entry(struct conf_entry *ent);
300 static struct conf_entry *init_entry(const char *fname,
301 struct conf_entry *src_entry);
302 static void parse_args(int argc, char **argv);
303 static int parse_doption(const char *doption);
304 static void usage(void);
305 static int log_trim(const char *logname, const struct conf_entry *log_ent);
306 static int age_old_log(const char *file);
307 static void savelog(char *from, char *to);
308 static void createdir(const struct conf_entry *ent, char *dirpart);
309 static void createlog(const struct conf_entry *ent);
310 static int parse_signal(const char *str);
313 * All the following take a parameter of 'int', but expect values in the
314 * range of unsigned char. Define wrappers which take values of type 'char',
315 * whether signed or unsigned, and ensure they end up in the right range.
317 #define isdigitch(Anychar) isdigit((u_char)(Anychar))
318 #define isprintch(Anychar) isprint((u_char)(Anychar))
319 #define isspacech(Anychar) isspace((u_char)(Anychar))
320 #define tolowerch(Anychar) tolower((u_char)(Anychar))
323 main(int argc, char **argv)
325 struct cflist *worklist;
326 struct conf_entry *p;
327 struct sigwork_entry *stmp;
328 struct zipwork_entry *ztmp;
333 parse_args(argc, argv);
337 if (needroot && getuid() && geteuid())
338 errx(1, "must have root privs");
339 worklist = get_worklist(argv);
342 * Rotate all the files which need to be rotated. Note that
343 * some users have *hundreds* of entries in newsyslog.conf!
345 while (!STAILQ_EMPTY(worklist)) {
346 p = STAILQ_FIRST(worklist);
347 STAILQ_REMOVE_HEAD(worklist, cf_nextp);
348 if (do_entry(p) == FREE_ENT)
353 * Send signals to any processes which need a signal to tell
354 * them to close and re-open the log file(s) we have rotated.
355 * Note that zipwork_entries include pointers to these
356 * sigwork_entry's, so we can not free the entries here.
358 if (!SLIST_EMPTY(&swhead)) {
359 if (noaction || verbose)
360 printf("Signal all daemon process(es)...\n");
361 SLIST_FOREACH(stmp, &swhead, sw_nextp)
363 if (!(rotatereq && nosignal)) {
365 printf("\tsleep 10\n");
368 printf("Pause 10 seconds to allow "
369 "daemon(s) to close log file(s)\n");
375 * Compress all files that we're expected to compress, now
376 * that all processes should have closed the files which
379 if (!SLIST_EMPTY(&zwhead)) {
380 if (noaction || verbose)
381 printf("Compress all rotated log file(s)...\n");
382 while (!SLIST_EMPTY(&zwhead)) {
383 ztmp = SLIST_FIRST(&zwhead);
385 SLIST_REMOVE_HEAD(&zwhead, zw_nextp);
389 /* Now free all the sigwork entries. */
390 while (!SLIST_EMPTY(&swhead)) {
391 stmp = SLIST_FIRST(&swhead);
392 SLIST_REMOVE_HEAD(&swhead, sw_nextp);
396 while (wait(NULL) > 0 || errno == EINTR)
401 static struct conf_entry *
402 init_entry(const char *fname, struct conf_entry *src_entry)
404 struct conf_entry *tempwork;
407 printf("\t--> [creating entry for %s]\n", fname);
409 tempwork = malloc(sizeof(struct conf_entry));
410 if (tempwork == NULL)
411 err(1, "malloc of conf_entry for %s", fname);
413 if (destdir == NULL || fname[0] != '/')
414 tempwork->log = strdup(fname);
416 asprintf(&tempwork->log, "%s%s", destdir, fname);
417 if (tempwork->log == NULL)
418 err(1, "strdup for %s", fname);
420 if (src_entry != NULL) {
421 tempwork->pid_cmd_file = NULL;
422 if (src_entry->pid_cmd_file)
423 tempwork->pid_cmd_file = strdup(src_entry->pid_cmd_file);
424 tempwork->r_reason = NULL;
425 tempwork->firstcreate = 0;
426 tempwork->rotate = 0;
427 tempwork->fsize = -1;
428 tempwork->uid = src_entry->uid;
429 tempwork->gid = src_entry->gid;
430 tempwork->numlogs = src_entry->numlogs;
431 tempwork->trsize = src_entry->trsize;
432 tempwork->hours = src_entry->hours;
433 tempwork->trim_at = NULL;
434 if (src_entry->trim_at != NULL)
435 tempwork->trim_at = ptime_init(src_entry->trim_at);
436 tempwork->permissions = src_entry->permissions;
437 tempwork->flags = src_entry->flags;
438 tempwork->compress = src_entry->compress;
439 tempwork->sig = src_entry->sig;
440 tempwork->def_cfg = src_entry->def_cfg;
442 /* Initialize as a "do-nothing" entry */
443 tempwork->pid_cmd_file = NULL;
444 tempwork->r_reason = NULL;
445 tempwork->firstcreate = 0;
446 tempwork->rotate = 0;
447 tempwork->fsize = -1;
448 tempwork->uid = (uid_t)-1;
449 tempwork->gid = (gid_t)-1;
450 tempwork->numlogs = 1;
451 tempwork->trsize = -1;
452 tempwork->hours = -1;
453 tempwork->trim_at = NULL;
454 tempwork->permissions = 0;
456 tempwork->compress = COMPRESS_NONE;
457 tempwork->sig = SIGHUP;
458 tempwork->def_cfg = 0;
465 free_entry(struct conf_entry *ent)
471 if (ent->log != NULL) {
473 printf("\t--> [freeing entry for %s]\n", ent->log);
478 if (ent->pid_cmd_file != NULL) {
479 free(ent->pid_cmd_file);
480 ent->pid_cmd_file = NULL;
483 if (ent->r_reason != NULL) {
485 ent->r_reason = NULL;
488 if (ent->trim_at != NULL) {
489 ptime_free(ent->trim_at);
497 free_clist(struct cflist *list)
499 struct conf_entry *ent;
501 while (!STAILQ_EMPTY(list)) {
502 ent = STAILQ_FIRST(list);
503 STAILQ_REMOVE_HEAD(list, cf_nextp);
512 do_entry(struct conf_entry * ent)
514 #define REASON_MAX 80
516 fk_entry free_or_keep;
518 char temp_reason[REASON_MAX];
521 free_or_keep = FREE_ENT;
523 printf("%s <%d%s>: ", ent->log, ent->numlogs,
524 compress_type[ent->compress].flag);
525 ent->fsize = sizefile(ent->log);
526 oversized = ((ent->trsize > 0) && (ent->fsize >= ent->trsize));
527 modtime = age_old_log(ent->log);
529 ent->firstcreate = 0;
530 if (ent->fsize < 0) {
532 * If either the C flag or the -C option was specified,
533 * and if we won't be creating the file, then have the
534 * verbose message include a hint as to why the file
535 * will not be created.
537 temp_reason[0] = '\0';
539 ent->firstcreate = 1;
540 else if ((ent->flags & CE_CREATE) && createlogs)
541 ent->firstcreate = 1;
542 else if (ent->flags & CE_CREATE)
543 strlcpy(temp_reason, " (no -C option)", REASON_MAX);
545 strlcpy(temp_reason, " (no C flag)", REASON_MAX);
547 if (ent->firstcreate) {
549 printf("does not exist -> will create.\n");
551 } else if (verbose) {
552 printf("does not exist, skipped%s.\n", temp_reason);
555 if (ent->flags & CE_TRIMAT && !force && !rotatereq &&
557 diffsecs = ptimeget_diff(timenow, ent->trim_at);
558 if (diffsecs < 0.0) {
559 /* trim_at is some time in the future. */
561 ptime_adjust4dst(ent->trim_at,
563 printf("--> will trim at %s",
564 ptimeget_ctime(ent->trim_at));
566 return (free_or_keep);
567 } else if (diffsecs >= 3600.0) {
569 * trim_at is more than an hour in the past,
570 * so find the next valid trim_at time, and
571 * tell the user what that will be.
573 if (verbose && dbg_at_times)
574 printf("\n\t--> prev trim at %s\t",
575 ptimeget_ctime(ent->trim_at));
577 ptimeset_nxtime(ent->trim_at);
578 printf("--> will trim at %s",
579 ptimeget_ctime(ent->trim_at));
581 return (free_or_keep);
582 } else if (verbose && noaction && dbg_at_times) {
584 * If we are just debugging at-times, then
585 * a detailed message is helpful. Also
586 * skip "doing" any commands, since they
587 * would all be turned off by no-action.
589 printf("\n\t--> timematch at %s",
590 ptimeget_ctime(ent->trim_at));
591 return (free_or_keep);
592 } else if (verbose && ent->hours <= 0) {
593 printf("--> time is up\n");
596 if (verbose && (ent->trsize > 0))
597 printf("size (Kb): %d [%d] ", ent->fsize, ent->trsize);
598 if (verbose && (ent->hours > 0))
599 printf(" age (hr): %d [%d] ", modtime, ent->hours);
602 * Figure out if this logfile needs to be rotated.
604 temp_reason[0] = '\0';
607 snprintf(temp_reason, REASON_MAX, " due to -R from %s",
611 snprintf(temp_reason, REASON_MAX, " due to -F request");
612 } else if (oversized) {
614 snprintf(temp_reason, REASON_MAX, " due to size>%dK",
616 } else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) {
618 } else if ((ent->hours > 0) && ((modtime >= ent->hours) ||
624 * If the file needs to be rotated, then rotate it.
626 if (ent->rotate && !norotate) {
627 if (temp_reason[0] != '\0')
628 ent->r_reason = strdup(temp_reason);
630 printf("--> trimming log....\n");
631 if (noaction && !verbose)
632 printf("%s <%d%s>: trimming\n", ent->log,
634 compress_type[ent->compress].flag);
635 free_or_keep = do_rotate(ent);
638 printf("--> skipping\n");
641 return (free_or_keep);
646 parse_args(int argc, char **argv)
651 timenow = ptime_init(NULL);
652 ptimeset_time(timenow, time(NULL));
653 strlcpy(daytime, ptimeget_ctime(timenow) + 4, DAYTIME_LEN);
654 ptimeget_ctime_rfc5424(timenow, daytime_rfc5424, DAYTIME_RFC5424_LEN);
656 /* Let's get our hostname */
657 (void)gethostname(hostname, sizeof(hostname));
659 /* Truncate domain */
660 if ((p = strchr(hostname, '.')) != NULL)
663 /* Parse command line options. */
664 while ((ch = getopt(argc, argv, "a:d:f:nrst:vCD:FNPR:S:")) != -1)
668 archdirname = optarg;
686 if (optarg[0] == '\0' ||
687 strcmp(optarg, "DEFAULT") == 0)
688 timefnamefmt = strdup(DEFAULT_TIMEFNAME_FMT);
690 timefnamefmt = strdup(optarg);
696 /* Useful for things like rc.diskless... */
701 * Set some debugging option. The specific option
702 * depends on the value of optarg. These options
703 * may come and go without notice or documentation.
705 if (parse_doption(optarg))
720 requestor = strdup(optarg);
723 path_syslogpid = optarg;
725 case 'm': /* Used by OpenBSD for "monitor mode" */
731 if (force && norotate) {
732 warnx("Only one of -F and -N may be specified.");
738 if (optind == argc) {
739 warnx("At least one filename must be given when -R is specified.");
743 /* Make sure "requestor" value is safe for a syslog message. */
744 for (p = requestor; *p != '\0'; p++) {
745 if (!isprintch(*p) && (*p != '\t'))
752 * Note that the 'daytime' variable is not changed.
753 * That is only used in messages that track when a
754 * logfile is rotated, and if a file *is* rotated,
755 * then it will still rotated at the "real now" time.
758 timenow = dbg_timenow;
759 fprintf(stderr, "Debug: Running as if TimeNow is %s",
760 ptimeget_ctime(dbg_timenow));
766 * These debugging options are mainly meant for developer use, such
767 * as writing regression-tests. They would not be needed by users
768 * during normal operation of newsyslog...
771 parse_doption(const char *doption)
773 const char TN[] = "TN=";
776 if (strncmp(doption, TN, sizeof(TN) - 1) == 0) {
778 * The "TimeNow" debugging option. This might be off
779 * by an hour when crossing a timezone change.
781 dbg_timenow = ptime_init(NULL);
782 res = ptime_relparse(dbg_timenow, PTM_PARSE_ISO8601,
783 time(NULL), doption + sizeof(TN) - 1);
785 warnx("Non-existent time specified on -D %s", doption);
786 return (0); /* failure */
787 } else if (res < 0) {
788 warnx("Malformed time given on -D %s", doption);
789 return (0); /* failure */
791 return (1); /* successfully parsed */
795 if (strcmp(doption, "ats") == 0) {
797 return (1); /* successfully parsed */
800 /* XXX - This check could probably be dropped. */
801 if ((strcmp(doption, "neworder") == 0) || (strcmp(doption, "oldorder")
803 warnx("NOTE: newsyslog always uses 'neworder'.");
804 return (1); /* successfully parsed */
807 warnx("Unknown -D (debug) option: '%s'", doption);
808 return (0); /* failure */
816 "usage: newsyslog [-CFNPnrsv] [-a directory] [-d directory] [-f config_file]\n"
817 " [-S pidfile] [-t timefmt] [[-R tagname] file ...]\n");
822 * Parse a configuration file and return a linked list of all the logs
823 * which should be processed.
825 static struct cflist *
826 get_worklist(char **files)
830 struct cflist *cmdlist, *filelist, *globlist;
831 struct conf_entry *defconf, *dupent, *ent;
832 struct ilist inclist;
833 struct include_entry *inc;
837 STAILQ_INIT(&inclist);
839 filelist = malloc(sizeof(struct cflist));
840 if (filelist == NULL)
841 err(1, "malloc of filelist");
842 STAILQ_INIT(filelist);
843 globlist = malloc(sizeof(struct cflist));
844 if (globlist == NULL)
845 err(1, "malloc of globlist");
846 STAILQ_INIT(globlist);
848 inc = malloc(sizeof(struct include_entry));
850 err(1, "malloc of inc");
852 if (inc->file == NULL)
853 inc->file = _PATH_CONF;
854 STAILQ_INSERT_TAIL(&inclist, inc, inc_nextp);
856 STAILQ_FOREACH(inc, &inclist, inc_nextp) {
857 if (strcmp(inc->file, "-") != 0)
858 f = fopen(inc->file, "r");
861 inc->file = "<stdin>";
864 err(1, "%s", inc->file);
867 printf("Processing %s\n", inc->file);
868 parse_file(f, filelist, globlist, defconf, &inclist);
873 * All config-file information has been read in and turned into
874 * a filelist and a globlist. If there were no specific files
875 * given on the run command, then the only thing left to do is to
876 * call a routine which finds all files matched by the globlist
877 * and adds them to the filelist. Then return the worklist.
879 if (*files == NULL) {
880 expand_globs(filelist, globlist);
881 free_clist(globlist);
889 * If newsyslog was given a specific list of files to process,
890 * it may be that some of those files were not listed in any
891 * config file. Those unlisted files should get the default
892 * rotation action. First, create the default-rotation action
893 * if none was found in a system config file.
895 if (defconf == NULL) {
896 defconf = init_entry(DEFAULT_MARKER, NULL);
897 defconf->numlogs = 3;
898 defconf->trsize = 50;
899 defconf->permissions = S_IRUSR|S_IWUSR;
903 * If newsyslog was run with a list of specific filenames,
904 * then create a new worklist which has only those files in
905 * it, picking up the rotation-rules for those files from
906 * the original filelist.
908 * XXX - Note that this will copy multiple rules for a single
909 * logfile, if multiple entries are an exact match for
910 * that file. That matches the historic behavior, but do
911 * we want to continue to allow it? If so, it should
912 * probably be handled more intelligently.
914 cmdlist = malloc(sizeof(struct cflist));
916 err(1, "malloc of cmdlist");
917 STAILQ_INIT(cmdlist);
919 for (given = files; *given; ++given) {
921 * First try to find exact-matches for this given file.
924 STAILQ_FOREACH(ent, filelist, cf_nextp) {
925 if (strcmp(ent->log, *given) == 0) {
927 dupent = init_entry(*given, ent);
928 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
933 printf("\t+ Matched entry %s\n", *given);
938 * There was no exact-match for this given file, so look
939 * for a "glob" entry which does match.
942 if (verbose > 2 && globlist != NULL)
943 printf("\t+ Checking globs for %s\n", *given);
944 STAILQ_FOREACH(ent, globlist, cf_nextp) {
945 fnres = fnmatch(ent->log, *given, FNM_PATHNAME);
947 printf("\t+ = %d for pattern %s\n", fnres,
951 dupent = init_entry(*given, ent);
952 /* This new entry is not a glob! */
953 dupent->flags &= ~CE_GLOB;
954 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
955 /* Only allow a match to one glob-entry */
961 printf("\t+ Matched %s via %s\n", *given,
967 * This given file was not found in any config file, so
968 * add a worklist item based on the default entry.
971 printf("\t+ No entry matched %s (will use %s)\n",
972 *given, DEFAULT_MARKER);
973 dupent = init_entry(*given, defconf);
974 /* Mark that it was *not* found in a config file */
976 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
980 * Free all the entries in the original work list, the list of
981 * glob entries, and the default entry.
983 free_clist(filelist);
984 free_clist(globlist);
987 /* And finally, return a worklist which matches the given files. */
992 * Expand the list of entries with filename patterns, and add all files
993 * which match those glob-entries onto the worklist.
996 expand_globs(struct cflist *work_p, struct cflist *glob_p)
1001 struct conf_entry *dupent, *ent, *globent;
1006 * The worklist contains all fully-specified (non-GLOB) names.
1008 * Now expand the list of filename-pattern (GLOB) entries into
1009 * a second list, which (by definition) will only match files
1010 * that already exist. Do not add a glob-related entry for any
1011 * file which already exists in the fully-specified list.
1013 STAILQ_FOREACH(globent, glob_p, cf_nextp) {
1014 gres = glob(globent->log, GLOB_NOCHECK, NULL, &pglob);
1016 warn("cannot expand pattern (%d): %s", gres,
1022 printf("\t+ Expanding pattern %s\n", globent->log);
1023 for (i = 0; i < pglob.gl_matchc; i++) {
1024 mfname = pglob.gl_pathv[i];
1026 /* See if this file already has a specific entry. */
1028 STAILQ_FOREACH(ent, work_p, cf_nextp) {
1029 if (strcmp(mfname, ent->log) == 0) {
1037 /* Make sure the named matched is a file. */
1038 gres = lstat(mfname, &st_fm);
1040 /* Error on a file that glob() matched?!? */
1041 warn("Skipping %s - lstat() error", mfname);
1044 if (!S_ISREG(st_fm.st_mode)) {
1045 /* We only rotate files! */
1047 printf("\t+ . skipping %s (!file)\n",
1053 printf("\t+ . add file %s\n", mfname);
1054 dupent = init_entry(mfname, globent);
1055 /* This new entry is not a glob! */
1056 dupent->flags &= ~CE_GLOB;
1058 /* Add to the worklist. */
1059 STAILQ_INSERT_TAIL(work_p, dupent, cf_nextp);
1063 printf("\t+ Done with pattern %s\n", globent->log);
1068 * Parse a configuration file and update a linked list of all the logs to
1072 parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
1073 struct conf_entry *defconf_p, struct ilist *inclist)
1075 char line[BUFSIZ], *parse, *q;
1076 char *cp, *errline, *group;
1077 struct conf_entry *working;
1081 int eol, ptm_opts, res, special;
1085 while (fgets(line, BUFSIZ, cf)) {
1086 if ((line[0] == '\n') || (line[0] == '#') ||
1087 (strlen(line) == 0))
1089 if (errline != NULL)
1091 errline = strdup(line);
1092 for (cp = line + 1; *cp != '\0'; cp++) {
1095 if (*(cp - 1) == '\\') {
1104 q = parse = missing_field(sob(line), errline);
1107 errx(1, "malformed line (missing fields):\n%s",
1112 * Allow people to set debug options via the config file.
1113 * (NOTE: debug options are undocumented, and may disappear
1114 * at any time, etc).
1116 if (strcasecmp(DEBUG_MARKER, q) == 0) {
1117 q = parse = missing_field(sob(parse + 1), errline);
1120 warnx("debug line specifies no option:\n%s",
1127 } else if (strcasecmp(INCLUDE_MARKER, q) == 0) {
1129 printf("Found: %s", errline);
1130 q = parse = missing_field(sob(parse + 1), errline);
1133 warnx("include line missing argument:\n%s",
1141 res = glob(q, GLOB_NOCHECK, NULL, &pglob);
1143 warn("cannot expand pattern (%d): %s",
1149 printf("\t+ Expanding pattern %s\n", q);
1151 for (i = 0; i < pglob.gl_matchc; i++)
1152 add_to_queue(pglob.gl_pathv[i],
1156 add_to_queue(q, inclist);
1161 working = init_entry(q, NULL);
1162 if (strcasecmp(DEFAULT_MARKER, q) == 0) {
1164 if (defconf_p != NULL) {
1165 warnx("Ignoring duplicate entry for %s!", q);
1166 free_entry(working);
1169 defconf_p = working;
1172 q = parse = missing_field(sob(parse + 1), errline);
1175 errx(1, "malformed line (missing fields):\n%s",
1178 if ((group = strchr(q, ':')) != NULL ||
1179 (group = strrchr(q, '.')) != NULL) {
1182 if (!(isnumberstr(q))) {
1183 if ((pwd = getpwnam(q)) == NULL)
1185 "error in config file; unknown user:\n%s",
1187 working->uid = pwd->pw_uid;
1189 working->uid = atoi(q);
1191 working->uid = (uid_t)-1;
1195 if (!(isnumberstr(q))) {
1196 if ((grp = getgrnam(q)) == NULL)
1198 "error in config file; unknown group:\n%s",
1200 working->gid = grp->gr_gid;
1202 working->gid = atoi(q);
1204 working->gid = (gid_t)-1;
1206 q = parse = missing_field(sob(parse + 1), errline);
1209 errx(1, "malformed line (missing fields):\n%s",
1213 working->uid = (uid_t)-1;
1214 working->gid = (gid_t)-1;
1217 if (!sscanf(q, "%o", &working->permissions))
1218 errx(1, "error in config file; bad permissions:\n%s",
1221 q = parse = missing_field(sob(parse + 1), errline);
1224 errx(1, "malformed line (missing fields):\n%s",
1227 if (!sscanf(q, "%d", &working->numlogs) || working->numlogs < 0)
1228 errx(1, "error in config file; bad value for count of logs to save:\n%s",
1231 q = parse = missing_field(sob(parse + 1), errline);
1234 errx(1, "malformed line (missing fields):\n%s",
1238 working->trsize = atoi(q);
1239 else if (strcmp(q, "*") == 0)
1240 working->trsize = -1;
1242 warnx("Invalid value of '%s' for 'size' in line:\n%s",
1244 working->trsize = -1;
1248 working->compress = COMPRESS_NONE;
1249 q = parse = missing_field(sob(parse + 1), errline);
1257 ul = strtoul(q, &ep, 10);
1260 else if (*ep == '*')
1261 working->hours = -1;
1262 else if (ul > INT_MAX)
1263 errx(1, "interval is too large:\n%s", errline);
1265 working->hours = ul;
1267 if (*ep == '\0' || strcmp(ep, "*") == 0)
1269 if (*ep != '@' && *ep != '$')
1270 errx(1, "malformed interval/at:\n%s", errline);
1272 working->flags |= CE_TRIMAT;
1273 working->trim_at = ptime_init(NULL);
1274 ptm_opts = PTM_PARSE_ISO8601;
1276 ptm_opts = PTM_PARSE_DWM;
1277 ptm_opts |= PTM_PARSE_MATCHDOM;
1278 res = ptime_relparse(working->trim_at, ptm_opts,
1279 ptimeget_secs(timenow), ep + 1);
1281 errx(1, "nonexistent time for 'at' value:\n%s",
1284 errx(1, "malformed 'at' value:\n%s", errline);
1291 q = parse = sob(parse + 1); /* Optional field */
1298 for (; q && *q && !isspacech(*q); q++) {
1299 switch (tolowerch(*q)) {
1301 working->flags |= CE_BINARY;
1304 working->flags |= CE_CREATE;
1307 working->flags |= CE_NODUMP;
1310 working->flags |= CE_GLOB;
1313 working->compress = COMPRESS_BZIP2;
1316 working->flags |= CE_NOSIGNAL;
1319 working->flags |= CE_PID2CMD;
1322 working->flags |= CE_RFC5424;
1325 working->flags |= CE_SIGNALGROUP;
1328 /* Deprecated flag - keep for compatibility purposes */
1331 working->compress = COMPRESS_XZ;
1334 working->compress = COMPRESS_ZSTD;
1337 working->compress = COMPRESS_GZIP;
1341 case 'f': /* Used by OpenBSD for "CE_FOLLOW" */
1342 case 'm': /* Used by OpenBSD for "CE_MONITOR" */
1343 case 'p': /* Used by NetBSD for "CE_PLAIN0" */
1345 errx(1, "illegal flag in config file -- %c",
1353 q = parse = sob(parse + 1); /* Optional field */
1360 working->pid_cmd_file = NULL;
1363 working->pid_cmd_file = strdup(q);
1364 else if (isalnum(*q))
1368 "illegal pid file or signal in config file:\n%s",
1375 q = parse = sob(parse + 1); /* Optional field */
1376 *(parse = son(parse)) = '\0';
1379 working->sig = SIGHUP;
1382 working->sig = parse_signal(q);
1383 if (working->sig < 1 || working->sig >= sys_nsig) {
1385 "illegal signal in config file:\n%s",
1391 * Finish figuring out what pid-file to use (if any) in
1392 * later processing if this logfile needs to be rotated.
1394 if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) {
1396 * This config-entry specified 'n' for nosignal,
1397 * see if it also specified an explicit pid_cmd_file.
1398 * This would be a pretty pointless combination.
1400 if (working->pid_cmd_file != NULL) {
1401 warnx("Ignoring '%s' because flag 'n' was specified in line:\n%s",
1402 working->pid_cmd_file, errline);
1403 free(working->pid_cmd_file);
1404 working->pid_cmd_file = NULL;
1406 } else if (working->pid_cmd_file == NULL) {
1408 * This entry did not specify the 'n' flag, which
1409 * means it should signal syslogd unless it had
1410 * specified some other pid-file (and obviously the
1411 * syslog pid-file will not be for a process-group).
1412 * Also, we should only try to notify syslog if we
1415 if (working->flags & CE_SIGNALGROUP) {
1416 warnx("Ignoring flag 'U' in line:\n%s",
1418 working->flags &= ~CE_SIGNALGROUP;
1421 working->pid_cmd_file = strdup(path_syslogpid);
1425 * Add this entry to the appropriate list of entries, unless
1426 * it was some kind of special entry (eg: <default>).
1429 ; /* Do not add to any list */
1430 } else if (working->flags & CE_GLOB) {
1431 STAILQ_INSERT_TAIL(glob_p, working, cf_nextp);
1433 STAILQ_INSERT_TAIL(work_p, working, cf_nextp);
1436 if (errline != NULL)
1441 missing_field(char *p, char *errline)
1445 errx(1, "missing field in config file:\n%s", errline);
1450 * In our sort we return it in the reverse of what qsort normally
1451 * would do, as we want the newest files first. If we have two
1452 * entries with the same time we don't really care about order.
1454 * Support function for qsort() in delete_oldest_timelog().
1457 oldlog_entry_compare(const void *a, const void *b)
1459 const struct oldlog_entry *ola = a, *olb = b;
1461 if (ola->t > olb->t)
1463 else if (ola->t < olb->t)
1470 * Check whether the file corresponding to dp is an archive of the logfile
1471 * logfname, based on the timefnamefmt format string. Return true and fill out
1472 * tm if this is the case; otherwise return false.
1475 validate_old_timelog(int fd, const struct dirent *dp, const char *logfname,
1479 size_t logfname_len;
1483 logfname_len = strlen(logfname);
1485 if (dp->d_type != DT_REG) {
1487 * Some filesystems (e.g. NFS) don't fill out the d_type field
1488 * and leave it set to DT_UNKNOWN; in this case we must obtain
1489 * the file type ourselves.
1491 if (dp->d_type != DT_UNKNOWN ||
1492 fstatat(fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) != 0 ||
1493 !S_ISREG(sb.st_mode))
1496 /* Ignore everything but files with our logfile prefix. */
1497 if (strncmp(dp->d_name, logfname, logfname_len) != 0)
1499 /* Ignore the actual non-rotated logfile. */
1500 if (dp->d_namlen == logfname_len)
1504 * Make sure we created have found a logfile, so the
1505 * postfix is valid, IE format is: '.<time>(.[bgx]z)?'.
1507 if (dp->d_name[logfname_len] != '.') {
1509 printf("Ignoring %s which has unexpected "
1510 "extension '%s'\n", dp->d_name,
1511 &dp->d_name[logfname_len]);
1514 memset(tm, 0, sizeof(*tm));
1515 if ((s = strptime(&dp->d_name[logfname_len + 1],
1516 timefnamefmt, tm)) == NULL) {
1518 * We could special case "old" sequentially named logfiles here,
1519 * but we do not as that would require special handling to
1520 * decide which one was the oldest compared to "new" time based
1524 printf("Ignoring %s which does not "
1525 "match time format\n", dp->d_name);
1529 for (c = 0; c < COMPRESS_TYPES; c++)
1530 if (strcmp(s, compress_type[c].suffix) == 0)
1535 printf("Ignoring %s which has unexpected extension '%s'\n",
1542 * Delete the oldest logfiles, when using time based filenames.
1545 delete_oldest_timelog(const struct conf_entry *ent, const char *archive_dir)
1547 char *basebuf, *dirbuf, errbuf[80];
1548 const char *base, *dir;
1549 int dir_fd, i, logcnt, max_logcnt;
1550 struct oldlog_entry *oldlogs;
1555 oldlogs = malloc(MAX_OLDLOGS * sizeof(struct oldlog_entry));
1556 max_logcnt = MAX_OLDLOGS;
1559 if (archive_dir != NULL && archive_dir[0] != '\0') {
1563 if ((dirbuf = strdup(ent->log)) == NULL)
1565 dir = dirname(dirbuf);
1568 if ((basebuf = strdup(ent->log)) == NULL)
1570 base = basename(basebuf);
1571 if (strcmp(base, "/") == 0)
1572 errx(1, "Invalid log filename - became '/'");
1575 printf("Searching for old logs in %s\n", dir);
1577 /* First we create a 'list' of all archived logfiles */
1578 if ((dirp = opendir(dir)) == NULL)
1579 err(1, "Cannot open log directory '%s'", dir);
1580 dir_fd = dirfd(dirp);
1581 while ((dp = readdir(dirp)) != NULL) {
1582 if (validate_old_timelog(dir_fd, dp, base, &tm) == 0)
1586 * We should now have old an old rotated logfile, so
1587 * add it to the 'list'.
1589 if ((oldlogs[logcnt].t = timegm(&tm)) == -1)
1590 err(1, "Could not convert time string to time value");
1591 if ((oldlogs[logcnt].fname = strdup(dp->d_name)) == NULL)
1596 * It is very unlikely we ever run out of space in the
1597 * logfile array from the default size, but lets
1598 * handle it anyway...
1600 if (logcnt >= max_logcnt) {
1602 /* Detect integer overflow */
1603 if (max_logcnt < logcnt)
1604 errx(1, "Too many old logfiles found");
1605 oldlogs = realloc(oldlogs,
1606 max_logcnt * sizeof(struct oldlog_entry));
1607 if (oldlogs == NULL)
1608 err(1, "realloc()");
1612 /* Second, if needed we delete oldest archived logfiles */
1613 if (logcnt > 0 && logcnt >= ent->numlogs && ent->numlogs > 1) {
1614 oldlogs = realloc(oldlogs, logcnt *
1615 sizeof(struct oldlog_entry));
1616 if (oldlogs == NULL)
1617 err(1, "realloc()");
1620 * We now sort the logs in the order of newest to
1621 * oldest. That way we can simply skip over the
1622 * number of records we want to keep.
1624 qsort(oldlogs, logcnt, sizeof(struct oldlog_entry),
1625 oldlog_entry_compare);
1626 for (i = ent->numlogs - 1; i < logcnt; i++) {
1628 printf("\trm -f %s/%s\n", dir,
1630 else if (unlinkat(dir_fd, oldlogs[i].fname, 0) != 0) {
1631 snprintf(errbuf, sizeof(errbuf),
1632 "Could not delete old logfile '%s'",
1637 } else if (verbose > 1)
1638 printf("No old logs to delete for logfile %s\n", ent->log);
1640 /* Third, cleanup */
1642 for (i = 0; i < logcnt; i++) {
1643 assert(oldlogs[i].fname != NULL);
1644 free(oldlogs[i].fname);
1652 * Generate a log filename, when using classic filenames.
1655 gen_classiclog_fname(char *fname, size_t fname_sz, const char *archive_dir,
1656 const char *namepart, int numlogs_c)
1659 if (archive_dir[0] != '\0')
1660 (void) snprintf(fname, fname_sz, "%s/%s.%d", archive_dir,
1661 namepart, numlogs_c);
1663 (void) snprintf(fname, fname_sz, "%s.%d", namepart, numlogs_c);
1667 * Delete a rotated logfile, when using classic filenames.
1670 delete_classiclog(const char *archive_dir, const char *namepart, int numlog_c)
1672 char file1[MAXPATHLEN], zfile1[MAXPATHLEN];
1675 gen_classiclog_fname(file1, sizeof(file1), archive_dir, namepart,
1678 for (c = 0; c < COMPRESS_TYPES; c++) {
1679 (void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1680 compress_type[c].suffix);
1682 printf("\trm -f %s\n", zfile1);
1684 (void) unlink(zfile1);
1689 * Only add to the queue if the file hasn't already been added. This is
1690 * done to prevent circular include loops.
1693 add_to_queue(const char *fname, struct ilist *inclist)
1695 struct include_entry *inc;
1697 STAILQ_FOREACH(inc, inclist, inc_nextp) {
1698 if (strcmp(fname, inc->file) == 0) {
1699 warnx("duplicate include detected: %s", fname);
1704 inc = malloc(sizeof(struct include_entry));
1706 err(1, "malloc of inc");
1707 inc->file = strdup(fname);
1710 printf("\t+ Adding %s to the processing queue.\n", fname);
1712 STAILQ_INSERT_TAIL(inclist, inc, inc_nextp);
1716 * Search for logfile and return its compression suffix (if supported)
1717 * The suffix detection is first-match in the order of compress_types
1719 * Note: if logfile without suffix exists (uncompressed, COMPRESS_NONE)
1720 * a zero-length string is returned
1723 get_logfile_suffix(const char *logfile)
1726 char zfile[MAXPATHLEN];
1729 for (c = 0; c < COMPRESS_TYPES; c++) {
1730 (void) strlcpy(zfile, logfile, MAXPATHLEN);
1731 (void) strlcat(zfile, compress_type[c].suffix, MAXPATHLEN);
1732 if (lstat(zfile, &st) == 0)
1733 return (compress_type[c].suffix);
1739 do_rotate(const struct conf_entry *ent)
1741 char dirpart[MAXPATHLEN], namepart[MAXPATHLEN];
1742 char file1[MAXPATHLEN], file2[MAXPATHLEN];
1743 char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN];
1744 const char *logfile_suffix;
1745 char datetimestr[30];
1746 int flags, numlogs_c;
1747 fk_entry free_or_keep;
1748 struct sigwork_entry *swork;
1754 free_or_keep = FREE_ENT;
1759 /* build complete name of archive directory into dirpart */
1760 if (*archdirname == '/') { /* absolute */
1761 strlcpy(dirpart, archdirname, sizeof(dirpart));
1762 } else { /* relative */
1763 /* get directory part of logfile */
1764 strlcpy(dirpart, ent->log, sizeof(dirpart));
1765 if ((p = strrchr(dirpart, '/')) == NULL)
1769 strlcat(dirpart, archdirname, sizeof(dirpart));
1772 /* check if archive directory exists, if not, create it */
1773 if (lstat(dirpart, &st))
1774 createdir(ent, dirpart);
1776 /* get filename part of logfile */
1777 if ((p = strrchr(ent->log, '/')) == NULL)
1778 strlcpy(namepart, ent->log, sizeof(namepart));
1780 strlcpy(namepart, p + 1, sizeof(namepart));
1783 * Tell utility functions we are not using an archive
1787 strlcpy(namepart, ent->log, sizeof(namepart));
1790 /* Delete old logs */
1791 if (timefnamefmt != NULL)
1792 delete_oldest_timelog(ent, dirpart);
1795 * Handle cleaning up after legacy newsyslog where we
1796 * kept ent->numlogs + 1 files. This code can go away
1797 * at some point in the future.
1799 delete_classiclog(dirpart, namepart, ent->numlogs);
1801 if (ent->numlogs > 0)
1802 delete_classiclog(dirpart, namepart, ent->numlogs - 1);
1806 if (timefnamefmt != NULL) {
1807 /* If time functions fails we can't really do any sensible */
1808 if (time(&now) == (time_t)-1 ||
1809 localtime_r(&now, &tm) == NULL)
1810 bzero(&tm, sizeof(tm));
1812 strftime(datetimestr, sizeof(datetimestr), timefnamefmt, &tm);
1814 (void) snprintf(file1, sizeof(file1), "%s/%s.%s",
1815 dirpart, namepart, datetimestr);
1817 (void) snprintf(file1, sizeof(file1), "%s.%s",
1818 ent->log, datetimestr);
1820 /* Don't run the code to move down logs */
1823 gen_classiclog_fname(file1, sizeof(file1), dirpart, namepart,
1825 numlogs_c = ent->numlogs - 2; /* copy for countdown */
1828 /* Move down log files */
1829 for (; numlogs_c >= 0; numlogs_c--) {
1830 (void) strlcpy(file2, file1, sizeof(file2));
1832 gen_classiclog_fname(file1, sizeof(file1), dirpart, namepart,
1835 logfile_suffix = get_logfile_suffix(file1);
1836 if (logfile_suffix == NULL)
1838 (void) strlcpy(zfile1, file1, MAXPATHLEN);
1839 (void) strlcpy(zfile2, file2, MAXPATHLEN);
1840 (void) strlcat(zfile1, logfile_suffix, MAXPATHLEN);
1841 (void) strlcat(zfile2, logfile_suffix, MAXPATHLEN);
1844 printf("\tmv %s %s\n", zfile1, zfile2);
1846 /* XXX - Ought to be checking for failure! */
1847 (void)rename(zfile1, zfile2);
1849 change_attrs(zfile2, ent);
1852 if (ent->numlogs > 0) {
1855 * Note that savelog() may succeed with using link()
1856 * for the archtodir case, but there is no good way
1857 * of knowing if it will when doing "noaction", so
1858 * here we claim that it will have to do a copy...
1861 printf("\tcp %s %s\n", ent->log, file1);
1863 printf("\tln %s %s\n", ent->log, file1);
1864 printf("\ttouch %s\t\t"
1865 "# Update mtime for 'when'-interval processing\n",
1868 if (!(flags & CE_BINARY)) {
1869 /* Report the trimming to the old log */
1870 log_trim(ent->log, ent);
1872 savelog(ent->log, file1);
1874 * Interval-based rotations are done using the mtime of
1875 * the most recently archived log, so make sure it gets
1876 * updated during a rotation.
1878 utimes(file1, NULL);
1880 change_attrs(file1, ent);
1883 /* Create the new log file and move it into place */
1885 printf("Start new log...\n");
1889 * Save all signalling and file-compression to be done after log
1890 * files from all entries have been rotated. This way any one
1891 * process will not be sent the same signal multiple times when
1892 * multiple log files had to be rotated.
1895 if (ent->pid_cmd_file != NULL)
1896 swork = save_sigwork(ent);
1897 if (ent->numlogs > 0 && ent->compress > COMPRESS_NONE) {
1899 * The zipwork_entry will include a pointer to this
1900 * conf_entry, so the conf_entry should not be freed.
1902 free_or_keep = KEEP_ENT;
1903 save_zipwork(ent, swork, ent->fsize, file1);
1906 return (free_or_keep);
1910 do_sigwork(struct sigwork_entry *swork)
1912 struct sigwork_entry *nextsig;
1916 if (swork->sw_runcmd == 0 && (!(swork->sw_pidok) || swork->sw_pid == 0))
1917 return; /* no work to do... */
1920 * If nosignal (-s) was specified, then do not signal any process.
1921 * Note that a nosignal request triggers a warning message if the
1922 * rotated logfile needs to be compressed, *unless* -R was also
1923 * specified. We assume that an `-sR' request came from a process
1924 * which writes to the logfile, and as such, we assume that process
1925 * has already made sure the logfile is not presently in use. This
1926 * just sets swork->sw_pidok to a special value, and do_zipwork
1927 * will print any necessary warning(s).
1931 swork->sw_pidok = -1;
1936 * Compute the pause between consecutive signals. Use a longer
1937 * sleep time if we will be sending two signals to the same
1938 * daemon or process-group.
1941 nextsig = SLIST_NEXT(swork, sw_nextp);
1942 if (nextsig != NULL) {
1943 if (swork->sw_pid == nextsig->sw_pid)
1950 if (swork->sw_runcmd)
1951 printf("\tsh -c '%s %d'\n", swork->sw_fname,
1954 printf("\tkill -%d %d \t\t# %s\n", swork->sw_signum,
1955 (int)swork->sw_pid, swork->sw_fname);
1957 printf("\tsleep %d\n", secs);
1962 if (swork->sw_runcmd) {
1963 asprintf(&tmp, "%s %d", swork->sw_fname, swork->sw_signum);
1965 warn("can't allocate memory to run %s",
1970 printf("Run command: %s\n", tmp);
1973 warnx("%s: returned non-zero exit code: %d",
1980 kres = kill(swork->sw_pid, swork->sw_signum);
1983 * Assume that "no such process" (ESRCH) is something
1984 * to warn about, but is not an error. Presumably the
1985 * process which writes to the rotated log file(s) is
1986 * gone, in which case we should have no problem with
1987 * compressing the rotated log file(s).
1990 swork->sw_pidok = 0;
1991 warn("can't notify %s, pid %d = %s", swork->sw_pidtype,
1992 (int)swork->sw_pid, swork->sw_fname);
1995 printf("Notified %s pid %d = %s\n", swork->sw_pidtype,
1996 (int)swork->sw_pid, swork->sw_fname);
1999 printf("Pause %d second(s) between signals\n",
2007 do_zipwork(struct zipwork_entry *zwork)
2009 const char *pgm_name, *pgm_path;
2010 int errsav, fcount, zstatus;
2012 char zresult[MAXPATHLEN];
2013 char command[BUFSIZ];
2017 assert(zwork != NULL);
2019 strlcpy(zresult, zwork->zw_fname, sizeof(zresult));
2020 if (zwork->zw_conf != NULL &&
2021 zwork->zw_conf->compress > COMPRESS_NONE)
2022 for (c = 1; c < COMPRESS_TYPES; c++) {
2023 if (zwork->zw_conf->compress == c) {
2024 pgm_path = compress_type[c].path;
2025 (void) strlcat(zresult,
2026 compress_type[c].suffix, sizeof(zresult));
2027 args = compress_type[c].args;
2031 if (pgm_path == NULL) {
2032 warnx("invalid entry for %s in do_zipwork", zwork->zw_fname);
2035 pgm_name = strrchr(pgm_path, '/');
2036 if (pgm_name == NULL)
2037 pgm_name = pgm_path;
2041 args[0] = strdup(pgm_name);
2042 if (args[0] == NULL)
2044 for (c = 0; args[c] != NULL; c++)
2046 args[c] = zwork->zw_fname;
2048 if (zwork->zw_swork != NULL && zwork->zw_swork->sw_runcmd == 0 &&
2049 zwork->zw_swork->sw_pidok <= 0) {
2051 "log %s not compressed because daemon(s) not notified",
2053 change_attrs(zwork->zw_fname, zwork->zw_conf);
2057 strlcpy(command, pgm_path, sizeof(command));
2058 for (c = 1; args[c] != NULL; c++) {
2059 strlcat(command, " ", sizeof(command));
2060 strlcat(command, args[c], sizeof(command));
2063 printf("\t%s %s\n", pgm_name, zwork->zw_fname);
2064 change_attrs(zresult, zwork->zw_conf);
2070 while (pidzip < 0) {
2072 * The fork failed. If the failure was due to a temporary
2073 * problem, then wait a short time and try it again.
2076 warn("fork() for `%s %s'", pgm_name, zwork->zw_fname);
2077 if (errsav != EAGAIN || fcount > 5)
2078 errx(1, "Exiting...");
2084 /* The child process executes the compression command */
2085 execv(pgm_path, (char *const*) args);
2086 err(1, "execv(`%s')", command);
2089 wpid = waitpid(pidzip, &zstatus, 0);
2091 /* XXX - should this be a fatal error? */
2092 warn("%s: waitpid(%d)", pgm_path, pidzip);
2095 if (!WIFEXITED(zstatus)) {
2096 warnx("`%s' did not terminate normally", command);
2099 if (WEXITSTATUS(zstatus)) {
2100 warnx("`%s' terminated with a non-zero status (%d)", command,
2101 WEXITSTATUS(zstatus));
2105 /* Compression was successful, set file attributes on the result. */
2106 change_attrs(zresult, zwork->zw_conf);
2110 * Save information on any process we need to signal. Any single
2111 * process may need to be sent different signal-values for different
2112 * log files, but usually a single signal-value will cause the process
2113 * to close and re-open all of its log files.
2115 static struct sigwork_entry *
2116 save_sigwork(const struct conf_entry *ent)
2118 struct sigwork_entry *sprev, *stmp;
2124 SLIST_FOREACH(stmp, &swhead, sw_nextp) {
2125 ndiff = strcmp(ent->pid_cmd_file, stmp->sw_fname);
2129 if (ent->sig == stmp->sw_signum)
2131 if (ent->sig > stmp->sw_signum) {
2138 if (stmp != NULL && ndiff == 0)
2141 tmpsiz = sizeof(struct sigwork_entry) + strlen(ent->pid_cmd_file) + 1;
2142 stmp = malloc(tmpsiz);
2144 stmp->sw_runcmd = 0;
2145 /* If this is a command to run we just set the flag and run command */
2146 if (ent->flags & CE_PID2CMD) {
2149 stmp->sw_runcmd = 1;
2151 set_swpid(stmp, ent);
2153 stmp->sw_signum = ent->sig;
2154 strcpy(stmp->sw_fname, ent->pid_cmd_file);
2156 SLIST_INSERT_HEAD(&swhead, stmp, sw_nextp);
2158 SLIST_INSERT_AFTER(sprev, stmp, sw_nextp);
2163 * Save information on any file we need to compress. We may see the same
2164 * file multiple times, so check the full list to avoid duplicates. The
2165 * list itself is sorted smallest-to-largest, because that's the order we
2166 * want to compress the files. If the partition is very low on disk space,
2167 * then the smallest files are the most likely to compress, and compressing
2168 * them first will free up more space for the larger files.
2170 static struct zipwork_entry *
2171 save_zipwork(const struct conf_entry *ent, const struct sigwork_entry *swork,
2172 int zsize, const char *zipfname)
2174 struct zipwork_entry *zprev, *ztmp;
2178 /* Compute the size if the caller did not know it. */
2180 zsize = sizefile(zipfname);
2184 SLIST_FOREACH(ztmp, &zwhead, zw_nextp) {
2185 ndiff = strcmp(zipfname, ztmp->zw_fname);
2188 if (zsize > ztmp->zw_fsize)
2191 if (ztmp != NULL && ndiff == 0)
2194 tmpsiz = sizeof(struct zipwork_entry) + strlen(zipfname) + 1;
2195 ztmp = malloc(tmpsiz);
2196 ztmp->zw_conf = ent;
2197 ztmp->zw_swork = swork;
2198 ztmp->zw_fsize = zsize;
2199 strcpy(ztmp->zw_fname, zipfname);
2201 SLIST_INSERT_HEAD(&zwhead, ztmp, zw_nextp);
2203 SLIST_INSERT_AFTER(zprev, ztmp, zw_nextp);
2207 /* Send a signal to the pid specified by pidfile */
2209 set_swpid(struct sigwork_entry *swork, const struct conf_entry *ent)
2212 long minok, maxok, rval;
2213 char *endp, *linep, line[BUFSIZ];
2217 swork->sw_pidok = 0;
2219 swork->sw_pidtype = "daemon";
2220 if (ent->flags & CE_SIGNALGROUP) {
2222 * If we are expected to signal a process-group when
2223 * rotating this logfile, then the value read in should
2224 * be the negative of a valid process ID.
2228 swork->sw_pidtype = "process-group";
2231 f = fopen(ent->pid_cmd_file, "r");
2233 if (errno == ENOENT && enforcepid == 0) {
2235 * Warn if the PID file doesn't exist, but do
2236 * not consider it an error. Most likely it
2237 * means the process has been terminated,
2238 * so it should be safe to rotate any log
2239 * files that the process would have been using.
2241 swork->sw_pidok = 1;
2242 warnx("pid file doesn't exist: %s", ent->pid_cmd_file);
2244 warn("can't open pid file: %s", ent->pid_cmd_file);
2248 if (fgets(line, BUFSIZ, f) == NULL) {
2250 * Warn if the PID file is empty, but do not consider
2251 * it an error. Most likely it means the process has
2252 * has terminated, so it should be safe to rotate any
2253 * log files that the process would have been using.
2255 if (feof(f) && enforcepid == 0) {
2256 swork->sw_pidok = 1;
2257 warnx("pid/cmd file is empty: %s", ent->pid_cmd_file);
2259 warn("can't read from pid file: %s", ent->pid_cmd_file);
2267 while (*linep == ' ')
2269 rval = strtol(linep, &endp, 10);
2270 if (*endp != '\0' && !isspacech(*endp)) {
2271 warnx("pid file does not start with a valid number: %s",
2273 } else if (rval < minok || rval > maxok) {
2274 warnx("bad value '%ld' for process number in %s",
2275 rval, ent->pid_cmd_file);
2277 warnx("\t(expecting value between %ld and %ld)",
2280 swork->sw_pidok = 1;
2281 swork->sw_pid = rval;
2287 /* Log the fact that the logs were turned over */
2289 log_trim(const char *logname, const struct conf_entry *log_ent)
2294 if ((f = fopen(logname, "a")) == NULL)
2297 if (log_ent->def_cfg)
2298 xtra = " using <default> rule";
2299 if (log_ent->flags & CE_RFC5424) {
2300 if (log_ent->firstcreate) {
2301 fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s\n",
2302 LOG_MAKEPRI(LOG_USER, LOG_INFO),
2303 daytime_rfc5424, hostname, getpid(),
2304 "logfile first created", xtra);
2305 } else if (log_ent->r_reason != NULL) {
2306 fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s%s\n",
2307 LOG_MAKEPRI(LOG_USER, LOG_INFO),
2308 daytime_rfc5424, hostname, getpid(),
2309 "logfile turned over", log_ent->r_reason, xtra);
2311 fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s\n",
2312 LOG_MAKEPRI(LOG_USER, LOG_INFO),
2313 daytime_rfc5424, hostname, getpid(),
2314 "logfile turned over", xtra);
2317 if (log_ent->firstcreate)
2318 fprintf(f, "%s %s newsyslog[%d]: logfile first created%s\n",
2319 daytime, hostname, getpid(), xtra);
2320 else if (log_ent->r_reason != NULL)
2321 fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s%s\n",
2322 daytime, hostname, getpid(), log_ent->r_reason, xtra);
2324 fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s\n",
2325 daytime, hostname, getpid(), xtra);
2327 if (fclose(f) == EOF)
2328 err(1, "log_trim: fclose");
2332 /* Return size in kilobytes of a file */
2334 sizefile(const char *file)
2338 if (stat(file, &sb) < 0)
2340 return (kbytes(sb.st_size));
2344 * Return the mtime of the most recent archive of the logfile, using timestamp
2348 mtime_old_timelog(const char *file)
2356 char *logfname, *logfnamebuf, *dir, *dirbuf;
2360 if ((dirbuf = strdup(file)) == NULL) {
2361 warn("strdup() of '%s'", file);
2364 dir = dirname(dirbuf);
2365 if ((logfnamebuf = strdup(file)) == NULL) {
2366 warn("strdup() of '%s'", file);
2370 logfname = basename(logfnamebuf);
2371 if (logfname[0] == '/') {
2372 warnx("Invalid log filename '%s'", logfname);
2376 if ((dirp = opendir(dir)) == NULL) {
2377 warn("Cannot open log directory '%s'", dir);
2380 dir_fd = dirfd(dirp);
2381 /* Open the archive dir and find the most recent archive of logfname. */
2382 while ((dp = readdir(dirp)) != NULL) {
2383 if (validate_old_timelog(dir_fd, dp, logfname, &tm) == 0)
2386 if (fstatat(dir_fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
2387 warn("Cannot stat '%s'", file);
2390 if (t < sb.st_mtime)
2401 /* Return the age in hours of the most recent archive of the logfile. */
2403 age_old_log(const char *file)
2406 const char *logfile_suffix;
2407 char tmp[MAXPATHLEN + sizeof(".0") + COMPRESS_SUFFIX_MAXLEN + 1];
2413 /* build name of archive directory into tmp */
2414 if (*archdirname == '/') { /* absolute */
2415 strlcpy(tmp, archdirname, sizeof(tmp));
2416 } else { /* relative */
2417 /* get directory part of logfile */
2418 strlcpy(tmp, file, sizeof(tmp));
2419 if ((p = strrchr(tmp, '/')) == NULL)
2423 strlcat(tmp, archdirname, sizeof(tmp));
2426 strlcat(tmp, "/", sizeof(tmp));
2428 /* get filename part of logfile */
2429 if ((p = strrchr(file, '/')) == NULL)
2430 strlcat(tmp, file, sizeof(tmp));
2432 strlcat(tmp, p + 1, sizeof(tmp));
2434 (void) strlcpy(tmp, file, sizeof(tmp));
2437 if (timefnamefmt != NULL) {
2438 mtime = mtime_old_timelog(tmp);
2442 strlcat(tmp, ".0", sizeof(tmp));
2443 logfile_suffix = get_logfile_suffix(tmp);
2444 if (logfile_suffix == NULL)
2446 (void) strlcat(tmp, logfile_suffix, sizeof(tmp));
2447 if (stat(tmp, &sb) < 0)
2449 mtime = sb.st_mtime;
2452 return ((int)(ptimeget_secs(timenow) - mtime + 1800) / 3600);
2455 /* Skip Over Blanks */
2459 while (p && *p && isspace(*p))
2464 /* Skip Over Non-Blanks */
2468 while (p && *p && !isspace(*p))
2473 /* Check if string is actually a number */
2475 isnumberstr(const char *string)
2478 if (!isdigitch(*string++))
2484 /* Check if string contains a glob */
2486 isglobstr(const char *string)
2490 while ((chr = *string++)) {
2491 if (chr == '*' || chr == '?' || chr == '[')
2498 * Save the active log file under a new name. A link to the new name
2499 * is the quick-and-easy way to do this. If that fails (which it will
2500 * if the destination is on another partition), then make a copy of
2501 * the file to the new location.
2504 savelog(char *from, char *to)
2509 res = link(from, to);
2513 if ((src = fopen(from, "r")) == NULL)
2514 err(1, "can't fopen %s for reading", from);
2515 if ((dst = fopen(to, "w")) == NULL)
2516 err(1, "can't fopen %s for writing", to);
2518 while ((c = getc(src)) != EOF) {
2519 if ((putc(c, dst)) == EOF)
2520 err(1, "error writing to %s", to);
2524 err(1, "error reading from %s", from);
2525 if ((fclose(src)) != 0)
2526 err(1, "can't fclose %s", to);
2527 if ((fclose(dst)) != 0)
2528 err(1, "can't fclose %s", from);
2531 /* create one or more directory components of a path */
2533 createdir(const struct conf_entry *ent, char *dirpart)
2537 char mkdirpath[MAXPATHLEN];
2545 if (*s != '/' && *s != '\0')
2548 res = lstat(mkdirpath, &st);
2551 printf("\tmkdir %s\n", mkdirpath);
2553 res = mkdir(mkdirpath, 0755);
2555 err(1, "Error on mkdir(\"%s\") for -a",
2563 if (ent->firstcreate)
2564 printf("Created directory '%s' for new %s\n",
2567 printf("Created directory '%s' for -a\n", dirpart);
2572 * Create a new log file, destroying any currently-existing version
2573 * of the log file in the process. If the caller wants a backup copy
2574 * of the file to exist, they should call 'link(logfile,logbackup)'
2575 * before calling this routine.
2578 createlog(const struct conf_entry *ent)
2582 char *realfile, *slash, tempfile[MAXPATHLEN];
2585 realfile = ent->log;
2588 * If this log file is being created for the first time (-C option),
2589 * then it may also be true that the parent directory does not exist
2590 * yet. Check, and create that directory if it is missing.
2592 if (ent->firstcreate) {
2593 strlcpy(tempfile, realfile, sizeof(tempfile));
2594 slash = strrchr(tempfile, '/');
2595 if (slash != NULL) {
2597 failed = stat(tempfile, &st);
2598 if (failed && errno != ENOENT)
2599 err(1, "Error on stat(%s)", tempfile);
2601 createdir(ent, tempfile);
2602 else if (!S_ISDIR(st.st_mode))
2603 errx(1, "%s exists but is not a directory",
2609 * First create an unused filename, so it can be chown'ed and
2610 * chmod'ed before it is moved into the real location. mkstemp
2611 * will create the file mode=600 & owned by us. Note that all
2612 * temp files will have a suffix of '.z<something>'.
2614 strlcpy(tempfile, realfile, sizeof(tempfile));
2615 strlcat(tempfile, ".zXXXXXX", sizeof(tempfile));
2617 printf("\tmktemp %s\n", tempfile);
2619 fd = mkstemp(tempfile);
2621 err(1, "can't mkstemp logfile %s", tempfile);
2624 * Add status message to what will become the new log file.
2626 if (!(ent->flags & CE_BINARY)) {
2627 if (log_trim(tempfile, ent))
2628 err(1, "can't add status message to log");
2632 /* Change the owner/group, if we are supposed to */
2633 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2635 printf("\tchown %u:%u %s\n", ent->uid, ent->gid,
2638 failed = fchown(fd, ent->uid, ent->gid);
2640 err(1, "can't fchown temp file %s", tempfile);
2644 /* Turn on NODUMP if it was requested in the config-file. */
2645 if (ent->flags & CE_NODUMP) {
2647 printf("\tchflags nodump %s\n", tempfile);
2649 failed = fchflags(fd, UF_NODUMP);
2651 warn("log_trim: fchflags(NODUMP)");
2657 * Note that if the real logfile still exists, and if the call
2658 * to rename() fails, then "neither the old file nor the new
2659 * file shall be changed or created" (to quote the standard).
2660 * If the call succeeds, then the file will be replaced without
2661 * any window where some other process might find that the file
2663 * XXX - ? It may be that for some error conditions, we could
2664 * retry by first removing the realfile and then renaming.
2667 printf("\tchmod %o %s\n", ent->permissions, tempfile);
2668 printf("\tmv %s %s\n", tempfile, realfile);
2670 failed = fchmod(fd, ent->permissions);
2672 err(1, "can't fchmod temp file '%s'", tempfile);
2673 failed = rename(tempfile, realfile);
2675 err(1, "can't mv %s to %s", tempfile, realfile);
2683 * Change the attributes of a given filename to what was specified in
2684 * the newsyslog.conf entry. This routine is only called for files
2685 * that newsyslog expects that it has created, and thus it is a fatal
2686 * error if this routine finds that the file does not exist.
2689 change_attrs(const char *fname, const struct conf_entry *ent)
2694 printf("\tchmod %o %s\n", ent->permissions, fname);
2696 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
2697 printf("\tchown %u:%u %s\n",
2698 ent->uid, ent->gid, fname);
2700 if (ent->flags & CE_NODUMP)
2701 printf("\tchflags nodump %s\n", fname);
2705 failed = chmod(fname, ent->permissions);
2708 err(1, "chmod(%s) in change_attrs", fname);
2709 warn("change_attrs couldn't chmod(%s)", fname);
2712 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2713 failed = chown(fname, ent->uid, ent->gid);
2715 warn("can't chown %s", fname);
2718 if (ent->flags & CE_NODUMP) {
2719 failed = chflags(fname, UF_NODUMP);
2721 warn("can't chflags %s NODUMP", fname);
2726 * Parse a signal number or signal name. Returns the signal number parsed or -1
2730 parse_signal(const char *str)
2735 sig = strtonum(str, 1, sys_nsig - 1, &errstr);
2739 if (strncasecmp(str, "SIG", 3) == 0)
2742 for (i = 1; i < sys_nsig; i++) {
2743 if (strcasecmp(str, sys_signame[i]) == 0)