]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/newsyslog/newsyslog.c
Complete fix for CID 1007454, CID 1007453: Resource leak in newsyslog
[FreeBSD/FreeBSD.git] / usr.sbin / newsyslog / newsyslog.c
1 /*-
2  * ------+---------+---------+-------- + --------+---------+---------+---------*
3  * This file includes significant modifications done by:
4  * Copyright (c) 2003, 2004  - Garance Alistair Drosehn <gad@FreeBSD.org>.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
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.
15  *
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
26  * SUCH DAMAGE.
27  *
28  * ------+---------+---------+-------- + --------+---------+---------+---------*
29  */
30
31 /*
32  * This file contains changes from the Open Software Foundation.
33  */
34
35 /*
36  * Copyright 1988, 1989 by the Massachusetts Institute of Technology
37  *
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
47  * warranty.
48  *
49  */
50
51 /*
52  * newsyslog - roll over selected logs at the appropriate time, keeping the a
53  * specified number of backup files around.
54  */
55
56 #include <sys/cdefs.h>
57 __FBSDID("$FreeBSD$");
58
59 #define OSF
60
61 #include <sys/param.h>
62 #include <sys/queue.h>
63 #include <sys/sbuf.h>
64 #include <sys/stat.h>
65 #include <sys/wait.h>
66
67 #include <assert.h>
68 #include <ctype.h>
69 #include <err.h>
70 #include <errno.h>
71 #include <dirent.h>
72 #include <fcntl.h>
73 #include <fnmatch.h>
74 #include <glob.h>
75 #include <grp.h>
76 #include <paths.h>
77 #include <pwd.h>
78 #include <signal.h>
79 #include <stdio.h>
80 #include <libgen.h>
81 #include <stdlib.h>
82 #include <string.h>
83 #include <syslog.h>
84 #include <time.h>
85 #include <unistd.h>
86
87 #include "pathnames.h"
88 #include "extern.h"
89
90 /*
91  * Compression types
92  */
93 #define COMPRESS_TYPES  5       /* Number of supported compression types */
94
95 #define COMPRESS_NONE   0
96 #define COMPRESS_GZIP   1
97 #define COMPRESS_BZIP2  2
98 #define COMPRESS_XZ     3
99 #define COMPRESS_ZSTD   4
100
101 /*
102  * Bit-values for the 'flags' parsed from a config-file entry.
103  */
104 #define CE_BINARY       0x0008  /* Logfile is in binary, do not add status */
105                                 /*    messages to logfile(s) when rotating. */
106 #define CE_NOSIGNAL     0x0010  /* There is no process to signal when */
107                                 /*    trimming this file. */
108 #define CE_TRIMAT       0x0020  /* trim file at a specific time. */
109 #define CE_GLOB         0x0040  /* name of the log is file name pattern. */
110 #define CE_SIGNALGROUP  0x0080  /* Signal a process-group instead of a single */
111                                 /*    process when trimming this file. */
112 #define CE_CREATE       0x0100  /* Create the log file if it does not exist. */
113 #define CE_NODUMP       0x0200  /* Set 'nodump' on newly created log file. */
114 #define CE_PID2CMD      0x0400  /* Replace PID file with a shell command.*/
115 #define CE_PLAIN0       0x0800  /* Do not compress zero'th history file */
116 #define CE_RFC5424      0x1000  /* Use RFC5424 format rotation message */
117
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 */
120
121 #define kbytes(size)  (((size) + 1023) >> 10)
122
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"
127
128 #define MAX_OLDLOGS 65536       /* Default maximum number of old logfiles */
129
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 */
136 };
137
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" };
142
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) }
149 };
150
151 struct conf_entry {
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 */
170 };
171
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 */
180 };
181
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 */
188 };
189
190 struct include_entry {
191         STAILQ_ENTRY(include_entry) inc_nextp;
192         const char *file;       /* Name of file to process */
193 };
194
195 struct oldlog_entry {
196         char *fname;            /* Filename of the log file */
197         time_t t;               /* Parsed timestamp of the logfile */
198 };
199
200 typedef enum {
201         FREE_ENT, KEEP_ENT
202 }       fk_entry;
203
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);
210
211 int dbg_at_times;               /* -D Show details of 'trim_at' code */
212
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 */
233
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 */
236
237 #define DAYTIME_LEN     16
238 static char daytime[DAYTIME_LEN];/* The current time in human readable form,
239                                   * used for rotation-tracking messages. */
240
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.
245  */
246 #define DAYTIME_RFC5424_LEN     sizeof("YYYY-MM-DDTHH:MM:SS+00:00")
247 static char daytime_rfc5424[DAYTIME_RFC5424_LEN];
248
249 static char hostname[MAXHOSTNAMELEN]; /* hostname */
250 static size_t hostname_shortlen;
251
252 static const char *path_syslogpid = _PATH_SYSLOGPID;
253
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);
290
291 /*
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.
295  */
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))
300
301 int
302 main(int argc, char **argv)
303 {
304         struct cflist *worklist;
305         struct conf_entry *p;
306         struct sigwork_entry *stmp;
307         struct zipwork_entry *ztmp;
308
309         SLIST_INIT(&swhead);
310         SLIST_INIT(&zwhead);
311
312         parse_args(argc, argv);
313         argc -= optind;
314         argv += optind;
315
316         if (needroot && getuid() && geteuid())
317                 errx(1, "must have root privs");
318         worklist = get_worklist(argv);
319
320         /*
321          * Rotate all the files which need to be rotated.  Note that
322          * some users have *hundreds* of entries in newsyslog.conf!
323          */
324         while (!STAILQ_EMPTY(worklist)) {
325                 p = STAILQ_FIRST(worklist);
326                 STAILQ_REMOVE_HEAD(worklist, cf_nextp);
327                 if (do_entry(p) == FREE_ENT)
328                         free_entry(p);
329         }
330
331         /*
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.
336          */
337         if (!SLIST_EMPTY(&swhead)) {
338                 if (noaction || verbose)
339                         printf("Signal all daemon process(es)...\n");
340                 SLIST_FOREACH(stmp, &swhead, sw_nextp)
341                         do_sigwork(stmp);
342                 if (!(rotatereq && nosignal)) {
343                         if (noaction)
344                                 printf("\tsleep 10\n");
345                         else {
346                                 if (verbose)
347                                         printf("Pause 10 seconds to allow "
348                                             "daemon(s) to close log file(s)\n");
349                                 sleep(10);
350                         }
351                 }
352         }
353         /*
354          * Compress all files that we're expected to compress, now
355          * that all processes should have closed the files which
356          * have been rotated.
357          */
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);
363                         do_zipwork(ztmp);
364                         SLIST_REMOVE_HEAD(&zwhead, zw_nextp);
365                         free(ztmp);
366                 }
367         }
368         /* Now free all the sigwork entries. */
369         while (!SLIST_EMPTY(&swhead)) {
370                 stmp = SLIST_FIRST(&swhead);
371                 SLIST_REMOVE_HEAD(&swhead, sw_nextp);
372                 free(stmp);
373         }
374
375         while (wait(NULL) > 0 || errno == EINTR)
376                 ;
377         free(timefnamefmt);
378         free(requestor);
379         return (0);
380 }
381
382 static struct conf_entry *
383 init_entry(const char *fname, struct conf_entry *src_entry)
384 {
385         struct conf_entry *tempwork;
386
387         if (verbose > 4)
388                 printf("\t--> [creating entry for %s]\n", fname);
389
390         tempwork = malloc(sizeof(struct conf_entry));
391         if (tempwork == NULL)
392                 err(1, "malloc of conf_entry for %s", fname);
393
394         if (destdir == NULL || fname[0] != '/')
395                 tempwork->log = strdup(fname);
396         else
397                 asprintf(&tempwork->log, "%s%s", destdir, fname);
398         if (tempwork->log == NULL)
399                 err(1, "strdup for %s", fname);
400
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;
422         } else {
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;
436                 tempwork->flags = 0;
437                 tempwork->compress = COMPRESS_NONE;
438                 tempwork->sig = SIGHUP;
439                 tempwork->def_cfg = 0;
440         }
441
442         return (tempwork);
443 }
444
445 static void
446 free_entry(struct conf_entry *ent)
447 {
448
449         if (ent == NULL)
450                 return;
451
452         if (ent->log != NULL) {
453                 if (verbose > 4)
454                         printf("\t--> [freeing entry for %s]\n", ent->log);
455                 free(ent->log);
456                 ent->log = NULL;
457         }
458
459         if (ent->pid_cmd_file != NULL) {
460                 free(ent->pid_cmd_file);
461                 ent->pid_cmd_file = NULL;
462         }
463
464         if (ent->r_reason != NULL) {
465                 free(ent->r_reason);
466                 ent->r_reason = NULL;
467         }
468
469         if (ent->trim_at != NULL) {
470                 ptime_free(ent->trim_at);
471                 ent->trim_at = NULL;
472         }
473
474         free(ent);
475 }
476
477 static void
478 free_clist(struct cflist *list)
479 {
480         struct conf_entry *ent;
481
482         while (!STAILQ_EMPTY(list)) {
483                 ent = STAILQ_FIRST(list);
484                 STAILQ_REMOVE_HEAD(list, cf_nextp);
485                 free_entry(ent);
486         }
487
488         free(list);
489         list = NULL;
490 }
491
492 static fk_entry
493 do_entry(struct conf_entry * ent)
494 {
495 #define REASON_MAX      80
496         int modtime;
497         fk_entry free_or_keep;
498         double diffsecs;
499         char temp_reason[REASON_MAX];
500         int oversized;
501
502         free_or_keep = FREE_ENT;
503         if (verbose)
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);
509         ent->rotate = 0;
510         ent->firstcreate = 0;
511         if (ent->fsize < 0) {
512                 /*
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.
517                  */
518                 temp_reason[0] = '\0';
519                 if (createlogs > 1)
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);
525                 else if (createlogs)
526                         strlcpy(temp_reason, " (no C flag)", REASON_MAX);
527
528                 if (ent->firstcreate) {
529                         if (verbose)
530                                 printf("does not exist -> will create.\n");
531                         createlog(ent);
532                 } else if (verbose) {
533                         printf("does not exist, skipped%s.\n", temp_reason);
534                 }
535         } else {
536                 if (ent->flags & CE_TRIMAT && !force && !rotatereq &&
537                     !oversized) {
538                         diffsecs = ptimeget_diff(timenow, ent->trim_at);
539                         if (diffsecs < 0.0) {
540                                 /* trim_at is some time in the future. */
541                                 if (verbose) {
542                                         ptime_adjust4dst(ent->trim_at,
543                                             timenow);
544                                         printf("--> will trim at %s",
545                                             ptimeget_ctime(ent->trim_at));
546                                 }
547                                 return (free_or_keep);
548                         } else if (diffsecs >= 3600.0) {
549                                 /*
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.
553                                  */
554                                 if (verbose && dbg_at_times)
555                                         printf("\n\t--> prev trim at %s\t",
556                                             ptimeget_ctime(ent->trim_at));
557                                 if (verbose) {
558                                         ptimeset_nxtime(ent->trim_at);
559                                         printf("--> will trim at %s",
560                                             ptimeget_ctime(ent->trim_at));
561                                 }
562                                 return (free_or_keep);
563                         } else if (verbose && noaction && dbg_at_times) {
564                                 /*
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.
569                                  */
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");
575                         }
576                 }
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);
581
582                 /*
583                  * Figure out if this logfile needs to be rotated.
584                  */
585                 temp_reason[0] = '\0';
586                 if (rotatereq) {
587                         ent->rotate = 1;
588                         snprintf(temp_reason, REASON_MAX, " due to -R from %s",
589                             requestor);
590                 } else if (force) {
591                         ent->rotate = 1;
592                         snprintf(temp_reason, REASON_MAX, " due to -F request");
593                 } else if (oversized) {
594                         ent->rotate = 1;
595                         snprintf(temp_reason, REASON_MAX, " due to size>%dK",
596                             ent->trsize);
597                 } else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) {
598                         ent->rotate = 1;
599                 } else if ((ent->hours > 0) && ((modtime >= ent->hours) ||
600                     (modtime < 0))) {
601                         ent->rotate = 1;
602                 }
603
604                 /*
605                  * If the file needs to be rotated, then rotate it.
606                  */
607                 if (ent->rotate && !norotate) {
608                         if (temp_reason[0] != '\0')
609                                 ent->r_reason = strdup(temp_reason);
610                         if (verbose)
611                                 printf("--> trimming log....\n");
612                         if (noaction && !verbose)
613                                 printf("%s <%d%s>: trimming\n", ent->log,
614                                     ent->numlogs,
615                                     compress_type[ent->compress].flag);
616                         free_or_keep = do_rotate(ent);
617                 } else {
618                         if (verbose)
619                                 printf("--> skipping\n");
620                 }
621         }
622         return (free_or_keep);
623 #undef REASON_MAX
624 }
625
626 static void
627 parse_args(int argc, char **argv)
628 {
629         int ch;
630         char *p;
631
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);
636
637         /* Let's get our hostname */
638         (void)gethostname(hostname, sizeof(hostname));
639         hostname_shortlen = strcspn(hostname, ".");
640
641         /* Parse command line options. */
642         while ((ch = getopt(argc, argv, "a:d:f:nrst:vCD:FNPR:S:")) != -1)
643                 switch (ch) {
644                 case 'a':
645                         archtodir++;
646                         archdirname = optarg;
647                         break;
648                 case 'd':
649                         destdir = optarg;
650                         break;
651                 case 'f':
652                         conf = optarg;
653                         break;
654                 case 'n':
655                         noaction++;
656                         /* FALLTHROUGH */
657                 case 'r':
658                         needroot = 0;
659                         break;
660                 case 's':
661                         nosignal = 1;
662                         break;
663                 case 't':
664                         if (optarg[0] == '\0' ||
665                             strcmp(optarg, "DEFAULT") == 0)
666                                 timefnamefmt = strdup(DEFAULT_TIMEFNAME_FMT);
667                         else
668                                 timefnamefmt = strdup(optarg);
669                         break;
670                 case 'v':
671                         verbose++;
672                         break;
673                 case 'C':
674                         /* Useful for things like rc.diskless... */
675                         createlogs++;
676                         break;
677                 case 'D':
678                         /*
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.
682                          */
683                         if (parse_doption(optarg))
684                                 break;
685                         usage();
686                         /* NOTREACHED */
687                 case 'F':
688                         force++;
689                         break;
690                 case 'N':
691                         norotate++;
692                         break;
693                 case 'P':
694                         enforcepid++;
695                         break;
696                 case 'R':
697                         rotatereq++;
698                         requestor = strdup(optarg);
699                         break;
700                 case 'S':
701                         path_syslogpid = optarg;
702                         break;
703                 case 'm':       /* Used by OpenBSD for "monitor mode" */
704                 default:
705                         usage();
706                         /* NOTREACHED */
707                 }
708
709         if (force && norotate) {
710                 warnx("Only one of -F and -N may be specified.");
711                 usage();
712                 /* NOTREACHED */
713         }
714
715         if (rotatereq) {
716                 if (optind == argc) {
717                         warnx("At least one filename must be given when -R is specified.");
718                         usage();
719                         /* NOTREACHED */
720                 }
721                 /* Make sure "requestor" value is safe for a syslog message. */
722                 for (p = requestor; *p != '\0'; p++) {
723                         if (!isprintch(*p) && (*p != '\t'))
724                                 *p = '.';
725                 }
726         }
727
728         if (dbg_timenow) {
729                 /*
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.
734                  */
735                 ptime_free(timenow);
736                 timenow = dbg_timenow;
737                 fprintf(stderr, "Debug: Running as if TimeNow is %s",
738                     ptimeget_ctime(dbg_timenow));
739         }
740
741 }
742
743 /*
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...
747  */
748 static int
749 parse_doption(const char *doption)
750 {
751         const char TN[] = "TN=";
752         int res;
753
754         if (strncmp(doption, TN, sizeof(TN) - 1) == 0) {
755                 /*
756                  * The "TimeNow" debugging option.  This might be off
757                  * by an hour when crossing a timezone change.
758                  */
759                 dbg_timenow = ptime_init(NULL);
760                 res = ptime_relparse(dbg_timenow, PTM_PARSE_ISO8601,
761                     time(NULL), doption + sizeof(TN) - 1);
762                 if (res == -2) {
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 */
768                 }
769                 return (1);                     /* successfully parsed */
770
771         }
772
773         if (strcmp(doption, "ats") == 0) {
774                 dbg_at_times++;
775                 return (1);                     /* successfully parsed */
776         }
777
778         /* XXX - This check could probably be dropped. */
779         if ((strcmp(doption, "neworder") == 0) || (strcmp(doption, "oldorder")
780             == 0)) {
781                 warnx("NOTE: newsyslog always uses 'neworder'.");
782                 return (1);                     /* successfully parsed */
783         }
784
785         warnx("Unknown -D (debug) option: '%s'", doption);
786         return (0);                             /* failure */
787 }
788
789 static void
790 usage(void)
791 {
792
793         fprintf(stderr,
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. */
797         free(timefnamefmt);
798         free(requestor);
799         exit(1);
800 }
801
802 /*
803  * Parse a configuration file and return a linked list of all the logs
804  * which should be processed.
805  */
806 static struct cflist *
807 get_worklist(char **files)
808 {
809         FILE *f;
810         char **given;
811         struct cflist *cmdlist, *filelist, *globlist;
812         struct conf_entry *defconf, *dupent, *ent;
813         struct ilist inclist;
814         struct include_entry *inc;
815         int gmatch, fnres;
816
817         defconf = NULL;
818         STAILQ_INIT(&inclist);
819
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);
828
829         inc = malloc(sizeof(struct include_entry));
830         if (inc == NULL)
831                 err(1, "malloc of inc");
832         inc->file = conf;
833         if (inc->file == NULL)
834                 inc->file = _PATH_CONF;
835         STAILQ_INSERT_TAIL(&inclist, inc, inc_nextp);
836
837         STAILQ_FOREACH(inc, &inclist, inc_nextp) {
838                 if (strcmp(inc->file, "-") != 0)
839                         f = fopen(inc->file, "r");
840                 else {
841                         f = stdin;
842                         inc->file = "<stdin>";
843                 }
844                 if (!f)
845                         err(1, "%s", inc->file);
846
847                 if (verbose)
848                         printf("Processing %s\n", inc->file);
849                 parse_file(f, filelist, globlist, &defconf, &inclist);
850                 (void) fclose(f);
851         }
852
853         /*
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.
859          */
860         if (*files == NULL) {
861                 expand_globs(filelist, globlist);
862                 free_clist(globlist);
863                 if (defconf != NULL)
864                         free_entry(defconf);
865                 return (filelist);
866         }
867
868         /*
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.
874          */
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;
880         }
881
882         /*
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.
887          *
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.
893          */
894         cmdlist = malloc(sizeof(struct cflist));
895         if (cmdlist == NULL)
896                 err(1, "malloc of cmdlist");
897         STAILQ_INIT(cmdlist);
898
899         for (given = files; *given; ++given) {
900                 /*
901                  * First try to find exact-matches for this given file.
902                  */
903                 gmatch = 0;
904                 STAILQ_FOREACH(ent, filelist, cf_nextp) {
905                         if (strcmp(ent->log, *given) == 0) {
906                                 gmatch++;
907                                 dupent = init_entry(*given, ent);
908                                 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
909                         }
910                 }
911                 if (gmatch) {
912                         if (verbose > 2)
913                                 printf("\t+ Matched entry %s\n", *given);
914                         continue;
915                 }
916
917                 /*
918                  * There was no exact-match for this given file, so look
919                  * for a "glob" entry which does match.
920                  */
921                 gmatch = 0;
922                 if (verbose > 2)
923                         printf("\t+ Checking globs for %s\n", *given);
924                 STAILQ_FOREACH(ent, globlist, cf_nextp) {
925                         fnres = fnmatch(ent->log, *given, FNM_PATHNAME);
926                         if (verbose > 2)
927                                 printf("\t+    = %d for pattern %s\n", fnres,
928                                     ent->log);
929                         if (fnres == 0) {
930                                 gmatch++;
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 */
936                                 break;
937                         }
938                 }
939                 if (gmatch) {
940                         if (verbose > 2)
941                                 printf("\t+ Matched %s via %s\n", *given,
942                                     ent->log);
943                         continue;
944                 }
945
946                 /*
947                  * This given file was not found in any config file, so
948                  * add a worklist item based on the default entry.
949                  */
950                 if (verbose > 2)
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 */
955                 dupent->def_cfg = 1;
956                 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
957         }
958
959         /*
960          * Free all the entries in the original work list, the list of
961          * glob entries, and the default entry.
962          */
963         free_clist(filelist);
964         free_clist(globlist);
965         free_entry(defconf);
966
967         /* And finally, return a worklist which matches the given files. */
968         return (cmdlist);
969 }
970
971 /*
972  * Expand the list of entries with filename patterns, and add all files
973  * which match those glob-entries onto the worklist.
974  */
975 static void
976 expand_globs(struct cflist *work_p, struct cflist *glob_p)
977 {
978         int gmatch, gres;
979         size_t i;
980         char *mfname;
981         struct conf_entry *dupent, *ent, *globent;
982         glob_t pglob;
983         struct stat st_fm;
984
985         /*
986          * The worklist contains all fully-specified (non-GLOB) names.
987          *
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.
992          */
993         STAILQ_FOREACH(globent, glob_p, cf_nextp) {
994                 gres = glob(globent->log, GLOB_NOCHECK, NULL, &pglob);
995                 if (gres != 0) {
996                         warn("cannot expand pattern (%d): %s", gres,
997                             globent->log);
998                         continue;
999                 }
1000
1001                 if (verbose > 2)
1002                         printf("\t+ Expanding pattern %s\n", globent->log);
1003                 for (i = 0; i < pglob.gl_matchc; i++) {
1004                         mfname = pglob.gl_pathv[i];
1005
1006                         /* See if this file already has a specific entry. */
1007                         gmatch = 0;
1008                         STAILQ_FOREACH(ent, work_p, cf_nextp) {
1009                                 if (strcmp(mfname, ent->log) == 0) {
1010                                         gmatch++;
1011                                         break;
1012                                 }
1013                         }
1014                         if (gmatch)
1015                                 continue;
1016
1017                         /* Make sure the named matched is a file. */
1018                         gres = lstat(mfname, &st_fm);
1019                         if (gres != 0) {
1020                                 /* Error on a file that glob() matched?!? */
1021                                 warn("Skipping %s - lstat() error", mfname);
1022                                 continue;
1023                         }
1024                         if (!S_ISREG(st_fm.st_mode)) {
1025                                 /* We only rotate files! */
1026                                 if (verbose > 2)
1027                                         printf("\t+  . skipping %s (!file)\n",
1028                                             mfname);
1029                                 continue;
1030                         }
1031
1032                         if (verbose > 2)
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;
1037
1038                         /* Add to the worklist. */
1039                         STAILQ_INSERT_TAIL(work_p, dupent, cf_nextp);
1040                 }
1041                 globfree(&pglob);
1042                 if (verbose > 2)
1043                         printf("\t+ Done with pattern %s\n", globent->log);
1044         }
1045 }
1046
1047 /*
1048  * Parse a configuration file and update a linked list of all the logs to
1049  * process.
1050  */
1051 static void
1052 parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
1053     struct conf_entry **defconf_p, struct ilist *inclist)
1054 {
1055         char line[BUFSIZ], *parse, *q;
1056         char *cp, *errline, *group;
1057         struct conf_entry *working;
1058         struct passwd *pwd;
1059         struct group *grp;
1060         glob_t pglob;
1061         int eol, ptm_opts, res, special;
1062         size_t i;
1063
1064         errline = NULL;
1065         while (fgets(line, BUFSIZ, cf)) {
1066                 if ((line[0] == '\n') || (line[0] == '#') ||
1067                     (strlen(line) == 0))
1068                         continue;
1069                 if (errline != NULL)
1070                         free(errline);
1071                 errline = strdup(line);
1072                 for (cp = line + 1; *cp != '\0'; cp++) {
1073                         if (*cp != '#')
1074                                 continue;
1075                         if (*(cp - 1) == '\\') {
1076                                 strcpy(cp - 1, cp);
1077                                 cp--;
1078                                 continue;
1079                         }
1080                         *cp = '\0';
1081                         break;
1082                 }
1083
1084                 q = parse = missing_field(sob(line), errline);
1085                 parse = son(line);
1086                 if (!*parse)
1087                         errx(1, "malformed line (missing fields):\n%s",
1088                             errline);
1089                 *parse = '\0';
1090
1091                 /*
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).
1095                  */
1096                 if (strcasecmp(DEBUG_MARKER, q) == 0) {
1097                         q = parse = missing_field(sob(parse + 1), errline);
1098                         parse = son(parse);
1099                         if (!*parse)
1100                                 warnx("debug line specifies no option:\n%s",
1101                                     errline);
1102                         else {
1103                                 *parse = '\0';
1104                                 parse_doption(q);
1105                         }
1106                         continue;
1107                 } else if (strcasecmp(INCLUDE_MARKER, q) == 0) {
1108                         if (verbose)
1109                                 printf("Found: %s", errline);
1110                         q = parse = missing_field(sob(parse + 1), errline);
1111                         parse = son(parse);
1112                         if (!*parse) {
1113                                 warnx("include line missing argument:\n%s",
1114                                     errline);
1115                                 continue;
1116                         }
1117
1118                         *parse = '\0';
1119
1120                         if (isglobstr(q)) {
1121                                 res = glob(q, GLOB_NOCHECK, NULL, &pglob);
1122                                 if (res != 0) {
1123                                         warn("cannot expand pattern (%d): %s",
1124                                             res, q);
1125                                         continue;
1126                                 }
1127
1128                                 if (verbose > 2)
1129                                         printf("\t+ Expanding pattern %s\n", q);
1130
1131                                 for (i = 0; i < pglob.gl_matchc; i++)
1132                                         add_to_queue(pglob.gl_pathv[i],
1133                                             inclist);
1134                                 globfree(&pglob);
1135                         } else
1136                                 add_to_queue(q, inclist);
1137                         continue;
1138                 }
1139
1140                 special = 0;
1141                 working = init_entry(q, NULL);
1142                 if (strcasecmp(DEFAULT_MARKER, q) == 0) {
1143                         special = 1;
1144                         if (*defconf_p != NULL) {
1145                                 warnx("Ignoring duplicate entry for %s!", q);
1146                                 free_entry(working);
1147                                 continue;
1148                         }
1149                         *defconf_p = working;
1150                 }
1151
1152                 q = parse = missing_field(sob(parse + 1), errline);
1153                 parse = son(parse);
1154                 if (!*parse)
1155                         errx(1, "malformed line (missing fields):\n%s",
1156                             errline);
1157                 *parse = '\0';
1158                 if ((group = strchr(q, ':')) != NULL ||
1159                     (group = strrchr(q, '.')) != NULL) {
1160                         *group++ = '\0';
1161                         if (*q) {
1162                                 if (!(isnumberstr(q))) {
1163                                         if ((pwd = getpwnam(q)) == NULL)
1164                                                 errx(1,
1165                                      "error in config file; unknown user:\n%s",
1166                                                     errline);
1167                                         working->uid = pwd->pw_uid;
1168                                 } else
1169                                         working->uid = atoi(q);
1170                         } else
1171                                 working->uid = (uid_t)-1;
1172
1173                         q = group;
1174                         if (*q) {
1175                                 if (!(isnumberstr(q))) {
1176                                         if ((grp = getgrnam(q)) == NULL)
1177                                                 errx(1,
1178                                     "error in config file; unknown group:\n%s",
1179                                                     errline);
1180                                         working->gid = grp->gr_gid;
1181                                 } else
1182                                         working->gid = atoi(q);
1183                         } else
1184                                 working->gid = (gid_t)-1;
1185
1186                         q = parse = missing_field(sob(parse + 1), errline);
1187                         parse = son(parse);
1188                         if (!*parse)
1189                                 errx(1, "malformed line (missing fields):\n%s",
1190                                     errline);
1191                         *parse = '\0';
1192                 } else {
1193                         working->uid = (uid_t)-1;
1194                         working->gid = (gid_t)-1;
1195                 }
1196
1197                 if (!sscanf(q, "%o", &working->permissions))
1198                         errx(1, "error in config file; bad permissions:\n%s",
1199                             errline);
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;
1205                 }
1206
1207                 q = parse = missing_field(sob(parse + 1), errline);
1208                 parse = son(parse);
1209                 if (!*parse)
1210                         errx(1, "malformed line (missing fields):\n%s",
1211                             errline);
1212                 *parse = '\0';
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",
1215                             errline);
1216
1217                 q = parse = missing_field(sob(parse + 1), errline);
1218                 parse = son(parse);
1219                 if (!*parse)
1220                         errx(1, "malformed line (missing fields):\n%s",
1221                             errline);
1222                 *parse = '\0';
1223                 if (isdigitch(*q))
1224                         working->trsize = atoi(q);
1225                 else if (strcmp(q, "*") == 0)
1226                         working->trsize = -1;
1227                 else {
1228                         warnx("Invalid value of '%s' for 'size' in line:\n%s",
1229                             q, errline);
1230                         working->trsize = -1;
1231                 }
1232
1233                 working->flags = 0;
1234                 working->compress = COMPRESS_NONE;
1235                 q = parse = missing_field(sob(parse + 1), errline);
1236                 parse = son(parse);
1237                 eol = !*parse;
1238                 *parse = '\0';
1239                 {
1240                         char *ep;
1241                         u_long ul;
1242
1243                         ul = strtoul(q, &ep, 10);
1244                         if (ep == q)
1245                                 working->hours = 0;
1246                         else if (*ep == '*')
1247                                 working->hours = -1;
1248                         else if (ul > INT_MAX)
1249                                 errx(1, "interval is too large:\n%s", errline);
1250                         else
1251                                 working->hours = ul;
1252
1253                         if (*ep == '\0' || strcmp(ep, "*") == 0)
1254                                 goto no_trimat;
1255                         if (*ep != '@' && *ep != '$')
1256                                 errx(1, "malformed interval/at:\n%s", errline);
1257
1258                         working->flags |= CE_TRIMAT;
1259                         working->trim_at = ptime_init(NULL);
1260                         ptm_opts = PTM_PARSE_ISO8601;
1261                         if (*ep == '$')
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);
1266                         if (res == -2)
1267                                 errx(1, "nonexistent time for 'at' value:\n%s",
1268                                     errline);
1269                         else if (res < 0)
1270                                 errx(1, "malformed 'at' value:\n%s", errline);
1271                 }
1272 no_trimat:
1273
1274                 if (eol)
1275                         q = NULL;
1276                 else {
1277                         q = parse = sob(parse + 1);     /* Optional field */
1278                         parse = son(parse);
1279                         if (!*parse)
1280                                 eol = 1;
1281                         *parse = '\0';
1282                 }
1283
1284                 for (; q && *q && !isspacech(*q); q++) {
1285                         switch (tolowerch(*q)) {
1286                         case 'b':
1287                                 working->flags |= CE_BINARY;
1288                                 break;
1289                         case 'c':
1290                                 working->flags |= CE_CREATE;
1291                                 break;
1292                         case 'd':
1293                                 working->flags |= CE_NODUMP;
1294                                 break;
1295                         case 'g':
1296                                 working->flags |= CE_GLOB;
1297                                 break;
1298                         case 'j':
1299                                 working->compress = COMPRESS_BZIP2;
1300                                 break;
1301                         case 'n':
1302                                 working->flags |= CE_NOSIGNAL;
1303                                 break;
1304                         case 'p':
1305                                 working->flags |= CE_PLAIN0;
1306                                 break;
1307                         case 'r':
1308                                 working->flags |= CE_PID2CMD;
1309                                 break;
1310                         case 't':
1311                                 working->flags |= CE_RFC5424;
1312                                 break;
1313                         case 'u':
1314                                 working->flags |= CE_SIGNALGROUP;
1315                                 break;
1316                         case 'w':
1317                                 /* Deprecated flag - keep for compatibility purposes */
1318                                 break;
1319                         case 'x':
1320                                 working->compress = COMPRESS_XZ;
1321                                 break;
1322                         case 'y':
1323                                 working->compress = COMPRESS_ZSTD;
1324                                 break;
1325                         case 'z':
1326                                 working->compress = COMPRESS_GZIP;
1327                                 break;
1328                         case '-':
1329                                 break;
1330                         case 'f':       /* Used by OpenBSD for "CE_FOLLOW" */
1331                         case 'm':       /* Used by OpenBSD for "CE_MONITOR" */
1332                         default:
1333                                 errx(1, "illegal flag in config file -- %c",
1334                                     *q);
1335                         }
1336                 }
1337
1338                 if (eol)
1339                         q = NULL;
1340                 else {
1341                         q = parse = sob(parse + 1);     /* Optional field */
1342                         parse = son(parse);
1343                         if (!*parse)
1344                                 eol = 1;
1345                         *parse = '\0';
1346                 }
1347
1348                 working->pid_cmd_file = NULL;
1349                 if (q && *q) {
1350                         if (*q == '/')
1351                                 working->pid_cmd_file = strdup(q);
1352                         else if (isalnum(*q))
1353                                 goto got_sig;
1354                         else {
1355                                 errx(1,
1356                         "illegal pid file or signal in config file:\n%s",
1357                                     errline);
1358                         }
1359                 }
1360                 if (eol)
1361                         q = NULL;
1362                 else {
1363                         q = parse = sob(parse + 1);     /* Optional field */
1364                         parse = son(parse);
1365                         *parse = '\0';
1366                 }
1367
1368                 working->sig = SIGHUP;
1369                 if (q && *q) {
1370 got_sig:
1371                         working->sig = parse_signal(q);
1372                         if (working->sig < 1 || working->sig >= sys_nsig) {
1373                                 errx(1,
1374                                     "illegal signal in config file:\n%s",
1375                                     errline);
1376                         }
1377                 }
1378
1379                 /*
1380                  * Finish figuring out what pid-file to use (if any) in
1381                  * later processing if this logfile needs to be rotated.
1382                  */
1383                 if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) {
1384                         /*
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.
1388                          */
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;
1394                         }
1395                 } else if (working->pid_cmd_file == NULL) {
1396                         /*
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
1402                          * are root.
1403                          */
1404                         if (working->flags & CE_SIGNALGROUP) {
1405                                 warnx("Ignoring flag 'U' in line:\n%s",
1406                                     errline);
1407                                 working->flags &= ~CE_SIGNALGROUP;
1408                         }
1409                         if (needroot)
1410                                 working->pid_cmd_file = strdup(path_syslogpid);
1411                 }
1412
1413                 /*
1414                  * Add this entry to the appropriate list of entries, unless
1415                  * it was some kind of special entry (eg: <default>).
1416                  */
1417                 if (special) {
1418                         ;                       /* Do not add to any list */
1419                 } else if (working->flags & CE_GLOB) {
1420                         STAILQ_INSERT_TAIL(glob_p, working, cf_nextp);
1421                 } else {
1422                         STAILQ_INSERT_TAIL(work_p, working, cf_nextp);
1423                 }
1424         }
1425         if (errline != NULL)
1426                 free(errline);
1427 }
1428
1429 static char *
1430 missing_field(char *p, char *errline)
1431 {
1432
1433         if (!p || !*p)
1434                 errx(1, "missing field in config file:\n%s", errline);
1435         return (p);
1436 }
1437
1438 /*
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.
1442  *
1443  * Support function for qsort() in delete_oldest_timelog().
1444  */
1445 static int
1446 oldlog_entry_compare(const void *a, const void *b)
1447 {
1448         const struct oldlog_entry *ola = a, *olb = b;
1449
1450         if (ola->t > olb->t)
1451                 return (-1);
1452         else if (ola->t < olb->t)
1453                 return (1);
1454         else
1455                 return (0);
1456 }
1457
1458 /*
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.
1462  */
1463 static int
1464 validate_old_timelog(int fd, const struct dirent *dp, const char *logfname,
1465     struct tm *tm)
1466 {
1467         struct stat sb;
1468         size_t logfname_len;
1469         char *s;
1470         int c;
1471
1472         logfname_len = strlen(logfname);
1473
1474         if (dp->d_type != DT_REG) {
1475                 /*
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.
1479                  */
1480                 if (dp->d_type != DT_UNKNOWN ||
1481                     fstatat(fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) != 0 ||
1482                     !S_ISREG(sb.st_mode))
1483                         return (0);
1484         }
1485         /* Ignore everything but files with our logfile prefix. */
1486         if (strncmp(dp->d_name, logfname, logfname_len) != 0)
1487                 return (0);
1488         /* Ignore the actual non-rotated logfile. */
1489         if (dp->d_namlen == logfname_len)
1490                 return (0);
1491
1492         /*
1493          * Make sure we created have found a logfile, so the
1494          * postfix is valid, IE format is: '.<time>(.[bgx]z)?'.
1495          */
1496         if (dp->d_name[logfname_len] != '.') {
1497                 if (verbose)
1498                         printf("Ignoring %s which has unexpected "
1499                             "extension '%s'\n", dp->d_name,
1500                             &dp->d_name[logfname_len]);
1501                 return (0);
1502         }
1503         memset(tm, 0, sizeof(*tm));
1504         if ((s = strptime(&dp->d_name[logfname_len + 1],
1505             timefnamefmt, tm)) == NULL) {
1506                 /*
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
1510                  * logfiles.
1511                  */
1512                 if (verbose)
1513                         printf("Ignoring %s which does not "
1514                             "match time format\n", dp->d_name);
1515                 return (0);
1516         }
1517
1518         for (c = 0; c < COMPRESS_TYPES; c++)
1519                 if (strcmp(s, compress_type[c].suffix) == 0)
1520                         /* We're done. */
1521                         return (1);
1522
1523         if (verbose)
1524                 printf("Ignoring %s which has unexpected extension '%s'\n",
1525                     dp->d_name, s);
1526
1527         return (0);
1528 }
1529
1530 /*
1531  * Delete the oldest logfiles, when using time based filenames.
1532  */
1533 static void
1534 delete_oldest_timelog(const struct conf_entry *ent, const char *archive_dir)
1535 {
1536         char *basebuf, *dirbuf, errbuf[80];
1537         const char *base, *dir;
1538         int dir_fd, i, logcnt, max_logcnt;
1539         struct oldlog_entry *oldlogs;
1540         struct dirent *dp;
1541         struct tm tm;
1542         DIR *dirp;
1543
1544         oldlogs = malloc(MAX_OLDLOGS * sizeof(struct oldlog_entry));
1545         max_logcnt = MAX_OLDLOGS;
1546         logcnt = 0;
1547
1548         if (archive_dir != NULL && archive_dir[0] != '\0') {
1549                 dirbuf = NULL;
1550                 dir = archive_dir;
1551         } else {
1552                 if ((dirbuf = strdup(ent->log)) == NULL)
1553                         err(1, "strdup()");
1554                 dir = dirname(dirbuf);
1555         }
1556
1557         if ((basebuf = strdup(ent->log)) == NULL)
1558                 err(1, "strdup()");
1559         base = basename(basebuf);
1560         if (strcmp(base, "/") == 0)
1561                 errx(1, "Invalid log filename - became '/'");
1562
1563         if (verbose > 2)
1564                 printf("Searching for old logs in %s\n", dir);
1565
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)
1572                         continue;
1573
1574                 /*
1575                  * We should now have old an old rotated logfile, so
1576                  * add it to the 'list'.
1577                  */
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)
1581                         err(1, "strdup()");
1582                 logcnt++;
1583
1584                 /*
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...
1588                  */
1589                 if (logcnt >= max_logcnt) {
1590                         max_logcnt *= 4;
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()");
1598                 }
1599         }
1600
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()");
1607
1608                 /*
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.
1612                  */
1613                 qsort(oldlogs, logcnt, sizeof(struct oldlog_entry),
1614                     oldlog_entry_compare);
1615                 for (i = ent->numlogs - 1; i < logcnt; i++) {
1616                         if (noaction)
1617                                 printf("\trm -f %s/%s\n", dir,
1618                                     oldlogs[i].fname);
1619                         else if (unlinkat(dir_fd, oldlogs[i].fname, 0) != 0) {
1620                                 snprintf(errbuf, sizeof(errbuf),
1621                                     "Could not delete old logfile '%s'",
1622                                     oldlogs[i].fname);
1623                                 perror(errbuf);
1624                         }
1625                 }
1626         } else if (verbose > 1)
1627                 printf("No old logs to delete for logfile %s\n", ent->log);
1628
1629         /* Third, cleanup */
1630         closedir(dirp);
1631         for (i = 0; i < logcnt; i++) {
1632                 assert(oldlogs[i].fname != NULL);
1633                 free(oldlogs[i].fname);
1634         }
1635         free(oldlogs);
1636         free(dirbuf);
1637         free(basebuf);
1638 }
1639
1640 /*
1641  * Generate a log filename, when using classic filenames.
1642  */
1643 static void
1644 gen_classiclog_fname(char *fname, size_t fname_sz, const char *archive_dir,
1645     const char *namepart, int numlogs_c)
1646 {
1647
1648         if (archive_dir[0] != '\0')
1649                 (void) snprintf(fname, fname_sz, "%s/%s.%d", archive_dir,
1650                     namepart, numlogs_c);
1651         else
1652                 (void) snprintf(fname, fname_sz, "%s.%d", namepart, numlogs_c);
1653 }
1654
1655 /*
1656  * Delete a rotated logfile, when using classic filenames.
1657  */
1658 static void
1659 delete_classiclog(const char *archive_dir, const char *namepart, int numlog_c)
1660 {
1661         char file1[MAXPATHLEN], zfile1[MAXPATHLEN];
1662         int c;
1663
1664         gen_classiclog_fname(file1, sizeof(file1), archive_dir, namepart,
1665             numlog_c);
1666
1667         for (c = 0; c < COMPRESS_TYPES; c++) {
1668                 (void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1669                     compress_type[c].suffix);
1670                 if (noaction)
1671                         printf("\trm -f %s\n", zfile1);
1672                 else
1673                         (void) unlink(zfile1);
1674         }
1675 }
1676
1677 /*
1678  * Only add to the queue if the file hasn't already been added. This is
1679  * done to prevent circular include loops.
1680  */
1681 static void
1682 add_to_queue(const char *fname, struct ilist *inclist)
1683 {
1684         struct include_entry *inc;
1685
1686         STAILQ_FOREACH(inc, inclist, inc_nextp) {
1687                 if (strcmp(fname, inc->file) == 0) {
1688                         warnx("duplicate include detected: %s", fname);
1689                         return;
1690                 }
1691         }
1692
1693         inc = malloc(sizeof(struct include_entry));
1694         if (inc == NULL)
1695                 err(1, "malloc of inc");
1696         inc->file = strdup(fname);
1697
1698         if (verbose > 2)
1699                 printf("\t+ Adding %s to the processing queue.\n", fname);
1700
1701         STAILQ_INSERT_TAIL(inclist, inc, inc_nextp);
1702 }
1703
1704 /*
1705  * Search for logfile and return its compression suffix (if supported)
1706  * The suffix detection is first-match in the order of compress_types
1707  *
1708  * Note: if logfile without suffix exists (uncompressed, COMPRESS_NONE)
1709  * a zero-length string is returned
1710  */
1711 static const char *
1712 get_logfile_suffix(const char *logfile)
1713 {
1714         struct stat st;
1715         char zfile[MAXPATHLEN];
1716         int c;
1717
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);
1723         }
1724         return (NULL);
1725 }
1726
1727 static fk_entry
1728 do_rotate(const struct conf_entry *ent)
1729 {
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;
1738         struct stat st;
1739         struct tm tm;
1740         time_t now;
1741
1742         flags = ent->flags;
1743         free_or_keep = FREE_ENT;
1744
1745         if (archtodir) {
1746                 char *p;
1747
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)
1755                                 dirpart[0] = '\0';
1756                         else
1757                                 *(p + 1) = '\0';
1758                         strlcat(dirpart, archdirname, sizeof(dirpart));
1759                 }
1760
1761                 /* check if archive directory exists, if not, create it */
1762                 if (lstat(dirpart, &st))
1763                         createdir(ent, dirpart);
1764
1765                 /* get filename part of logfile */
1766                 if ((p = strrchr(ent->log, '/')) == NULL)
1767                         strlcpy(namepart, ent->log, sizeof(namepart));
1768                 else
1769                         strlcpy(namepart, p + 1, sizeof(namepart));
1770         } else {
1771                 /*
1772                  * Tell utility functions we are not using an archive
1773                  * dir.
1774                  */
1775                 dirpart[0] = '\0';
1776                 strlcpy(namepart, ent->log, sizeof(namepart));
1777         }
1778
1779         /* Delete old logs */
1780         if (timefnamefmt != NULL)
1781                 delete_oldest_timelog(ent, dirpart);
1782         else {
1783                 /*
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.
1787                  */
1788                 delete_classiclog(dirpart, namepart, ent->numlogs);
1789
1790                 if (ent->numlogs > 0)
1791                         delete_classiclog(dirpart, namepart, ent->numlogs - 1);
1792
1793         }
1794
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));
1800
1801                 strftime(datetimestr, sizeof(datetimestr), timefnamefmt, &tm);
1802                 if (archtodir)
1803                         (void) snprintf(file1, sizeof(file1), "%s/%s.%s",
1804                             dirpart, namepart, datetimestr);
1805                 else
1806                         (void) snprintf(file1, sizeof(file1), "%s.%s",
1807                             ent->log, datetimestr);
1808
1809                 /* Don't run the code to move down logs */
1810                 numlogs_c = -1;
1811         } else {
1812                 gen_classiclog_fname(file1, sizeof(file1), dirpart, namepart,
1813                     ent->numlogs - 1);
1814                 numlogs_c = ent->numlogs - 2;           /* copy for countdown */
1815         }
1816
1817         /* Move down log files */
1818         for (; numlogs_c >= 0; numlogs_c--) {
1819                 (void) strlcpy(file2, file1, sizeof(file2));
1820
1821                 gen_classiclog_fname(file1, sizeof(file1), dirpart, namepart,
1822                     numlogs_c);
1823
1824                 logfile_suffix = get_logfile_suffix(file1);
1825                 if (logfile_suffix == NULL)
1826                         continue;
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);
1831
1832                 if (noaction)
1833                         printf("\tmv %s %s\n", zfile1, zfile2);
1834                 else {
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;
1841
1842                                 memset(&zwork, 0, sizeof(zwork));
1843                                 zwork.zw_conf = ent;
1844                                 zwork.zw_fsize = sizefile(zfile2);
1845                                 strcpy(zwork.zw_fname, zfile2);
1846                                 do_zipwork(&zwork);
1847                         }
1848                 }
1849         }
1850
1851         if (ent->numlogs > 0) {
1852                 if (noaction) {
1853                         /*
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...
1858                          */
1859                         if (archtodir)
1860                                 printf("\tcp %s %s\n", ent->log, file1);
1861                         else
1862                                 printf("\tln %s %s\n", ent->log, file1);
1863                         printf("\ttouch %s\t\t"
1864                             "# Update mtime for 'when'-interval processing\n",
1865                             file1);
1866                 } else {
1867                         if (!(flags & CE_BINARY)) {
1868                                 /* Report the trimming to the old log */
1869                                 log_trim(ent->log, ent);
1870                         }
1871                         savelog(ent->log, file1);
1872                         /*
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.
1876                          */
1877                         utimes(file1, NULL);
1878                 }
1879                 change_attrs(file1, ent);
1880         }
1881
1882         /* Create the new log file and move it into place */
1883         if (noaction)
1884                 printf("Start new log...\n");
1885         createlog(ent);
1886
1887         /*
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.
1892          */
1893         swork = NULL;
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) {
1899                         /*
1900                          * The zipwork_entry will include a pointer to this
1901                          * conf_entry, so the conf_entry should not be freed.
1902                          */
1903                         free_or_keep = KEEP_ENT;
1904                         save_zipwork(ent, swork, ent->fsize, file1);
1905                 }
1906         }
1907
1908         return (free_or_keep);
1909 }
1910
1911 static void
1912 do_sigwork(struct sigwork_entry *swork)
1913 {
1914         struct sigwork_entry *nextsig;
1915         int kres, secs;
1916         char *tmp;
1917
1918         if (swork->sw_runcmd == 0 && (!(swork->sw_pidok) || swork->sw_pid == 0))
1919                 return;                 /* no work to do... */
1920
1921         /*
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).
1930          */
1931         if (nosignal) {
1932                 if (!rotatereq)
1933                         swork->sw_pidok = -1;
1934                 return;
1935         }
1936
1937         /*
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.
1941          */
1942         secs = 0;
1943         nextsig = SLIST_NEXT(swork, sw_nextp);
1944         if (nextsig != NULL) {
1945                 if (swork->sw_pid == nextsig->sw_pid)
1946                         secs = 10;
1947                 else
1948                         secs = 1;
1949         }
1950
1951         if (noaction) {
1952                 if (swork->sw_runcmd)
1953                         printf("\tsh -c '%s %d'\n", swork->sw_fname,
1954                             swork->sw_signum);
1955                 else {
1956                         printf("\tkill -%d %d \t\t# %s\n", swork->sw_signum,
1957                             (int)swork->sw_pid, swork->sw_fname);
1958                         if (secs > 0)
1959                                 printf("\tsleep %d\n", secs);
1960                 }
1961                 return;
1962         }
1963
1964         if (swork->sw_runcmd) {
1965                 asprintf(&tmp, "%s %d", swork->sw_fname, swork->sw_signum);
1966                 if (tmp == NULL) {
1967                         warn("can't allocate memory to run %s",
1968                             swork->sw_fname);
1969                         return;
1970                 }
1971                 if (verbose)
1972                         printf("Run command: %s\n", tmp);
1973                 kres = system(tmp);
1974                 if (kres) {
1975                         warnx("%s: returned non-zero exit code: %d",
1976                             tmp, kres);
1977                 }
1978                 free(tmp);
1979                 return;
1980         }
1981
1982         kres = kill(swork->sw_pid, swork->sw_signum);
1983         if (kres != 0) {
1984                 /*
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).
1990                  */
1991                 if (errno != ESRCH)
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);
1995         } else {
1996                 if (verbose)
1997                         printf("Notified %s pid %d = %s\n", swork->sw_pidtype,
1998                             (int)swork->sw_pid, swork->sw_fname);
1999                 if (secs > 0) {
2000                         if (verbose)
2001                                 printf("Pause %d second(s) between signals\n",
2002                                     secs);
2003                         sleep(secs);
2004                 }
2005         }
2006 }
2007
2008 static void
2009 do_zipwork(struct zipwork_entry *zwork)
2010 {
2011         const struct compress_types *ct;
2012         struct sbuf *command;
2013         pid_t pidzip, wpid;
2014         int c, errsav, fcount, zstatus;
2015         const char **args, *pgm_name, *pgm_path;
2016         char *zresult;
2017
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);
2022
2023         if (zwork->zw_swork != NULL && zwork->zw_swork->sw_runcmd == 0 &&
2024             zwork->zw_swork->sw_pidok <= 0) {
2025                 warnx(
2026                     "log %s not compressed because daemon(s) not notified",
2027                     zwork->zw_fname);
2028                 change_attrs(zwork->zw_fname, zwork->zw_conf);
2029                 return;
2030         }
2031
2032         ct = &compress_type[zwork->zw_conf->compress];
2033
2034         /*
2035          * execv will be called with the array [ program, flags ... ,
2036          * filename, NULL ] so allocate nflags+3 elements for the array.
2037          */
2038         args = calloc(ct->nflags + 3, sizeof(*args));
2039         if (args == NULL)
2040                 err(1, "calloc");
2041
2042         pgm_path = ct->path;
2043         pgm_name = strrchr(pgm_path, '/');
2044         if (pgm_name == NULL)
2045                 pgm_name = pgm_path;
2046         else
2047                 pgm_name++;
2048
2049         /* Build the argument array. */
2050         args[0] = pgm_name;
2051         for (c = 0; c < ct->nflags; c++)
2052                 args[c + 1] = ct->flags[c];
2053         args[c + 1] = zwork->zw_fname;
2054
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]);
2062         }
2063         if (sbuf_finish(command) == -1)
2064                 err(1, "sbuf_finish");
2065
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");
2070
2071         if (verbose)
2072                 printf("Executing: %s\n", sbuf_data(command));
2073
2074         if (noaction) {
2075                 printf("\t%s %s\n", pgm_name, zwork->zw_fname);
2076                 change_attrs(zresult, zwork->zw_conf);
2077                 goto out;
2078         }
2079
2080         fcount = 1;
2081         pidzip = fork();
2082         while (pidzip < 0) {
2083                 /*
2084                  * The fork failed.  If the failure was due to a temporary
2085                  * problem, then wait a short time and try it again.
2086                  */
2087                 errsav = errno;
2088                 warn("fork() for `%s %s'", pgm_name, zwork->zw_fname);
2089                 if (errsav != EAGAIN || fcount > 5)
2090                         errx(1, "Exiting...");
2091                 sleep(fcount * 12);
2092                 fcount++;
2093                 pidzip = fork();
2094         }
2095         if (!pidzip) {
2096                 /* The child process executes the compression command */
2097                 execv(pgm_path, __DECONST(char *const*, args));
2098                 err(1, "execv(`%s')", sbuf_data(command));
2099         }
2100
2101         wpid = waitpid(pidzip, &zstatus, 0);
2102         if (wpid == -1) {
2103                 /* XXX - should this be a fatal error? */
2104                 warn("%s: waitpid(%d)", pgm_path, pidzip);
2105                 goto out;
2106         }
2107         if (!WIFEXITED(zstatus)) {
2108                 warnx("`%s' did not terminate normally", sbuf_data(command));
2109                 goto out;
2110         }
2111         if (WEXITSTATUS(zstatus)) {
2112                 warnx("`%s' terminated with a non-zero status (%d)",
2113                     sbuf_data(command), WEXITSTATUS(zstatus));
2114                 goto out;
2115         }
2116
2117         /* Compression was successful, set file attributes on the result. */
2118         change_attrs(zresult, zwork->zw_conf);
2119
2120 out:
2121         sbuf_delete(command);
2122         free(args);
2123         free(zresult);
2124 }
2125
2126 /*
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.
2131  */
2132 static struct sigwork_entry *
2133 save_sigwork(const struct conf_entry *ent)
2134 {
2135         struct sigwork_entry *sprev, *stmp;
2136         int ndiff;
2137         size_t tmpsiz;
2138
2139         sprev = NULL;
2140         ndiff = 1;
2141         SLIST_FOREACH(stmp, &swhead, sw_nextp) {
2142                 ndiff = strcmp(ent->pid_cmd_file, stmp->sw_fname);
2143                 if (ndiff > 0)
2144                         break;
2145                 if (ndiff == 0) {
2146                         if (ent->sig == stmp->sw_signum)
2147                                 break;
2148                         if (ent->sig > stmp->sw_signum) {
2149                                 ndiff = 1;
2150                                 break;
2151                         }
2152                 }
2153                 sprev = stmp;
2154         }
2155         if (stmp != NULL && ndiff == 0)
2156                 return (stmp);
2157
2158         tmpsiz = sizeof(struct sigwork_entry) + strlen(ent->pid_cmd_file) + 1;
2159         stmp = malloc(tmpsiz);
2160
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) {
2164                 stmp->sw_pid = -1;
2165                 stmp->sw_pidok = 0;
2166                 stmp->sw_runcmd = 1;
2167         } else {
2168                 set_swpid(stmp, ent);
2169         }
2170         stmp->sw_signum = ent->sig;
2171         strcpy(stmp->sw_fname, ent->pid_cmd_file);
2172         if (sprev == NULL)
2173                 SLIST_INSERT_HEAD(&swhead, stmp, sw_nextp);
2174         else
2175                 SLIST_INSERT_AFTER(sprev, stmp, sw_nextp);
2176         return (stmp);
2177 }
2178
2179 /*
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.
2186  */
2187 static struct zipwork_entry *
2188 save_zipwork(const struct conf_entry *ent, const struct sigwork_entry *swork,
2189     int zsize, const char *zipfname)
2190 {
2191         struct zipwork_entry *zprev, *ztmp;
2192         int ndiff;
2193         size_t tmpsiz;
2194
2195         /* Compute the size if the caller did not know it. */
2196         if (zsize < 0)
2197                 zsize = sizefile(zipfname);
2198
2199         zprev = NULL;
2200         ndiff = 1;
2201         SLIST_FOREACH(ztmp, &zwhead, zw_nextp) {
2202                 ndiff = strcmp(zipfname, ztmp->zw_fname);
2203                 if (ndiff == 0)
2204                         break;
2205                 if (zsize > ztmp->zw_fsize)
2206                         zprev = ztmp;
2207         }
2208         if (ztmp != NULL && ndiff == 0)
2209                 return (ztmp);
2210
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);
2217         if (zprev == NULL)
2218                 SLIST_INSERT_HEAD(&zwhead, ztmp, zw_nextp);
2219         else
2220                 SLIST_INSERT_AFTER(zprev, ztmp, zw_nextp);
2221         return (ztmp);
2222 }
2223
2224 /* Send a signal to the pid specified by pidfile */
2225 static void
2226 set_swpid(struct sigwork_entry *swork, const struct conf_entry *ent)
2227 {
2228         FILE *f;
2229         long minok, maxok, rval;
2230         char *endp, *linep, line[BUFSIZ];
2231
2232         minok = MIN_PID;
2233         maxok = MAX_PID;
2234         swork->sw_pidok = 0;
2235         swork->sw_pid = 0;
2236         swork->sw_pidtype = "daemon";
2237         if (ent->flags & CE_SIGNALGROUP) {
2238                 /*
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.
2242                  */
2243                 minok = -MAX_PID;
2244                 maxok = -MIN_PID;
2245                 swork->sw_pidtype = "process-group";
2246         }
2247
2248         f = fopen(ent->pid_cmd_file, "r");
2249         if (f == NULL) {
2250                 if (errno == ENOENT && enforcepid == 0) {
2251                         /*
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.
2257                          */
2258                         swork->sw_pidok = 1;
2259                         warnx("pid file doesn't exist: %s", ent->pid_cmd_file);
2260                 } else
2261                         warn("can't open pid file: %s", ent->pid_cmd_file);
2262                 return;
2263         }
2264
2265         if (fgets(line, BUFSIZ, f) == NULL) {
2266                 /*
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.
2271                  */
2272                 if (feof(f) && enforcepid == 0) {
2273                         swork->sw_pidok = 1;
2274                         warnx("pid/cmd file is empty: %s", ent->pid_cmd_file);
2275                 } else
2276                         warn("can't read from pid file: %s", ent->pid_cmd_file);
2277                 (void)fclose(f);
2278                 return;
2279         }
2280         (void)fclose(f);
2281
2282         errno = 0;
2283         linep = line;
2284         while (*linep == ' ')
2285                 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",
2289                     ent->pid_cmd_file);
2290         } else if (rval < minok || rval > maxok) {
2291                 warnx("bad value '%ld' for process number in %s",
2292                     rval, ent->pid_cmd_file);
2293                 if (verbose)
2294                         warnx("\t(expecting value between %ld and %ld)",
2295                             minok, maxok);
2296         } else {
2297                 swork->sw_pidok = 1;
2298                 swork->sw_pid = rval;
2299         }
2300
2301         return;
2302 }
2303
2304 /* Log the fact that the logs were turned over */
2305 static int
2306 log_trim(const char *logname, const struct conf_entry *log_ent)
2307 {
2308         FILE *f;
2309         const char *xtra;
2310
2311         if ((f = fopen(logname, "a")) == NULL)
2312                 return (-1);
2313         xtra = "";
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);
2327                 } else {
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);
2332                 }
2333         } else {
2334                 if (log_ent->firstcreate)
2335                         fprintf(f,
2336                             "%s %.*s newsyslog[%d]: logfile first created%s\n",
2337                             daytime, (int)hostname_shortlen, hostname, getpid(),
2338                             xtra);
2339                 else if (log_ent->r_reason != NULL)
2340                         fprintf(f,
2341                             "%s %.*s newsyslog[%d]: logfile turned over%s%s\n",
2342                             daytime, (int)hostname_shortlen, hostname, getpid(),
2343                             log_ent->r_reason, xtra);
2344                 else
2345                         fprintf(f,
2346                             "%s %.*s newsyslog[%d]: logfile turned over%s\n",
2347                             daytime, (int)hostname_shortlen, hostname, getpid(),
2348                             xtra);
2349         }
2350         if (fclose(f) == EOF)
2351                 err(1, "log_trim: fclose");
2352         return (0);
2353 }
2354
2355 /* Return size in kilobytes of a file */
2356 static int
2357 sizefile(const char *file)
2358 {
2359         struct stat sb;
2360
2361         if (stat(file, &sb) < 0)
2362                 return (-1);
2363         return (kbytes(sb.st_size));
2364 }
2365
2366 /*
2367  * Return the mtime of the most recent archive of the logfile, using timestamp
2368  * based filenames.
2369  */
2370 static time_t
2371 mtime_old_timelog(const char *file)
2372 {
2373         struct stat sb;
2374         struct tm tm;
2375         int dir_fd;
2376         time_t t;
2377         struct dirent *dp;
2378         DIR *dirp;
2379         char *logfname, *logfnamebuf, *dir, *dirbuf;
2380
2381         t = -1;
2382
2383         if ((dirbuf = strdup(file)) == NULL) {
2384                 warn("strdup() of '%s'", file);
2385                 return (t);
2386         }
2387         dir = dirname(dirbuf);
2388         if ((logfnamebuf = strdup(file)) == NULL) {
2389                 warn("strdup() of '%s'", file);
2390                 free(dirbuf);
2391                 return (t);
2392         }
2393         logfname = basename(logfnamebuf);
2394         if (logfname[0] == '/') {
2395                 warnx("Invalid log filename '%s'", logfname);
2396                 goto out;
2397         }
2398
2399         if ((dirp = opendir(dir)) == NULL) {
2400                 warn("Cannot open log directory '%s'", dir);
2401                 goto out;
2402         }
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)
2407                         continue;
2408
2409                 if (fstatat(dir_fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
2410                         warn("Cannot stat '%s'", file);
2411                         continue;
2412                 }
2413                 if (t < sb.st_mtime)
2414                         t = sb.st_mtime;
2415         }
2416         closedir(dirp);
2417
2418 out:
2419         free(dirbuf);
2420         free(logfnamebuf);
2421         return (t);
2422 }
2423
2424 /* Return the age in hours of the most recent archive of the logfile. */
2425 static int
2426 age_old_log(const char *file)
2427 {
2428         struct stat sb;
2429         const char *logfile_suffix;
2430         static unsigned int suffix_maxlen = 0;
2431         char *tmp;
2432         size_t tmpsiz;
2433         time_t mtime;
2434         int c;
2435
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));
2440         }
2441
2442         tmpsiz = MAXPATHLEN + sizeof(".0") + suffix_maxlen + 1;
2443         tmp = alloca(tmpsiz);
2444
2445         if (archtodir) {
2446                 char *p;
2447
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)
2455                                 tmp[0] = '\0';
2456                         else
2457                                 *(p + 1) = '\0';
2458                         strlcat(tmp, archdirname, tmpsiz);
2459                 }
2460
2461                 strlcat(tmp, "/", tmpsiz);
2462
2463                 /* get filename part of logfile */
2464                 if ((p = strrchr(file, '/')) == NULL)
2465                         strlcat(tmp, file, tmpsiz);
2466                 else
2467                         strlcat(tmp, p + 1, tmpsiz);
2468         } else {
2469                 (void) strlcpy(tmp, file, tmpsiz);
2470         }
2471
2472         if (timefnamefmt != NULL) {
2473                 mtime = mtime_old_timelog(tmp);
2474                 if (mtime == -1)
2475                         return (-1);
2476         } else {
2477                 strlcat(tmp, ".0", tmpsiz);
2478                 logfile_suffix = get_logfile_suffix(tmp);
2479                 if (logfile_suffix == NULL)
2480                         return (-1);
2481                 (void) strlcat(tmp, logfile_suffix, tmpsiz);
2482                 if (stat(tmp, &sb) < 0)
2483                         return (-1);
2484                 mtime = sb.st_mtime;
2485         }
2486
2487         return ((int)(ptimeget_secs(timenow) - mtime + 1800) / 3600);
2488 }
2489
2490 /* Skip Over Blanks */
2491 static char *
2492 sob(char *p)
2493 {
2494         while (p && *p && isspace(*p))
2495                 p++;
2496         return (p);
2497 }
2498
2499 /* Skip Over Non-Blanks */
2500 static char *
2501 son(char *p)
2502 {
2503         while (p && *p && !isspace(*p))
2504                 p++;
2505         return (p);
2506 }
2507
2508 /* Check if string is actually a number */
2509 static int
2510 isnumberstr(const char *string)
2511 {
2512         while (*string) {
2513                 if (!isdigitch(*string++))
2514                         return (0);
2515         }
2516         return (1);
2517 }
2518
2519 /* Check if string contains a glob */
2520 static int
2521 isglobstr(const char *string)
2522 {
2523         char chr;
2524
2525         while ((chr = *string++)) {
2526                 if (chr == '*' || chr == '?' || chr == '[')
2527                         return (1);
2528         }
2529         return (0);
2530 }
2531
2532 /*
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.
2537  */
2538 static void
2539 savelog(char *from, char *to)
2540 {
2541         FILE *src, *dst;
2542         int c, res;
2543
2544         res = link(from, to);
2545         if (res == 0)
2546                 return;
2547
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);
2552
2553         while ((c = getc(src)) != EOF) {
2554                 if ((putc(c, dst)) == EOF)
2555                         err(1, "error writing to %s", to);
2556         }
2557
2558         if (ferror(src))
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);
2564 }
2565
2566 /* create one or more directory components of a path */
2567 static void
2568 createdir(const struct conf_entry *ent, char *dirpart)
2569 {
2570         int res;
2571         char *s, *d;
2572         char mkdirpath[MAXPATHLEN];
2573         struct stat st;
2574
2575         s = dirpart;
2576         d = mkdirpath;
2577
2578         for (;;) {
2579                 *d++ = *s++;
2580                 if (*s != '/' && *s != '\0')
2581                         continue;
2582                 *d = '\0';
2583                 res = lstat(mkdirpath, &st);
2584                 if (res != 0) {
2585                         if (noaction) {
2586                                 printf("\tmkdir %s\n", mkdirpath);
2587                         } else {
2588                                 res = mkdir(mkdirpath, 0755);
2589                                 if (res != 0)
2590                                         err(1, "Error on mkdir(\"%s\") for -a",
2591                                             mkdirpath);
2592                         }
2593                 }
2594                 if (*s == '\0')
2595                         break;
2596         }
2597         if (verbose) {
2598                 if (ent->firstcreate)
2599                         printf("Created directory '%s' for new %s\n",
2600                             dirpart, ent->log);
2601                 else
2602                         printf("Created directory '%s' for -a\n", dirpart);
2603         }
2604 }
2605
2606 /*
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.
2611  */
2612 void
2613 createlog(const struct conf_entry *ent)
2614 {
2615         int fd, failed;
2616         struct stat st;
2617         char *realfile, *slash, tempfile[MAXPATHLEN];
2618
2619         fd = -1;
2620         realfile = ent->log;
2621
2622         /*
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.
2626          */
2627         if (ent->firstcreate) {
2628                 strlcpy(tempfile, realfile, sizeof(tempfile));
2629                 slash = strrchr(tempfile, '/');
2630                 if (slash != NULL) {
2631                         *slash = '\0';
2632                         failed = stat(tempfile, &st);
2633                         if (failed && errno != ENOENT)
2634                                 err(1, "Error on stat(%s)", tempfile);
2635                         if (failed)
2636                                 createdir(ent, tempfile);
2637                         else if (!S_ISDIR(st.st_mode))
2638                                 errx(1, "%s exists but is not a directory",
2639                                     tempfile);
2640                 }
2641         }
2642
2643         /*
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>'.
2648          */
2649         strlcpy(tempfile, realfile, sizeof(tempfile));
2650         strlcat(tempfile, ".zXXXXXX", sizeof(tempfile));
2651         if (noaction)
2652                 printf("\tmktemp %s\n", tempfile);
2653         else {
2654                 fd = mkstemp(tempfile);
2655                 if (fd < 0)
2656                         err(1, "can't mkstemp logfile %s", tempfile);
2657
2658                 /*
2659                  * Add status message to what will become the new log file.
2660                  */
2661                 if (!(ent->flags & CE_BINARY)) {
2662                         if (log_trim(tempfile, ent))
2663                                 err(1, "can't add status message to log");
2664                 }
2665         }
2666
2667         /* Change the owner/group, if we are supposed to */
2668         if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2669                 if (noaction)
2670                         printf("\tchown %u:%u %s\n", ent->uid, ent->gid,
2671                             tempfile);
2672                 else {
2673                         failed = fchown(fd, ent->uid, ent->gid);
2674                         if (failed)
2675                                 err(1, "can't fchown temp file %s", tempfile);
2676                 }
2677         }
2678
2679         /* Turn on NODUMP if it was requested in the config-file. */
2680         if (ent->flags & CE_NODUMP) {
2681                 if (noaction)
2682                         printf("\tchflags nodump %s\n", tempfile);
2683                 else {
2684                         failed = fchflags(fd, UF_NODUMP);
2685                         if (failed) {
2686                                 warn("log_trim: fchflags(NODUMP)");
2687                         }
2688                 }
2689         }
2690
2691         /*
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
2697          * did not exist.
2698          * XXX - ? It may be that for some error conditions, we could
2699          *      retry by first removing the realfile and then renaming.
2700          */
2701         if (noaction) {
2702                 printf("\tchmod %o %s\n", ent->permissions, tempfile);
2703                 printf("\tmv %s %s\n", tempfile, realfile);
2704         } else {
2705                 failed = fchmod(fd, ent->permissions);
2706                 if (failed)
2707                         err(1, "can't fchmod temp file '%s'", tempfile);
2708                 failed = rename(tempfile, realfile);
2709                 if (failed)
2710                         err(1, "can't mv %s to %s", tempfile, realfile);
2711         }
2712
2713         if (fd >= 0)
2714                 close(fd);
2715 }
2716
2717 /*
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.
2722  */
2723 static void
2724 change_attrs(const char *fname, const struct conf_entry *ent)
2725 {
2726         int failed;
2727
2728         if (noaction) {
2729                 printf("\tchmod %o %s\n", ent->permissions, fname);
2730
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);
2734
2735                 if (ent->flags & CE_NODUMP)
2736                         printf("\tchflags nodump %s\n", fname);
2737                 return;
2738         }
2739
2740         failed = chmod(fname, ent->permissions);
2741         if (failed) {
2742                 if (errno != EPERM)
2743                         err(1, "chmod(%s) in change_attrs", fname);
2744                 warn("change_attrs couldn't chmod(%s)", fname);
2745         }
2746
2747         if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2748                 failed = chown(fname, ent->uid, ent->gid);
2749                 if (failed)
2750                         warn("can't chown %s", fname);
2751         }
2752
2753         if (ent->flags & CE_NODUMP) {
2754                 failed = chflags(fname, UF_NODUMP);
2755                 if (failed)
2756                         warn("can't chflags %s NODUMP", fname);
2757         }
2758 }
2759
2760 /*
2761  * Parse a signal number or signal name. Returns the signal number parsed or -1
2762  * on failure.
2763  */
2764 static int
2765 parse_signal(const char *str)
2766 {
2767         int sig, i;
2768         const char *errstr;
2769
2770         sig = strtonum(str, 1, sys_nsig - 1, &errstr);
2771
2772         if (errstr == NULL)
2773                 return (sig);
2774         if (strncasecmp(str, "SIG", 3) == 0)
2775                 str += 3;
2776
2777         for (i = 1; i < sys_nsig; i++) {
2778                 if (strcasecmp(str, sys_signame[i]) == 0)
2779                         return (i);
2780         }
2781
2782         return (-1);
2783 }