]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/newsyslog/newsyslog.c
Don't hard-code the number of compression utility arguments.
[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/stat.h>
64 #include <sys/wait.h>
65
66 #include <assert.h>
67 #include <ctype.h>
68 #include <err.h>
69 #include <errno.h>
70 #include <dirent.h>
71 #include <fcntl.h>
72 #include <fnmatch.h>
73 #include <glob.h>
74 #include <grp.h>
75 #include <paths.h>
76 #include <pwd.h>
77 #include <signal.h>
78 #include <stdio.h>
79 #include <libgen.h>
80 #include <stdlib.h>
81 #include <string.h>
82 #include <syslog.h>
83 #include <time.h>
84 #include <unistd.h>
85
86 #include "pathnames.h"
87 #include "extern.h"
88
89 /*
90  * Compression suffixes
91  */
92 #ifndef COMPRESS_SUFFIX_GZ
93 #define COMPRESS_SUFFIX_GZ      ".gz"
94 #endif
95
96 #ifndef COMPRESS_SUFFIX_BZ2
97 #define COMPRESS_SUFFIX_BZ2     ".bz2"
98 #endif
99
100 #ifndef COMPRESS_SUFFIX_XZ
101 #define COMPRESS_SUFFIX_XZ      ".xz"
102 #endif
103
104 #ifndef COMPRESS_SUFFIX_ZST
105 #define COMPRESS_SUFFIX_ZST     ".zst"
106 #endif
107
108 #define COMPRESS_SUFFIX_MAXLEN  MAX(MAX(MAX(sizeof(COMPRESS_SUFFIX_GZ),sizeof(COMPRESS_SUFFIX_BZ2)),sizeof(COMPRESS_SUFFIX_XZ)),sizeof(COMPRESS_SUFFIX_ZST))
109
110 /*
111  * Compression types
112  */
113 #define COMPRESS_TYPES  5       /* Number of supported compression types */
114
115 #define COMPRESS_NONE   0
116 #define COMPRESS_GZIP   1
117 #define COMPRESS_BZIP2  2
118 #define COMPRESS_XZ     3
119 #define COMPRESS_ZSTD   4
120
121 /*
122  * Bit-values for the 'flags' parsed from a config-file entry.
123  */
124 #define CE_BINARY       0x0008  /* Logfile is in binary, do not add status */
125                                 /*    messages to logfile(s) when rotating. */
126 #define CE_NOSIGNAL     0x0010  /* There is no process to signal when */
127                                 /*    trimming this file. */
128 #define CE_TRIMAT       0x0020  /* trim file at a specific time. */
129 #define CE_GLOB         0x0040  /* name of the log is file name pattern. */
130 #define CE_SIGNALGROUP  0x0080  /* Signal a process-group instead of a single */
131                                 /*    process when trimming this file. */
132 #define CE_CREATE       0x0100  /* Create the log file if it does not exist. */
133 #define CE_NODUMP       0x0200  /* Set 'nodump' on newly created log file. */
134 #define CE_PID2CMD      0x0400  /* Replace PID file with a shell command.*/
135 #define CE_PLAIN0       0x0800  /* Do not compress zero'th history file */
136
137 #define CE_RFC5424      0x0800  /* Use RFC5424 format rotation message */
138
139 #define MIN_PID         5       /* Don't touch pids lower than this */
140 #define MAX_PID         99999   /* was lower, see /usr/include/sys/proc.h */
141
142 #define kbytes(size)  (((size) + 1023) >> 10)
143
144 #define DEFAULT_MARKER  "<default>"
145 #define DEBUG_MARKER    "<debug>"
146 #define INCLUDE_MARKER  "<include>"
147 #define DEFAULT_TIMEFNAME_FMT   "%Y%m%dT%H%M%S"
148
149 #define MAX_OLDLOGS 65536       /* Default maximum number of old logfiles */
150
151 struct compress_types {
152         const char *flag;       /* Flag in configuration file */
153         const char *suffix;     /* Compression suffix */
154         const char *path;       /* Path to compression program */
155         char **args;            /* Compression program arguments */
156         int nargs;              /* Program argument count */
157 };
158
159 static char f_arg[] = "-f";
160 static char q_arg[] = "-q";
161 static char rm_arg[] = "--rm";
162 static char *gz_args[] = { NULL, f_arg, NULL, NULL };
163 #define bz2_args gz_args
164 #define xz_args gz_args
165 static char *zstd_args[] = { NULL, q_arg, rm_arg, NULL, NULL };
166
167 #define ARGS_NUM 5
168 static const struct compress_types compress_type[COMPRESS_TYPES] = {
169         { "", "", "", NULL, 0},
170         { "Z", COMPRESS_SUFFIX_GZ, _PATH_GZIP, gz_args, nitems(gz_args) },
171         { "J", COMPRESS_SUFFIX_BZ2, _PATH_BZIP2, bz2_args, nitems(bz2_args) },
172         { "X", COMPRESS_SUFFIX_XZ, _PATH_XZ, xz_args, nitems(xz_args) },
173         { "Y", COMPRESS_SUFFIX_ZST, _PATH_ZSTD, zstd_args, nitems(zstd_args) }
174 };
175
176 struct conf_entry {
177         STAILQ_ENTRY(conf_entry) cf_nextp;
178         char *log;              /* Name of the log */
179         char *pid_cmd_file;             /* PID or command file */
180         char *r_reason;         /* The reason this file is being rotated */
181         int firstcreate;        /* Creating log for the first time (-C). */
182         int rotate;             /* Non-zero if this file should be rotated */
183         int fsize;              /* size found for the log file */
184         uid_t uid;              /* Owner of log */
185         gid_t gid;              /* Group of log */
186         int numlogs;            /* Number of logs to keep */
187         int trsize;             /* Size cutoff to trigger trimming the log */
188         int hours;              /* Hours between log trimming */
189         struct ptime_data *trim_at;     /* Specific time to do trimming */
190         unsigned int permissions;       /* File permissions on the log */
191         int flags;              /* CE_BINARY */
192         int compress;           /* Compression */
193         int sig;                /* Signal to send */
194         int def_cfg;            /* Using the <default> rule for this file */
195 };
196
197 struct sigwork_entry {
198         SLIST_ENTRY(sigwork_entry) sw_nextp;
199         int      sw_signum;             /* the signal to send */
200         int      sw_pidok;              /* true if pid value is valid */
201         pid_t    sw_pid;                /* the process id from the PID file */
202         const char *sw_pidtype;         /* "daemon" or "process group" */
203         int      sw_runcmd;             /* run command or send PID to signal */
204         char     sw_fname[1];           /* file the PID was read from or shell cmd */
205 };
206
207 struct zipwork_entry {
208         SLIST_ENTRY(zipwork_entry) zw_nextp;
209         const struct conf_entry *zw_conf;       /* for chown/perm/flag info */
210         const struct sigwork_entry *zw_swork;   /* to know success of signal */
211         int      zw_fsize;              /* size of the file to compress */
212         char     zw_fname[1];           /* the file to compress */
213 };
214
215 struct include_entry {
216         STAILQ_ENTRY(include_entry) inc_nextp;
217         const char *file;       /* Name of file to process */
218 };
219
220 struct oldlog_entry {
221         char *fname;            /* Filename of the log file */
222         time_t t;               /* Parsed timestamp of the logfile */
223 };
224
225 typedef enum {
226         FREE_ENT, KEEP_ENT
227 }       fk_entry;
228
229 STAILQ_HEAD(cflist, conf_entry);
230 static SLIST_HEAD(swlisthead, sigwork_entry) swhead =
231     SLIST_HEAD_INITIALIZER(swhead);
232 static SLIST_HEAD(zwlisthead, zipwork_entry) zwhead =
233     SLIST_HEAD_INITIALIZER(zwhead);
234 STAILQ_HEAD(ilist, include_entry);
235
236 int dbg_at_times;               /* -D Show details of 'trim_at' code */
237
238 static int archtodir = 0;       /* Archive old logfiles to other directory */
239 static int createlogs;          /* Create (non-GLOB) logfiles which do not */
240                                 /*    already exist.  1=='for entries with */
241                                 /*    C flag', 2=='for all entries'. */
242 int verbose = 0;                /* Print out what's going on */
243 static int needroot = 1;        /* Root privs are necessary */
244 int noaction = 0;               /* Don't do anything, just show it */
245 static int norotate = 0;        /* Don't rotate */
246 static int nosignal;            /* Do not send any signals */
247 static int enforcepid = 0;      /* If PID file does not exist or empty, do nothing */
248 static int force = 0;           /* Force the trim no matter what */
249 static int rotatereq = 0;       /* -R = Always rotate the file(s) as given */
250                                 /*    on the command (this also requires   */
251                                 /*    that a list of files *are* given on  */
252                                 /*    the run command). */
253 static char *requestor;         /* The name given on a -R request */
254 static char *timefnamefmt = NULL;/* Use time based filenames instead of .0 */
255 static char *archdirname;       /* Directory path to old logfiles archive */
256 static char *destdir = NULL;    /* Directory to treat at root for logs */
257 static const char *conf;        /* Configuration file to use */
258
259 struct ptime_data *dbg_timenow; /* A "timenow" value set via -D option */
260 static struct ptime_data *timenow; /* The time to use for checking at-fields */
261
262 #define DAYTIME_LEN     16
263 static char daytime[DAYTIME_LEN];/* The current time in human readable form,
264                                   * used for rotation-tracking messages. */
265
266 /* Another buffer to hold the current time in RFC5424 format. Fractional
267  * seconds are allowed by the RFC, but are not included in the
268  * rotation-tracking messages written by newsyslog and so are not accounted for
269  * in the length below.
270  */
271 #define DAYTIME_RFC5424_LEN     sizeof("YYYY-MM-DDTHH:MM:SS+00:00")
272 static char daytime_rfc5424[DAYTIME_RFC5424_LEN];
273
274 static char hostname[MAXHOSTNAMELEN]; /* hostname */
275 static size_t hostname_shortlen;
276
277 static const char *path_syslogpid = _PATH_SYSLOGPID;
278
279 static struct cflist *get_worklist(char **files);
280 static void parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
281                     struct conf_entry *defconf_p, struct ilist *inclist);
282 static void add_to_queue(const char *fname, struct ilist *inclist);
283 static char *sob(char *p);
284 static char *son(char *p);
285 static int isnumberstr(const char *);
286 static int isglobstr(const char *);
287 static char *missing_field(char *p, char *errline);
288 static void      change_attrs(const char *, const struct conf_entry *);
289 static const char *get_logfile_suffix(const char *logfile);
290 static fk_entry  do_entry(struct conf_entry *);
291 static fk_entry  do_rotate(const struct conf_entry *);
292 static void      do_sigwork(struct sigwork_entry *);
293 static void      do_zipwork(struct zipwork_entry *);
294 static struct sigwork_entry *
295                  save_sigwork(const struct conf_entry *);
296 static struct zipwork_entry *
297                  save_zipwork(const struct conf_entry *, const struct
298                     sigwork_entry *, int, const char *);
299 static void      set_swpid(struct sigwork_entry *, const struct conf_entry *);
300 static int       sizefile(const char *);
301 static void expand_globs(struct cflist *work_p, struct cflist *glob_p);
302 static void free_clist(struct cflist *list);
303 static void free_entry(struct conf_entry *ent);
304 static struct conf_entry *init_entry(const char *fname,
305                 struct conf_entry *src_entry);
306 static void parse_args(int argc, char **argv);
307 static int parse_doption(const char *doption);
308 static void usage(void);
309 static int log_trim(const char *logname, const struct conf_entry *log_ent);
310 static int age_old_log(const char *file);
311 static void savelog(char *from, char *to);
312 static void createdir(const struct conf_entry *ent, char *dirpart);
313 static void createlog(const struct conf_entry *ent);
314 static int parse_signal(const char *str);
315
316 /*
317  * All the following take a parameter of 'int', but expect values in the
318  * range of unsigned char.  Define wrappers which take values of type 'char',
319  * whether signed or unsigned, and ensure they end up in the right range.
320  */
321 #define isdigitch(Anychar) isdigit((u_char)(Anychar))
322 #define isprintch(Anychar) isprint((u_char)(Anychar))
323 #define isspacech(Anychar) isspace((u_char)(Anychar))
324 #define tolowerch(Anychar) tolower((u_char)(Anychar))
325
326 int
327 main(int argc, char **argv)
328 {
329         struct cflist *worklist;
330         struct conf_entry *p;
331         struct sigwork_entry *stmp;
332         struct zipwork_entry *ztmp;
333
334         SLIST_INIT(&swhead);
335         SLIST_INIT(&zwhead);
336
337         parse_args(argc, argv);
338         argc -= optind;
339         argv += optind;
340
341         if (needroot && getuid() && geteuid())
342                 errx(1, "must have root privs");
343         worklist = get_worklist(argv);
344
345         /*
346          * Rotate all the files which need to be rotated.  Note that
347          * some users have *hundreds* of entries in newsyslog.conf!
348          */
349         while (!STAILQ_EMPTY(worklist)) {
350                 p = STAILQ_FIRST(worklist);
351                 STAILQ_REMOVE_HEAD(worklist, cf_nextp);
352                 if (do_entry(p) == FREE_ENT)
353                         free_entry(p);
354         }
355
356         /*
357          * Send signals to any processes which need a signal to tell
358          * them to close and re-open the log file(s) we have rotated.
359          * Note that zipwork_entries include pointers to these
360          * sigwork_entry's, so we can not free the entries here.
361          */
362         if (!SLIST_EMPTY(&swhead)) {
363                 if (noaction || verbose)
364                         printf("Signal all daemon process(es)...\n");
365                 SLIST_FOREACH(stmp, &swhead, sw_nextp)
366                         do_sigwork(stmp);
367                 if (!(rotatereq && nosignal)) {
368                         if (noaction)
369                                 printf("\tsleep 10\n");
370                         else {
371                                 if (verbose)
372                                         printf("Pause 10 seconds to allow "
373                                             "daemon(s) to close log file(s)\n");
374                                 sleep(10);
375                         }
376                 }
377         }
378         /*
379          * Compress all files that we're expected to compress, now
380          * that all processes should have closed the files which
381          * have been rotated.
382          */
383         if (!SLIST_EMPTY(&zwhead)) {
384                 if (noaction || verbose)
385                         printf("Compress all rotated log file(s)...\n");
386                 while (!SLIST_EMPTY(&zwhead)) {
387                         ztmp = SLIST_FIRST(&zwhead);
388                         do_zipwork(ztmp);
389                         SLIST_REMOVE_HEAD(&zwhead, zw_nextp);
390                         free(ztmp);
391                 }
392         }
393         /* Now free all the sigwork entries. */
394         while (!SLIST_EMPTY(&swhead)) {
395                 stmp = SLIST_FIRST(&swhead);
396                 SLIST_REMOVE_HEAD(&swhead, sw_nextp);
397                 free(stmp);
398         }
399
400         while (wait(NULL) > 0 || errno == EINTR)
401                 ;
402         return (0);
403 }
404
405 static struct conf_entry *
406 init_entry(const char *fname, struct conf_entry *src_entry)
407 {
408         struct conf_entry *tempwork;
409
410         if (verbose > 4)
411                 printf("\t--> [creating entry for %s]\n", fname);
412
413         tempwork = malloc(sizeof(struct conf_entry));
414         if (tempwork == NULL)
415                 err(1, "malloc of conf_entry for %s", fname);
416
417         if (destdir == NULL || fname[0] != '/')
418                 tempwork->log = strdup(fname);
419         else
420                 asprintf(&tempwork->log, "%s%s", destdir, fname);
421         if (tempwork->log == NULL)
422                 err(1, "strdup for %s", fname);
423
424         if (src_entry != NULL) {
425                 tempwork->pid_cmd_file = NULL;
426                 if (src_entry->pid_cmd_file)
427                         tempwork->pid_cmd_file = strdup(src_entry->pid_cmd_file);
428                 tempwork->r_reason = NULL;
429                 tempwork->firstcreate = 0;
430                 tempwork->rotate = 0;
431                 tempwork->fsize = -1;
432                 tempwork->uid = src_entry->uid;
433                 tempwork->gid = src_entry->gid;
434                 tempwork->numlogs = src_entry->numlogs;
435                 tempwork->trsize = src_entry->trsize;
436                 tempwork->hours = src_entry->hours;
437                 tempwork->trim_at = NULL;
438                 if (src_entry->trim_at != NULL)
439                         tempwork->trim_at = ptime_init(src_entry->trim_at);
440                 tempwork->permissions = src_entry->permissions;
441                 tempwork->flags = src_entry->flags;
442                 tempwork->compress = src_entry->compress;
443                 tempwork->sig = src_entry->sig;
444                 tempwork->def_cfg = src_entry->def_cfg;
445         } else {
446                 /* Initialize as a "do-nothing" entry */
447                 tempwork->pid_cmd_file = NULL;
448                 tempwork->r_reason = NULL;
449                 tempwork->firstcreate = 0;
450                 tempwork->rotate = 0;
451                 tempwork->fsize = -1;
452                 tempwork->uid = (uid_t)-1;
453                 tempwork->gid = (gid_t)-1;
454                 tempwork->numlogs = 1;
455                 tempwork->trsize = -1;
456                 tempwork->hours = -1;
457                 tempwork->trim_at = NULL;
458                 tempwork->permissions = 0;
459                 tempwork->flags = 0;
460                 tempwork->compress = COMPRESS_NONE;
461                 tempwork->sig = SIGHUP;
462                 tempwork->def_cfg = 0;
463         }
464
465         return (tempwork);
466 }
467
468 static void
469 free_entry(struct conf_entry *ent)
470 {
471
472         if (ent == NULL)
473                 return;
474
475         if (ent->log != NULL) {
476                 if (verbose > 4)
477                         printf("\t--> [freeing entry for %s]\n", ent->log);
478                 free(ent->log);
479                 ent->log = NULL;
480         }
481
482         if (ent->pid_cmd_file != NULL) {
483                 free(ent->pid_cmd_file);
484                 ent->pid_cmd_file = NULL;
485         }
486
487         if (ent->r_reason != NULL) {
488                 free(ent->r_reason);
489                 ent->r_reason = NULL;
490         }
491
492         if (ent->trim_at != NULL) {
493                 ptime_free(ent->trim_at);
494                 ent->trim_at = NULL;
495         }
496
497         free(ent);
498 }
499
500 static void
501 free_clist(struct cflist *list)
502 {
503         struct conf_entry *ent;
504
505         while (!STAILQ_EMPTY(list)) {
506                 ent = STAILQ_FIRST(list);
507                 STAILQ_REMOVE_HEAD(list, cf_nextp);
508                 free_entry(ent);
509         }
510
511         free(list);
512         list = NULL;
513 }
514
515 static fk_entry
516 do_entry(struct conf_entry * ent)
517 {
518 #define REASON_MAX      80
519         int modtime;
520         fk_entry free_or_keep;
521         double diffsecs;
522         char temp_reason[REASON_MAX];
523         int oversized;
524
525         free_or_keep = FREE_ENT;
526         if (verbose)
527                 printf("%s <%d%s>: ", ent->log, ent->numlogs,
528                     compress_type[ent->compress].flag);
529         ent->fsize = sizefile(ent->log);
530         oversized = ((ent->trsize > 0) && (ent->fsize >= ent->trsize));
531         modtime = age_old_log(ent->log);
532         ent->rotate = 0;
533         ent->firstcreate = 0;
534         if (ent->fsize < 0) {
535                 /*
536                  * If either the C flag or the -C option was specified,
537                  * and if we won't be creating the file, then have the
538                  * verbose message include a hint as to why the file
539                  * will not be created.
540                  */
541                 temp_reason[0] = '\0';
542                 if (createlogs > 1)
543                         ent->firstcreate = 1;
544                 else if ((ent->flags & CE_CREATE) && createlogs)
545                         ent->firstcreate = 1;
546                 else if (ent->flags & CE_CREATE)
547                         strlcpy(temp_reason, " (no -C option)", REASON_MAX);
548                 else if (createlogs)
549                         strlcpy(temp_reason, " (no C flag)", REASON_MAX);
550
551                 if (ent->firstcreate) {
552                         if (verbose)
553                                 printf("does not exist -> will create.\n");
554                         createlog(ent);
555                 } else if (verbose) {
556                         printf("does not exist, skipped%s.\n", temp_reason);
557                 }
558         } else {
559                 if (ent->flags & CE_TRIMAT && !force && !rotatereq &&
560                     !oversized) {
561                         diffsecs = ptimeget_diff(timenow, ent->trim_at);
562                         if (diffsecs < 0.0) {
563                                 /* trim_at is some time in the future. */
564                                 if (verbose) {
565                                         ptime_adjust4dst(ent->trim_at,
566                                             timenow);
567                                         printf("--> will trim at %s",
568                                             ptimeget_ctime(ent->trim_at));
569                                 }
570                                 return (free_or_keep);
571                         } else if (diffsecs >= 3600.0) {
572                                 /*
573                                  * trim_at is more than an hour in the past,
574                                  * so find the next valid trim_at time, and
575                                  * tell the user what that will be.
576                                  */
577                                 if (verbose && dbg_at_times)
578                                         printf("\n\t--> prev trim at %s\t",
579                                             ptimeget_ctime(ent->trim_at));
580                                 if (verbose) {
581                                         ptimeset_nxtime(ent->trim_at);
582                                         printf("--> will trim at %s",
583                                             ptimeget_ctime(ent->trim_at));
584                                 }
585                                 return (free_or_keep);
586                         } else if (verbose && noaction && dbg_at_times) {
587                                 /*
588                                  * If we are just debugging at-times, then
589                                  * a detailed message is helpful.  Also
590                                  * skip "doing" any commands, since they
591                                  * would all be turned off by no-action.
592                                  */
593                                 printf("\n\t--> timematch at %s",
594                                     ptimeget_ctime(ent->trim_at));
595                                 return (free_or_keep);
596                         } else if (verbose && ent->hours <= 0) {
597                                 printf("--> time is up\n");
598                         }
599                 }
600                 if (verbose && (ent->trsize > 0))
601                         printf("size (Kb): %d [%d] ", ent->fsize, ent->trsize);
602                 if (verbose && (ent->hours > 0))
603                         printf(" age (hr): %d [%d] ", modtime, ent->hours);
604
605                 /*
606                  * Figure out if this logfile needs to be rotated.
607                  */
608                 temp_reason[0] = '\0';
609                 if (rotatereq) {
610                         ent->rotate = 1;
611                         snprintf(temp_reason, REASON_MAX, " due to -R from %s",
612                             requestor);
613                 } else if (force) {
614                         ent->rotate = 1;
615                         snprintf(temp_reason, REASON_MAX, " due to -F request");
616                 } else if (oversized) {
617                         ent->rotate = 1;
618                         snprintf(temp_reason, REASON_MAX, " due to size>%dK",
619                             ent->trsize);
620                 } else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) {
621                         ent->rotate = 1;
622                 } else if ((ent->hours > 0) && ((modtime >= ent->hours) ||
623                     (modtime < 0))) {
624                         ent->rotate = 1;
625                 }
626
627                 /*
628                  * If the file needs to be rotated, then rotate it.
629                  */
630                 if (ent->rotate && !norotate) {
631                         if (temp_reason[0] != '\0')
632                                 ent->r_reason = strdup(temp_reason);
633                         if (verbose)
634                                 printf("--> trimming log....\n");
635                         if (noaction && !verbose)
636                                 printf("%s <%d%s>: trimming\n", ent->log,
637                                     ent->numlogs,
638                                     compress_type[ent->compress].flag);
639                         free_or_keep = do_rotate(ent);
640                 } else {
641                         if (verbose)
642                                 printf("--> skipping\n");
643                 }
644         }
645         return (free_or_keep);
646 #undef REASON_MAX
647 }
648
649 static void
650 parse_args(int argc, char **argv)
651 {
652         int ch;
653         char *p;
654
655         timenow = ptime_init(NULL);
656         ptimeset_time(timenow, time(NULL));
657         strlcpy(daytime, ptimeget_ctime(timenow) + 4, DAYTIME_LEN);
658         ptimeget_ctime_rfc5424(timenow, daytime_rfc5424, DAYTIME_RFC5424_LEN);
659
660         /* Let's get our hostname */
661         (void)gethostname(hostname, sizeof(hostname));
662         hostname_shortlen = strcspn(hostname, ".");
663
664         /* Parse command line options. */
665         while ((ch = getopt(argc, argv, "a:d:f:nrst:vCD:FNPR:S:")) != -1)
666                 switch (ch) {
667                 case 'a':
668                         archtodir++;
669                         archdirname = optarg;
670                         break;
671                 case 'd':
672                         destdir = optarg;
673                         break;
674                 case 'f':
675                         conf = optarg;
676                         break;
677                 case 'n':
678                         noaction++;
679                         /* FALLTHROUGH */
680                 case 'r':
681                         needroot = 0;
682                         break;
683                 case 's':
684                         nosignal = 1;
685                         break;
686                 case 't':
687                         if (optarg[0] == '\0' ||
688                             strcmp(optarg, "DEFAULT") == 0)
689                                 timefnamefmt = strdup(DEFAULT_TIMEFNAME_FMT);
690                         else
691                                 timefnamefmt = strdup(optarg);
692                         break;
693                 case 'v':
694                         verbose++;
695                         break;
696                 case 'C':
697                         /* Useful for things like rc.diskless... */
698                         createlogs++;
699                         break;
700                 case 'D':
701                         /*
702                          * Set some debugging option.  The specific option
703                          * depends on the value of optarg.  These options
704                          * may come and go without notice or documentation.
705                          */
706                         if (parse_doption(optarg))
707                                 break;
708                         usage();
709                         /* NOTREACHED */
710                 case 'F':
711                         force++;
712                         break;
713                 case 'N':
714                         norotate++;
715                         break;
716                 case 'P':
717                         enforcepid++;
718                         break;
719                 case 'R':
720                         rotatereq++;
721                         requestor = strdup(optarg);
722                         break;
723                 case 'S':
724                         path_syslogpid = optarg;
725                         break;
726                 case 'm':       /* Used by OpenBSD for "monitor mode" */
727                 default:
728                         usage();
729                         /* NOTREACHED */
730                 }
731
732         if (force && norotate) {
733                 warnx("Only one of -F and -N may be specified.");
734                 usage();
735                 /* NOTREACHED */
736         }
737
738         if (rotatereq) {
739                 if (optind == argc) {
740                         warnx("At least one filename must be given when -R is specified.");
741                         usage();
742                         /* NOTREACHED */
743                 }
744                 /* Make sure "requestor" value is safe for a syslog message. */
745                 for (p = requestor; *p != '\0'; p++) {
746                         if (!isprintch(*p) && (*p != '\t'))
747                                 *p = '.';
748                 }
749         }
750
751         if (dbg_timenow) {
752                 /*
753                  * Note that the 'daytime' variable is not changed.
754                  * That is only used in messages that track when a
755                  * logfile is rotated, and if a file *is* rotated,
756                  * then it will still rotated at the "real now" time.
757                  */
758                 ptime_free(timenow);
759                 timenow = dbg_timenow;
760                 fprintf(stderr, "Debug: Running as if TimeNow is %s",
761                     ptimeget_ctime(dbg_timenow));
762         }
763
764 }
765
766 /*
767  * These debugging options are mainly meant for developer use, such
768  * as writing regression-tests.  They would not be needed by users
769  * during normal operation of newsyslog...
770  */
771 static int
772 parse_doption(const char *doption)
773 {
774         const char TN[] = "TN=";
775         int res;
776
777         if (strncmp(doption, TN, sizeof(TN) - 1) == 0) {
778                 /*
779                  * The "TimeNow" debugging option.  This might be off
780                  * by an hour when crossing a timezone change.
781                  */
782                 dbg_timenow = ptime_init(NULL);
783                 res = ptime_relparse(dbg_timenow, PTM_PARSE_ISO8601,
784                     time(NULL), doption + sizeof(TN) - 1);
785                 if (res == -2) {
786                         warnx("Non-existent time specified on -D %s", doption);
787                         return (0);                     /* failure */
788                 } else if (res < 0) {
789                         warnx("Malformed time given on -D %s", doption);
790                         return (0);                     /* failure */
791                 }
792                 return (1);                     /* successfully parsed */
793
794         }
795
796         if (strcmp(doption, "ats") == 0) {
797                 dbg_at_times++;
798                 return (1);                     /* successfully parsed */
799         }
800
801         /* XXX - This check could probably be dropped. */
802         if ((strcmp(doption, "neworder") == 0) || (strcmp(doption, "oldorder")
803             == 0)) {
804                 warnx("NOTE: newsyslog always uses 'neworder'.");
805                 return (1);                     /* successfully parsed */
806         }
807
808         warnx("Unknown -D (debug) option: '%s'", doption);
809         return (0);                             /* failure */
810 }
811
812 static void
813 usage(void)
814 {
815
816         fprintf(stderr,
817             "usage: newsyslog [-CFNPnrsv] [-a directory] [-d directory] [-f config_file]\n"
818             "                 [-S pidfile] [-t timefmt] [[-R tagname] file ...]\n");
819         exit(1);
820 }
821
822 /*
823  * Parse a configuration file and return a linked list of all the logs
824  * which should be processed.
825  */
826 static struct cflist *
827 get_worklist(char **files)
828 {
829         FILE *f;
830         char **given;
831         struct cflist *cmdlist, *filelist, *globlist;
832         struct conf_entry *defconf, *dupent, *ent;
833         struct ilist inclist;
834         struct include_entry *inc;
835         int gmatch, fnres;
836
837         defconf = NULL;
838         STAILQ_INIT(&inclist);
839
840         filelist = malloc(sizeof(struct cflist));
841         if (filelist == NULL)
842                 err(1, "malloc of filelist");
843         STAILQ_INIT(filelist);
844         globlist = malloc(sizeof(struct cflist));
845         if (globlist == NULL)
846                 err(1, "malloc of globlist");
847         STAILQ_INIT(globlist);
848
849         inc = malloc(sizeof(struct include_entry));
850         if (inc == NULL)
851                 err(1, "malloc of inc");
852         inc->file = conf;
853         if (inc->file == NULL)
854                 inc->file = _PATH_CONF;
855         STAILQ_INSERT_TAIL(&inclist, inc, inc_nextp);
856
857         STAILQ_FOREACH(inc, &inclist, inc_nextp) {
858                 if (strcmp(inc->file, "-") != 0)
859                         f = fopen(inc->file, "r");
860                 else {
861                         f = stdin;
862                         inc->file = "<stdin>";
863                 }
864                 if (!f)
865                         err(1, "%s", inc->file);
866
867                 if (verbose)
868                         printf("Processing %s\n", inc->file);
869                 parse_file(f, filelist, globlist, defconf, &inclist);
870                 (void) fclose(f);
871         }
872
873         /*
874          * All config-file information has been read in and turned into
875          * a filelist and a globlist.  If there were no specific files
876          * given on the run command, then the only thing left to do is to
877          * call a routine which finds all files matched by the globlist
878          * and adds them to the filelist.  Then return the worklist.
879          */
880         if (*files == NULL) {
881                 expand_globs(filelist, globlist);
882                 free_clist(globlist);
883                 if (defconf != NULL)
884                         free_entry(defconf);
885                 return (filelist);
886                 /* NOTREACHED */
887         }
888
889         /*
890          * If newsyslog was given a specific list of files to process,
891          * it may be that some of those files were not listed in any
892          * config file.  Those unlisted files should get the default
893          * rotation action.  First, create the default-rotation action
894          * if none was found in a system config file.
895          */
896         if (defconf == NULL) {
897                 defconf = init_entry(DEFAULT_MARKER, NULL);
898                 defconf->numlogs = 3;
899                 defconf->trsize = 50;
900                 defconf->permissions = S_IRUSR|S_IWUSR;
901         }
902
903         /*
904          * If newsyslog was run with a list of specific filenames,
905          * then create a new worklist which has only those files in
906          * it, picking up the rotation-rules for those files from
907          * the original filelist.
908          *
909          * XXX - Note that this will copy multiple rules for a single
910          *      logfile, if multiple entries are an exact match for
911          *      that file.  That matches the historic behavior, but do
912          *      we want to continue to allow it?  If so, it should
913          *      probably be handled more intelligently.
914          */
915         cmdlist = malloc(sizeof(struct cflist));
916         if (cmdlist == NULL)
917                 err(1, "malloc of cmdlist");
918         STAILQ_INIT(cmdlist);
919
920         for (given = files; *given; ++given) {
921                 /*
922                  * First try to find exact-matches for this given file.
923                  */
924                 gmatch = 0;
925                 STAILQ_FOREACH(ent, filelist, cf_nextp) {
926                         if (strcmp(ent->log, *given) == 0) {
927                                 gmatch++;
928                                 dupent = init_entry(*given, ent);
929                                 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
930                         }
931                 }
932                 if (gmatch) {
933                         if (verbose > 2)
934                                 printf("\t+ Matched entry %s\n", *given);
935                         continue;
936                 }
937
938                 /*
939                  * There was no exact-match for this given file, so look
940                  * for a "glob" entry which does match.
941                  */
942                 gmatch = 0;
943                 if (verbose > 2 && globlist != NULL)
944                         printf("\t+ Checking globs for %s\n", *given);
945                 STAILQ_FOREACH(ent, globlist, cf_nextp) {
946                         fnres = fnmatch(ent->log, *given, FNM_PATHNAME);
947                         if (verbose > 2)
948                                 printf("\t+    = %d for pattern %s\n", fnres,
949                                     ent->log);
950                         if (fnres == 0) {
951                                 gmatch++;
952                                 dupent = init_entry(*given, ent);
953                                 /* This new entry is not a glob! */
954                                 dupent->flags &= ~CE_GLOB;
955                                 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
956                                 /* Only allow a match to one glob-entry */
957                                 break;
958                         }
959                 }
960                 if (gmatch) {
961                         if (verbose > 2)
962                                 printf("\t+ Matched %s via %s\n", *given,
963                                     ent->log);
964                         continue;
965                 }
966
967                 /*
968                  * This given file was not found in any config file, so
969                  * add a worklist item based on the default entry.
970                  */
971                 if (verbose > 2)
972                         printf("\t+ No entry matched %s  (will use %s)\n",
973                             *given, DEFAULT_MARKER);
974                 dupent = init_entry(*given, defconf);
975                 /* Mark that it was *not* found in a config file */
976                 dupent->def_cfg = 1;
977                 STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
978         }
979
980         /*
981          * Free all the entries in the original work list, the list of
982          * glob entries, and the default entry.
983          */
984         free_clist(filelist);
985         free_clist(globlist);
986         free_entry(defconf);
987
988         /* And finally, return a worklist which matches the given files. */
989         return (cmdlist);
990 }
991
992 /*
993  * Expand the list of entries with filename patterns, and add all files
994  * which match those glob-entries onto the worklist.
995  */
996 static void
997 expand_globs(struct cflist *work_p, struct cflist *glob_p)
998 {
999         int gmatch, gres;
1000         size_t i;
1001         char *mfname;
1002         struct conf_entry *dupent, *ent, *globent;
1003         glob_t pglob;
1004         struct stat st_fm;
1005
1006         /*
1007          * The worklist contains all fully-specified (non-GLOB) names.
1008          *
1009          * Now expand the list of filename-pattern (GLOB) entries into
1010          * a second list, which (by definition) will only match files
1011          * that already exist.  Do not add a glob-related entry for any
1012          * file which already exists in the fully-specified list.
1013          */
1014         STAILQ_FOREACH(globent, glob_p, cf_nextp) {
1015                 gres = glob(globent->log, GLOB_NOCHECK, NULL, &pglob);
1016                 if (gres != 0) {
1017                         warn("cannot expand pattern (%d): %s", gres,
1018                             globent->log);
1019                         continue;
1020                 }
1021
1022                 if (verbose > 2)
1023                         printf("\t+ Expanding pattern %s\n", globent->log);
1024                 for (i = 0; i < pglob.gl_matchc; i++) {
1025                         mfname = pglob.gl_pathv[i];
1026
1027                         /* See if this file already has a specific entry. */
1028                         gmatch = 0;
1029                         STAILQ_FOREACH(ent, work_p, cf_nextp) {
1030                                 if (strcmp(mfname, ent->log) == 0) {
1031                                         gmatch++;
1032                                         break;
1033                                 }
1034                         }
1035                         if (gmatch)
1036                                 continue;
1037
1038                         /* Make sure the named matched is a file. */
1039                         gres = lstat(mfname, &st_fm);
1040                         if (gres != 0) {
1041                                 /* Error on a file that glob() matched?!? */
1042                                 warn("Skipping %s - lstat() error", mfname);
1043                                 continue;
1044                         }
1045                         if (!S_ISREG(st_fm.st_mode)) {
1046                                 /* We only rotate files! */
1047                                 if (verbose > 2)
1048                                         printf("\t+  . skipping %s (!file)\n",
1049                                             mfname);
1050                                 continue;
1051                         }
1052
1053                         if (verbose > 2)
1054                                 printf("\t+  . add file %s\n", mfname);
1055                         dupent = init_entry(mfname, globent);
1056                         /* This new entry is not a glob! */
1057                         dupent->flags &= ~CE_GLOB;
1058
1059                         /* Add to the worklist. */
1060                         STAILQ_INSERT_TAIL(work_p, dupent, cf_nextp);
1061                 }
1062                 globfree(&pglob);
1063                 if (verbose > 2)
1064                         printf("\t+ Done with pattern %s\n", globent->log);
1065         }
1066 }
1067
1068 /*
1069  * Parse a configuration file and update a linked list of all the logs to
1070  * process.
1071  */
1072 static void
1073 parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
1074     struct conf_entry *defconf_p, struct ilist *inclist)
1075 {
1076         char line[BUFSIZ], *parse, *q;
1077         char *cp, *errline, *group;
1078         struct conf_entry *working;
1079         struct passwd *pwd;
1080         struct group *grp;
1081         glob_t pglob;
1082         int eol, ptm_opts, res, special;
1083         size_t i;
1084
1085         errline = NULL;
1086         while (fgets(line, BUFSIZ, cf)) {
1087                 if ((line[0] == '\n') || (line[0] == '#') ||
1088                     (strlen(line) == 0))
1089                         continue;
1090                 if (errline != NULL)
1091                         free(errline);
1092                 errline = strdup(line);
1093                 for (cp = line + 1; *cp != '\0'; cp++) {
1094                         if (*cp != '#')
1095                                 continue;
1096                         if (*(cp - 1) == '\\') {
1097                                 strcpy(cp - 1, cp);
1098                                 cp--;
1099                                 continue;
1100                         }
1101                         *cp = '\0';
1102                         break;
1103                 }
1104
1105                 q = parse = missing_field(sob(line), errline);
1106                 parse = son(line);
1107                 if (!*parse)
1108                         errx(1, "malformed line (missing fields):\n%s",
1109                             errline);
1110                 *parse = '\0';
1111
1112                 /*
1113                  * Allow people to set debug options via the config file.
1114                  * (NOTE: debug options are undocumented, and may disappear
1115                  * at any time, etc).
1116                  */
1117                 if (strcasecmp(DEBUG_MARKER, q) == 0) {
1118                         q = parse = missing_field(sob(parse + 1), errline);
1119                         parse = son(parse);
1120                         if (!*parse)
1121                                 warnx("debug line specifies no option:\n%s",
1122                                     errline);
1123                         else {
1124                                 *parse = '\0';
1125                                 parse_doption(q);
1126                         }
1127                         continue;
1128                 } else if (strcasecmp(INCLUDE_MARKER, q) == 0) {
1129                         if (verbose)
1130                                 printf("Found: %s", errline);
1131                         q = parse = missing_field(sob(parse + 1), errline);
1132                         parse = son(parse);
1133                         if (!*parse) {
1134                                 warnx("include line missing argument:\n%s",
1135                                     errline);
1136                                 continue;
1137                         }
1138
1139                         *parse = '\0';
1140
1141                         if (isglobstr(q)) {
1142                                 res = glob(q, GLOB_NOCHECK, NULL, &pglob);
1143                                 if (res != 0) {
1144                                         warn("cannot expand pattern (%d): %s",
1145                                             res, q);
1146                                         continue;
1147                                 }
1148
1149                                 if (verbose > 2)
1150                                         printf("\t+ Expanding pattern %s\n", q);
1151
1152                                 for (i = 0; i < pglob.gl_matchc; i++)
1153                                         add_to_queue(pglob.gl_pathv[i],
1154                                             inclist);
1155                                 globfree(&pglob);
1156                         } else
1157                                 add_to_queue(q, inclist);
1158                         continue;
1159                 }
1160
1161                 special = 0;
1162                 working = init_entry(q, NULL);
1163                 if (strcasecmp(DEFAULT_MARKER, q) == 0) {
1164                         special = 1;
1165                         if (defconf_p != NULL) {
1166                                 warnx("Ignoring duplicate entry for %s!", q);
1167                                 free_entry(working);
1168                                 continue;
1169                         }
1170                         defconf_p = working;
1171                 }
1172
1173                 q = parse = missing_field(sob(parse + 1), errline);
1174                 parse = son(parse);
1175                 if (!*parse)
1176                         errx(1, "malformed line (missing fields):\n%s",
1177                             errline);
1178                 *parse = '\0';
1179                 if ((group = strchr(q, ':')) != NULL ||
1180                     (group = strrchr(q, '.')) != NULL) {
1181                         *group++ = '\0';
1182                         if (*q) {
1183                                 if (!(isnumberstr(q))) {
1184                                         if ((pwd = getpwnam(q)) == NULL)
1185                                                 errx(1,
1186                                      "error in config file; unknown user:\n%s",
1187                                                     errline);
1188                                         working->uid = pwd->pw_uid;
1189                                 } else
1190                                         working->uid = atoi(q);
1191                         } else
1192                                 working->uid = (uid_t)-1;
1193
1194                         q = group;
1195                         if (*q) {
1196                                 if (!(isnumberstr(q))) {
1197                                         if ((grp = getgrnam(q)) == NULL)
1198                                                 errx(1,
1199                                     "error in config file; unknown group:\n%s",
1200                                                     errline);
1201                                         working->gid = grp->gr_gid;
1202                                 } else
1203                                         working->gid = atoi(q);
1204                         } else
1205                                 working->gid = (gid_t)-1;
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                 } else {
1214                         working->uid = (uid_t)-1;
1215                         working->gid = (gid_t)-1;
1216                 }
1217
1218                 if (!sscanf(q, "%o", &working->permissions))
1219                         errx(1, "error in config file; bad permissions:\n%s",
1220                             errline);
1221
1222                 q = parse = missing_field(sob(parse + 1), errline);
1223                 parse = son(parse);
1224                 if (!*parse)
1225                         errx(1, "malformed line (missing fields):\n%s",
1226                             errline);
1227                 *parse = '\0';
1228                 if (!sscanf(q, "%d", &working->numlogs) || working->numlogs < 0)
1229                         errx(1, "error in config file; bad value for count of logs to save:\n%s",
1230                             errline);
1231
1232                 q = parse = missing_field(sob(parse + 1), errline);
1233                 parse = son(parse);
1234                 if (!*parse)
1235                         errx(1, "malformed line (missing fields):\n%s",
1236                             errline);
1237                 *parse = '\0';
1238                 if (isdigitch(*q))
1239                         working->trsize = atoi(q);
1240                 else if (strcmp(q, "*") == 0)
1241                         working->trsize = -1;
1242                 else {
1243                         warnx("Invalid value of '%s' for 'size' in line:\n%s",
1244                             q, errline);
1245                         working->trsize = -1;
1246                 }
1247
1248                 working->flags = 0;
1249                 working->compress = COMPRESS_NONE;
1250                 q = parse = missing_field(sob(parse + 1), errline);
1251                 parse = son(parse);
1252                 eol = !*parse;
1253                 *parse = '\0';
1254                 {
1255                         char *ep;
1256                         u_long ul;
1257
1258                         ul = strtoul(q, &ep, 10);
1259                         if (ep == q)
1260                                 working->hours = 0;
1261                         else if (*ep == '*')
1262                                 working->hours = -1;
1263                         else if (ul > INT_MAX)
1264                                 errx(1, "interval is too large:\n%s", errline);
1265                         else
1266                                 working->hours = ul;
1267
1268                         if (*ep == '\0' || strcmp(ep, "*") == 0)
1269                                 goto no_trimat;
1270                         if (*ep != '@' && *ep != '$')
1271                                 errx(1, "malformed interval/at:\n%s", errline);
1272
1273                         working->flags |= CE_TRIMAT;
1274                         working->trim_at = ptime_init(NULL);
1275                         ptm_opts = PTM_PARSE_ISO8601;
1276                         if (*ep == '$')
1277                                 ptm_opts = PTM_PARSE_DWM;
1278                         ptm_opts |= PTM_PARSE_MATCHDOM;
1279                         res = ptime_relparse(working->trim_at, ptm_opts,
1280                             ptimeget_secs(timenow), ep + 1);
1281                         if (res == -2)
1282                                 errx(1, "nonexistent time for 'at' value:\n%s",
1283                                     errline);
1284                         else if (res < 0)
1285                                 errx(1, "malformed 'at' value:\n%s", errline);
1286                 }
1287 no_trimat:
1288
1289                 if (eol)
1290                         q = NULL;
1291                 else {
1292                         q = parse = sob(parse + 1);     /* Optional field */
1293                         parse = son(parse);
1294                         if (!*parse)
1295                                 eol = 1;
1296                         *parse = '\0';
1297                 }
1298
1299                 for (; q && *q && !isspacech(*q); q++) {
1300                         switch (tolowerch(*q)) {
1301                         case 'b':
1302                                 working->flags |= CE_BINARY;
1303                                 break;
1304                         case 'c':
1305                                 working->flags |= CE_CREATE;
1306                                 break;
1307                         case 'd':
1308                                 working->flags |= CE_NODUMP;
1309                                 break;
1310                         case 'g':
1311                                 working->flags |= CE_GLOB;
1312                                 break;
1313                         case 'j':
1314                                 working->compress = COMPRESS_BZIP2;
1315                                 break;
1316                         case 'n':
1317                                 working->flags |= CE_NOSIGNAL;
1318                                 break;
1319                         case 'p':
1320                                 working->flags |= CE_PLAIN0;
1321                                 break;
1322                         case 'r':
1323                                 working->flags |= CE_PID2CMD;
1324                                 break;
1325                         case 't':
1326                                 working->flags |= CE_RFC5424;
1327                                 break;
1328                         case 'u':
1329                                 working->flags |= CE_SIGNALGROUP;
1330                                 break;
1331                         case 'w':
1332                                 /* Deprecated flag - keep for compatibility purposes */
1333                                 break;
1334                         case 'x':
1335                                 working->compress = COMPRESS_XZ;
1336                                 break;
1337                         case 'y':
1338                                 working->compress = COMPRESS_ZSTD;
1339                                 break;
1340                         case 'z':
1341                                 working->compress = COMPRESS_GZIP;
1342                                 break;
1343                         case '-':
1344                                 break;
1345                         case 'f':       /* Used by OpenBSD for "CE_FOLLOW" */
1346                         case 'm':       /* Used by OpenBSD for "CE_MONITOR" */
1347                         default:
1348                                 errx(1, "illegal flag in config file -- %c",
1349                                     *q);
1350                         }
1351                 }
1352
1353                 if (eol)
1354                         q = NULL;
1355                 else {
1356                         q = parse = sob(parse + 1);     /* Optional field */
1357                         parse = son(parse);
1358                         if (!*parse)
1359                                 eol = 1;
1360                         *parse = '\0';
1361                 }
1362
1363                 working->pid_cmd_file = NULL;
1364                 if (q && *q) {
1365                         if (*q == '/')
1366                                 working->pid_cmd_file = strdup(q);
1367                         else if (isalnum(*q))
1368                                 goto got_sig;
1369                         else {
1370                                 errx(1,
1371                         "illegal pid file or signal in config file:\n%s",
1372                                     errline);
1373                         }
1374                 }
1375                 if (eol)
1376                         q = NULL;
1377                 else {
1378                         q = parse = sob(parse + 1);     /* Optional field */
1379                         *(parse = son(parse)) = '\0';
1380                 }
1381
1382                 working->sig = SIGHUP;
1383                 if (q && *q) {
1384 got_sig:
1385                         working->sig = parse_signal(q);
1386                         if (working->sig < 1 || working->sig >= sys_nsig) {
1387                                 errx(1,
1388                                     "illegal signal in config file:\n%s",
1389                                     errline);
1390                         }
1391                 }
1392
1393                 /*
1394                  * Finish figuring out what pid-file to use (if any) in
1395                  * later processing if this logfile needs to be rotated.
1396                  */
1397                 if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) {
1398                         /*
1399                          * This config-entry specified 'n' for nosignal,
1400                          * see if it also specified an explicit pid_cmd_file.
1401                          * This would be a pretty pointless combination.
1402                          */
1403                         if (working->pid_cmd_file != NULL) {
1404                                 warnx("Ignoring '%s' because flag 'n' was specified in line:\n%s",
1405                                     working->pid_cmd_file, errline);
1406                                 free(working->pid_cmd_file);
1407                                 working->pid_cmd_file = NULL;
1408                         }
1409                 } else if (working->pid_cmd_file == NULL) {
1410                         /*
1411                          * This entry did not specify the 'n' flag, which
1412                          * means it should signal syslogd unless it had
1413                          * specified some other pid-file (and obviously the
1414                          * syslog pid-file will not be for a process-group).
1415                          * Also, we should only try to notify syslog if we
1416                          * are root.
1417                          */
1418                         if (working->flags & CE_SIGNALGROUP) {
1419                                 warnx("Ignoring flag 'U' in line:\n%s",
1420                                     errline);
1421                                 working->flags &= ~CE_SIGNALGROUP;
1422                         }
1423                         if (needroot)
1424                                 working->pid_cmd_file = strdup(path_syslogpid);
1425                 }
1426
1427                 /*
1428                  * Add this entry to the appropriate list of entries, unless
1429                  * it was some kind of special entry (eg: <default>).
1430                  */
1431                 if (special) {
1432                         ;                       /* Do not add to any list */
1433                 } else if (working->flags & CE_GLOB) {
1434                         STAILQ_INSERT_TAIL(glob_p, working, cf_nextp);
1435                 } else {
1436                         STAILQ_INSERT_TAIL(work_p, working, cf_nextp);
1437                 }
1438         }
1439         if (errline != NULL)
1440                 free(errline);
1441 }
1442
1443 static char *
1444 missing_field(char *p, char *errline)
1445 {
1446
1447         if (!p || !*p)
1448                 errx(1, "missing field in config file:\n%s", errline);
1449         return (p);
1450 }
1451
1452 /*
1453  * In our sort we return it in the reverse of what qsort normally
1454  * would do, as we want the newest files first.  If we have two
1455  * entries with the same time we don't really care about order.
1456  *
1457  * Support function for qsort() in delete_oldest_timelog().
1458  */
1459 static int
1460 oldlog_entry_compare(const void *a, const void *b)
1461 {
1462         const struct oldlog_entry *ola = a, *olb = b;
1463
1464         if (ola->t > olb->t)
1465                 return (-1);
1466         else if (ola->t < olb->t)
1467                 return (1);
1468         else
1469                 return (0);
1470 }
1471
1472 /*
1473  * Check whether the file corresponding to dp is an archive of the logfile
1474  * logfname, based on the timefnamefmt format string. Return true and fill out
1475  * tm if this is the case; otherwise return false.
1476  */
1477 static int
1478 validate_old_timelog(int fd, const struct dirent *dp, const char *logfname,
1479     struct tm *tm)
1480 {
1481         struct stat sb;
1482         size_t logfname_len;
1483         char *s;
1484         int c;
1485
1486         logfname_len = strlen(logfname);
1487
1488         if (dp->d_type != DT_REG) {
1489                 /*
1490                  * Some filesystems (e.g. NFS) don't fill out the d_type field
1491                  * and leave it set to DT_UNKNOWN; in this case we must obtain
1492                  * the file type ourselves.
1493                  */
1494                 if (dp->d_type != DT_UNKNOWN ||
1495                     fstatat(fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) != 0 ||
1496                     !S_ISREG(sb.st_mode))
1497                         return (0);
1498         }
1499         /* Ignore everything but files with our logfile prefix. */
1500         if (strncmp(dp->d_name, logfname, logfname_len) != 0)
1501                 return (0);
1502         /* Ignore the actual non-rotated logfile. */
1503         if (dp->d_namlen == logfname_len)
1504                 return (0);
1505
1506         /*
1507          * Make sure we created have found a logfile, so the
1508          * postfix is valid, IE format is: '.<time>(.[bgx]z)?'.
1509          */
1510         if (dp->d_name[logfname_len] != '.') {
1511                 if (verbose)
1512                         printf("Ignoring %s which has unexpected "
1513                             "extension '%s'\n", dp->d_name,
1514                             &dp->d_name[logfname_len]);
1515                 return (0);
1516         }
1517         memset(tm, 0, sizeof(*tm));
1518         if ((s = strptime(&dp->d_name[logfname_len + 1],
1519             timefnamefmt, tm)) == NULL) {
1520                 /*
1521                  * We could special case "old" sequentially named logfiles here,
1522                  * but we do not as that would require special handling to
1523                  * decide which one was the oldest compared to "new" time based
1524                  * logfiles.
1525                  */
1526                 if (verbose)
1527                         printf("Ignoring %s which does not "
1528                             "match time format\n", dp->d_name);
1529                 return (0);
1530         }
1531
1532         for (c = 0; c < COMPRESS_TYPES; c++)
1533                 if (strcmp(s, compress_type[c].suffix) == 0)
1534                         /* We're done. */
1535                         return (1);
1536
1537         if (verbose)
1538                 printf("Ignoring %s which has unexpected extension '%s'\n",
1539                     dp->d_name, s);
1540
1541         return (0);
1542 }
1543
1544 /*
1545  * Delete the oldest logfiles, when using time based filenames.
1546  */
1547 static void
1548 delete_oldest_timelog(const struct conf_entry *ent, const char *archive_dir)
1549 {
1550         char *basebuf, *dirbuf, errbuf[80];
1551         const char *base, *dir;
1552         int dir_fd, i, logcnt, max_logcnt;
1553         struct oldlog_entry *oldlogs;
1554         struct dirent *dp;
1555         struct tm tm;
1556         DIR *dirp;
1557
1558         oldlogs = malloc(MAX_OLDLOGS * sizeof(struct oldlog_entry));
1559         max_logcnt = MAX_OLDLOGS;
1560         logcnt = 0;
1561
1562         if (archive_dir != NULL && archive_dir[0] != '\0') {
1563                 dirbuf = NULL;
1564                 dir = archive_dir;
1565         } else {
1566                 if ((dirbuf = strdup(ent->log)) == NULL)
1567                         err(1, "strdup()");
1568                 dir = dirname(dirbuf);
1569         }
1570
1571         if ((basebuf = strdup(ent->log)) == NULL)
1572                 err(1, "strdup()");
1573         base = basename(basebuf);
1574         if (strcmp(base, "/") == 0)
1575                 errx(1, "Invalid log filename - became '/'");
1576
1577         if (verbose > 2)
1578                 printf("Searching for old logs in %s\n", dir);
1579
1580         /* First we create a 'list' of all archived logfiles */
1581         if ((dirp = opendir(dir)) == NULL)
1582                 err(1, "Cannot open log directory '%s'", dir);
1583         dir_fd = dirfd(dirp);
1584         while ((dp = readdir(dirp)) != NULL) {
1585                 if (validate_old_timelog(dir_fd, dp, base, &tm) == 0)
1586                         continue;
1587
1588                 /*
1589                  * We should now have old an old rotated logfile, so
1590                  * add it to the 'list'.
1591                  */
1592                 if ((oldlogs[logcnt].t = timegm(&tm)) == -1)
1593                         err(1, "Could not convert time string to time value");
1594                 if ((oldlogs[logcnt].fname = strdup(dp->d_name)) == NULL)
1595                         err(1, "strdup()");
1596                 logcnt++;
1597
1598                 /*
1599                  * It is very unlikely we ever run out of space in the
1600                  * logfile array from the default size, but lets
1601                  * handle it anyway...
1602                  */
1603                 if (logcnt >= max_logcnt) {
1604                         max_logcnt *= 4;
1605                         /* Detect integer overflow */
1606                         if (max_logcnt < logcnt)
1607                                 errx(1, "Too many old logfiles found");
1608                         oldlogs = realloc(oldlogs,
1609                             max_logcnt * sizeof(struct oldlog_entry));
1610                         if (oldlogs == NULL)
1611                                 err(1, "realloc()");
1612                 }
1613         }
1614
1615         /* Second, if needed we delete oldest archived logfiles */
1616         if (logcnt > 0 && logcnt >= ent->numlogs && ent->numlogs > 1) {
1617                 oldlogs = realloc(oldlogs, logcnt *
1618                     sizeof(struct oldlog_entry));
1619                 if (oldlogs == NULL)
1620                         err(1, "realloc()");
1621
1622                 /*
1623                  * We now sort the logs in the order of newest to
1624                  * oldest.  That way we can simply skip over the
1625                  * number of records we want to keep.
1626                  */
1627                 qsort(oldlogs, logcnt, sizeof(struct oldlog_entry),
1628                     oldlog_entry_compare);
1629                 for (i = ent->numlogs - 1; i < logcnt; i++) {
1630                         if (noaction)
1631                                 printf("\trm -f %s/%s\n", dir,
1632                                     oldlogs[i].fname);
1633                         else if (unlinkat(dir_fd, oldlogs[i].fname, 0) != 0) {
1634                                 snprintf(errbuf, sizeof(errbuf),
1635                                     "Could not delete old logfile '%s'",
1636                                     oldlogs[i].fname);
1637                                 perror(errbuf);
1638                         }
1639                 }
1640         } else if (verbose > 1)
1641                 printf("No old logs to delete for logfile %s\n", ent->log);
1642
1643         /* Third, cleanup */
1644         closedir(dirp);
1645         for (i = 0; i < logcnt; i++) {
1646                 assert(oldlogs[i].fname != NULL);
1647                 free(oldlogs[i].fname);
1648         }
1649         free(oldlogs);
1650         free(dirbuf);
1651         free(basebuf);
1652 }
1653
1654 /*
1655  * Generate a log filename, when using classic filenames.
1656  */
1657 static void
1658 gen_classiclog_fname(char *fname, size_t fname_sz, const char *archive_dir,
1659     const char *namepart, int numlogs_c)
1660 {
1661
1662         if (archive_dir[0] != '\0')
1663                 (void) snprintf(fname, fname_sz, "%s/%s.%d", archive_dir,
1664                     namepart, numlogs_c);
1665         else
1666                 (void) snprintf(fname, fname_sz, "%s.%d", namepart, numlogs_c);
1667 }
1668
1669 /*
1670  * Delete a rotated logfile, when using classic filenames.
1671  */
1672 static void
1673 delete_classiclog(const char *archive_dir, const char *namepart, int numlog_c)
1674 {
1675         char file1[MAXPATHLEN], zfile1[MAXPATHLEN];
1676         int c;
1677
1678         gen_classiclog_fname(file1, sizeof(file1), archive_dir, namepart,
1679             numlog_c);
1680
1681         for (c = 0; c < COMPRESS_TYPES; c++) {
1682                 (void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1683                     compress_type[c].suffix);
1684                 if (noaction)
1685                         printf("\trm -f %s\n", zfile1);
1686                 else
1687                         (void) unlink(zfile1);
1688         }
1689 }
1690
1691 /*
1692  * Only add to the queue if the file hasn't already been added. This is
1693  * done to prevent circular include loops.
1694  */
1695 static void
1696 add_to_queue(const char *fname, struct ilist *inclist)
1697 {
1698         struct include_entry *inc;
1699
1700         STAILQ_FOREACH(inc, inclist, inc_nextp) {
1701                 if (strcmp(fname, inc->file) == 0) {
1702                         warnx("duplicate include detected: %s", fname);
1703                         return;
1704                 }
1705         }
1706
1707         inc = malloc(sizeof(struct include_entry));
1708         if (inc == NULL)
1709                 err(1, "malloc of inc");
1710         inc->file = strdup(fname);
1711
1712         if (verbose > 2)
1713                 printf("\t+ Adding %s to the processing queue.\n", fname);
1714
1715         STAILQ_INSERT_TAIL(inclist, inc, inc_nextp);
1716 }
1717
1718 /*
1719  * Search for logfile and return its compression suffix (if supported)
1720  * The suffix detection is first-match in the order of compress_types
1721  *
1722  * Note: if logfile without suffix exists (uncompressed, COMPRESS_NONE)
1723  * a zero-length string is returned
1724  */
1725 static const char *
1726 get_logfile_suffix(const char *logfile)
1727 {
1728         struct stat st;
1729         char zfile[MAXPATHLEN];
1730         int c;
1731
1732         for (c = 0; c < COMPRESS_TYPES; c++) {
1733                 (void) strlcpy(zfile, logfile, MAXPATHLEN);
1734                 (void) strlcat(zfile, compress_type[c].suffix, MAXPATHLEN);
1735                 if (lstat(zfile, &st) == 0)
1736                         return (compress_type[c].suffix);
1737         }
1738         return (NULL);
1739 }
1740
1741 static fk_entry
1742 do_rotate(const struct conf_entry *ent)
1743 {
1744         char dirpart[MAXPATHLEN], namepart[MAXPATHLEN];
1745         char file1[MAXPATHLEN], file2[MAXPATHLEN];
1746         char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN];
1747         const char *logfile_suffix;
1748         char datetimestr[30];
1749         int flags, numlogs_c;
1750         fk_entry free_or_keep;
1751         struct sigwork_entry *swork;
1752         struct stat st;
1753         struct tm tm;
1754         time_t now;
1755
1756         flags = ent->flags;
1757         free_or_keep = FREE_ENT;
1758
1759         if (archtodir) {
1760                 char *p;
1761
1762                 /* build complete name of archive directory into dirpart */
1763                 if (*archdirname == '/') {      /* absolute */
1764                         strlcpy(dirpart, archdirname, sizeof(dirpart));
1765                 } else {        /* relative */
1766                         /* get directory part of logfile */
1767                         strlcpy(dirpart, ent->log, sizeof(dirpart));
1768                         if ((p = strrchr(dirpart, '/')) == NULL)
1769                                 dirpart[0] = '\0';
1770                         else
1771                                 *(p + 1) = '\0';
1772                         strlcat(dirpart, archdirname, sizeof(dirpart));
1773                 }
1774
1775                 /* check if archive directory exists, if not, create it */
1776                 if (lstat(dirpart, &st))
1777                         createdir(ent, dirpart);
1778
1779                 /* get filename part of logfile */
1780                 if ((p = strrchr(ent->log, '/')) == NULL)
1781                         strlcpy(namepart, ent->log, sizeof(namepart));
1782                 else
1783                         strlcpy(namepart, p + 1, sizeof(namepart));
1784         } else {
1785                 /*
1786                  * Tell utility functions we are not using an archive
1787                  * dir.
1788                  */
1789                 dirpart[0] = '\0';
1790                 strlcpy(namepart, ent->log, sizeof(namepart));
1791         }
1792
1793         /* Delete old logs */
1794         if (timefnamefmt != NULL)
1795                 delete_oldest_timelog(ent, dirpart);
1796         else {
1797                 /*
1798                  * Handle cleaning up after legacy newsyslog where we
1799                  * kept ent->numlogs + 1 files.  This code can go away
1800                  * at some point in the future.
1801                  */
1802                 delete_classiclog(dirpart, namepart, ent->numlogs);
1803
1804                 if (ent->numlogs > 0)
1805                         delete_classiclog(dirpart, namepart, ent->numlogs - 1);
1806
1807         }
1808
1809         if (timefnamefmt != NULL) {
1810                 /* If time functions fails we can't really do any sensible */
1811                 if (time(&now) == (time_t)-1 ||
1812                     localtime_r(&now, &tm) == NULL)
1813                         bzero(&tm, sizeof(tm));
1814
1815                 strftime(datetimestr, sizeof(datetimestr), timefnamefmt, &tm);
1816                 if (archtodir)
1817                         (void) snprintf(file1, sizeof(file1), "%s/%s.%s",
1818                             dirpart, namepart, datetimestr);
1819                 else
1820                         (void) snprintf(file1, sizeof(file1), "%s.%s",
1821                             ent->log, datetimestr);
1822
1823                 /* Don't run the code to move down logs */
1824                 numlogs_c = -1;
1825         } else {
1826                 gen_classiclog_fname(file1, sizeof(file1), dirpart, namepart,
1827                     ent->numlogs - 1);
1828                 numlogs_c = ent->numlogs - 2;           /* copy for countdown */
1829         }
1830
1831         /* Move down log files */
1832         for (; numlogs_c >= 0; numlogs_c--) {
1833                 (void) strlcpy(file2, file1, sizeof(file2));
1834
1835                 gen_classiclog_fname(file1, sizeof(file1), dirpart, namepart,
1836                     numlogs_c);
1837
1838                 logfile_suffix = get_logfile_suffix(file1);
1839                 if (logfile_suffix == NULL)
1840                         continue;
1841                 (void) strlcpy(zfile1, file1, MAXPATHLEN);
1842                 (void) strlcpy(zfile2, file2, MAXPATHLEN);
1843                 (void) strlcat(zfile1, logfile_suffix, MAXPATHLEN);
1844                 (void) strlcat(zfile2, logfile_suffix, MAXPATHLEN);
1845
1846                 if (noaction)
1847                         printf("\tmv %s %s\n", zfile1, zfile2);
1848                 else {
1849                         /* XXX - Ought to be checking for failure! */
1850                         (void)rename(zfile1, zfile2);
1851                         change_attrs(zfile2, ent);
1852                         if (ent->compress && !strlen(logfile_suffix)) {
1853                                 /* compress old rotation */
1854                                 struct zipwork_entry zwork;
1855
1856                                 memset(&zwork, 0, sizeof(zwork));
1857                                 zwork.zw_conf = ent;
1858                                 zwork.zw_fsize = sizefile(zfile2);
1859                                 strcpy(zwork.zw_fname, zfile2);
1860                                 do_zipwork(&zwork);
1861                         }
1862                 }
1863         }
1864
1865         if (ent->numlogs > 0) {
1866                 if (noaction) {
1867                         /*
1868                          * Note that savelog() may succeed with using link()
1869                          * for the archtodir case, but there is no good way
1870                          * of knowing if it will when doing "noaction", so
1871                          * here we claim that it will have to do a copy...
1872                          */
1873                         if (archtodir)
1874                                 printf("\tcp %s %s\n", ent->log, file1);
1875                         else
1876                                 printf("\tln %s %s\n", ent->log, file1);
1877                         printf("\ttouch %s\t\t"
1878                             "# Update mtime for 'when'-interval processing\n",
1879                             file1);
1880                 } else {
1881                         if (!(flags & CE_BINARY)) {
1882                                 /* Report the trimming to the old log */
1883                                 log_trim(ent->log, ent);
1884                         }
1885                         savelog(ent->log, file1);
1886                         /*
1887                          * Interval-based rotations are done using the mtime of
1888                          * the most recently archived log, so make sure it gets
1889                          * updated during a rotation.
1890                          */
1891                         utimes(file1, NULL);
1892                 }
1893                 change_attrs(file1, ent);
1894         }
1895
1896         /* Create the new log file and move it into place */
1897         if (noaction)
1898                 printf("Start new log...\n");
1899         createlog(ent);
1900
1901         /*
1902          * Save all signalling and file-compression to be done after log
1903          * files from all entries have been rotated.  This way any one
1904          * process will not be sent the same signal multiple times when
1905          * multiple log files had to be rotated.
1906          */
1907         swork = NULL;
1908         if (ent->pid_cmd_file != NULL)
1909                 swork = save_sigwork(ent);
1910         if (ent->numlogs > 0 && ent->compress > COMPRESS_NONE) {
1911                 if (!(ent->flags & CE_PLAIN0) ||
1912                     strcmp(&file1[strlen(file1) - 2], ".0") != 0) {
1913                         /*
1914                          * The zipwork_entry will include a pointer to this
1915                          * conf_entry, so the conf_entry should not be freed.
1916                          */
1917                         free_or_keep = KEEP_ENT;
1918                         save_zipwork(ent, swork, ent->fsize, file1);
1919                 }
1920         }
1921
1922         return (free_or_keep);
1923 }
1924
1925 static void
1926 do_sigwork(struct sigwork_entry *swork)
1927 {
1928         struct sigwork_entry *nextsig;
1929         int kres, secs;
1930         char *tmp;
1931
1932         if (swork->sw_runcmd == 0 && (!(swork->sw_pidok) || swork->sw_pid == 0))
1933                 return;                 /* no work to do... */
1934
1935         /*
1936          * If nosignal (-s) was specified, then do not signal any process.
1937          * Note that a nosignal request triggers a warning message if the
1938          * rotated logfile needs to be compressed, *unless* -R was also
1939          * specified.  We assume that an `-sR' request came from a process
1940          * which writes to the logfile, and as such, we assume that process
1941          * has already made sure the logfile is not presently in use.  This
1942          * just sets swork->sw_pidok to a special value, and do_zipwork
1943          * will print any necessary warning(s).
1944          */
1945         if (nosignal) {
1946                 if (!rotatereq)
1947                         swork->sw_pidok = -1;
1948                 return;
1949         }
1950
1951         /*
1952          * Compute the pause between consecutive signals.  Use a longer
1953          * sleep time if we will be sending two signals to the same
1954          * daemon or process-group.
1955          */
1956         secs = 0;
1957         nextsig = SLIST_NEXT(swork, sw_nextp);
1958         if (nextsig != NULL) {
1959                 if (swork->sw_pid == nextsig->sw_pid)
1960                         secs = 10;
1961                 else
1962                         secs = 1;
1963         }
1964
1965         if (noaction) {
1966                 if (swork->sw_runcmd)
1967                         printf("\tsh -c '%s %d'\n", swork->sw_fname,
1968                             swork->sw_signum);
1969                 else {
1970                         printf("\tkill -%d %d \t\t# %s\n", swork->sw_signum,
1971                             (int)swork->sw_pid, swork->sw_fname);
1972                         if (secs > 0)
1973                                 printf("\tsleep %d\n", secs);
1974                 }
1975                 return;
1976         }
1977
1978         if (swork->sw_runcmd) {
1979                 asprintf(&tmp, "%s %d", swork->sw_fname, swork->sw_signum);
1980                 if (tmp == NULL) {
1981                         warn("can't allocate memory to run %s",
1982                             swork->sw_fname);
1983                         return;
1984                 }
1985                 if (verbose)
1986                         printf("Run command: %s\n", tmp);
1987                 kres = system(tmp);
1988                 if (kres) {
1989                         warnx("%s: returned non-zero exit code: %d",
1990                             tmp, kres);
1991                 }
1992                 free(tmp);
1993                 return;
1994         }
1995
1996         kres = kill(swork->sw_pid, swork->sw_signum);
1997         if (kres != 0) {
1998                 /*
1999                  * Assume that "no such process" (ESRCH) is something
2000                  * to warn about, but is not an error.  Presumably the
2001                  * process which writes to the rotated log file(s) is
2002                  * gone, in which case we should have no problem with
2003                  * compressing the rotated log file(s).
2004                  */
2005                 if (errno != ESRCH)
2006                         swork->sw_pidok = 0;
2007                 warn("can't notify %s, pid %d = %s", swork->sw_pidtype,
2008                     (int)swork->sw_pid, swork->sw_fname);
2009         } else {
2010                 if (verbose)
2011                         printf("Notified %s pid %d = %s\n", swork->sw_pidtype,
2012                             (int)swork->sw_pid, swork->sw_fname);
2013                 if (secs > 0) {
2014                         if (verbose)
2015                                 printf("Pause %d second(s) between signals\n",
2016                                     secs);
2017                         sleep(secs);
2018                 }
2019         }
2020 }
2021
2022 static void
2023 do_zipwork(struct zipwork_entry *zwork)
2024 {
2025         const char *pgm_name, *pgm_path;
2026         int errsav, fcount, zstatus;
2027         pid_t pidzip, wpid;
2028         char zresult[MAXPATHLEN];
2029         char command[BUFSIZ];
2030         char **args;
2031         int c, i, nargs;
2032
2033         assert(zwork != NULL);
2034         pgm_path = NULL;
2035         strlcpy(zresult, zwork->zw_fname, sizeof(zresult));
2036         if (zwork->zw_conf != NULL &&
2037             zwork->zw_conf->compress > COMPRESS_NONE)
2038                 for (c = 1; c < COMPRESS_TYPES; c++) {
2039                         if (zwork->zw_conf->compress == c) {
2040                                 nargs = compress_type[c].nargs;
2041                                 args = calloc(nargs, sizeof(*args));
2042                                 if (args == NULL)
2043                                         err(1, "calloc()");
2044                                 pgm_path = compress_type[c].path;
2045                                 (void) strlcat(zresult,
2046                                     compress_type[c].suffix, sizeof(zresult));
2047                                 /* the first argument is always NULL, skip it */
2048                                 for (i = 1; i < nargs; i++) {
2049                                         if (compress_type[c].args[i] == NULL)
2050                                                 break;
2051                                         args[i] = compress_type[c].args[i];
2052                                 }
2053                                 break;
2054                         }
2055                 }
2056         if (pgm_path == NULL) {
2057                 warnx("invalid entry for %s in do_zipwork", zwork->zw_fname);
2058                 return;
2059         }
2060         pgm_name = strrchr(pgm_path, '/');
2061         if (pgm_name == NULL)
2062                 pgm_name = pgm_path;
2063         else
2064                 pgm_name++;
2065
2066         args[0] = strdup(pgm_name);
2067         if (args[0] == NULL)
2068                 err(1, "strdup()");
2069         for (c = 0; args[c] != NULL; c++)
2070                 ;
2071         args[c] = zwork->zw_fname;
2072
2073         if (zwork->zw_swork != NULL && zwork->zw_swork->sw_runcmd == 0 &&
2074             zwork->zw_swork->sw_pidok <= 0) {
2075                 warnx(
2076                     "log %s not compressed because daemon(s) not notified",
2077                     zwork->zw_fname);
2078                 change_attrs(zwork->zw_fname, zwork->zw_conf);
2079                 return;
2080         }
2081
2082         strlcpy(command, pgm_path, sizeof(command));
2083         for (c = 1; args[c] != NULL; c++) {
2084                 strlcat(command, " ", sizeof(command));
2085                 strlcat(command, args[c], sizeof(command));
2086         }
2087         if (noaction) {
2088                 printf("\t%s %s\n", pgm_name, zwork->zw_fname);
2089                 change_attrs(zresult, zwork->zw_conf);
2090                 return;
2091         }
2092
2093         if (verbose) {
2094                 printf("Executing: %s\n", command);
2095         }
2096         fcount = 1;
2097         pidzip = fork();
2098         while (pidzip < 0) {
2099                 /*
2100                  * The fork failed.  If the failure was due to a temporary
2101                  * problem, then wait a short time and try it again.
2102                  */
2103                 errsav = errno;
2104                 warn("fork() for `%s %s'", pgm_name, zwork->zw_fname);
2105                 if (errsav != EAGAIN || fcount > 5)
2106                         errx(1, "Exiting...");
2107                 sleep(fcount * 12);
2108                 fcount++;
2109                 pidzip = fork();
2110         }
2111         if (!pidzip) {
2112                 /* The child process executes the compression command */
2113                 execv(pgm_path, (char *const*) args);
2114                 err(1, "execv(`%s')", command);
2115         }
2116
2117         wpid = waitpid(pidzip, &zstatus, 0);
2118         if (wpid == -1) {
2119                 /* XXX - should this be a fatal error? */
2120                 warn("%s: waitpid(%d)", pgm_path, pidzip);
2121                 return;
2122         }
2123         if (!WIFEXITED(zstatus)) {
2124                 warnx("`%s' did not terminate normally", command);
2125                 free(args[0]);
2126                 free(args);
2127                 return;
2128         }
2129         if (WEXITSTATUS(zstatus)) {
2130                 warnx("`%s' terminated with a non-zero status (%d)", command,
2131                     WEXITSTATUS(zstatus));
2132                 free(args[0]);
2133                 free(args);
2134                 return;
2135         }
2136
2137         free(args[0]);
2138         free(args);
2139         /* Compression was successful, set file attributes on the result. */
2140         change_attrs(zresult, zwork->zw_conf);
2141 }
2142
2143 /*
2144  * Save information on any process we need to signal.  Any single
2145  * process may need to be sent different signal-values for different
2146  * log files, but usually a single signal-value will cause the process
2147  * to close and re-open all of its log files.
2148  */
2149 static struct sigwork_entry *
2150 save_sigwork(const struct conf_entry *ent)
2151 {
2152         struct sigwork_entry *sprev, *stmp;
2153         int ndiff;
2154         size_t tmpsiz;
2155
2156         sprev = NULL;
2157         ndiff = 1;
2158         SLIST_FOREACH(stmp, &swhead, sw_nextp) {
2159                 ndiff = strcmp(ent->pid_cmd_file, stmp->sw_fname);
2160                 if (ndiff > 0)
2161                         break;
2162                 if (ndiff == 0) {
2163                         if (ent->sig == stmp->sw_signum)
2164                                 break;
2165                         if (ent->sig > stmp->sw_signum) {
2166                                 ndiff = 1;
2167                                 break;
2168                         }
2169                 }
2170                 sprev = stmp;
2171         }
2172         if (stmp != NULL && ndiff == 0)
2173                 return (stmp);
2174
2175         tmpsiz = sizeof(struct sigwork_entry) + strlen(ent->pid_cmd_file) + 1;
2176         stmp = malloc(tmpsiz);
2177
2178         stmp->sw_runcmd = 0;
2179         /* If this is a command to run we just set the flag and run command */
2180         if (ent->flags & CE_PID2CMD) {
2181                 stmp->sw_pid = -1;
2182                 stmp->sw_pidok = 0;
2183                 stmp->sw_runcmd = 1;
2184         } else {
2185                 set_swpid(stmp, ent);
2186         }
2187         stmp->sw_signum = ent->sig;
2188         strcpy(stmp->sw_fname, ent->pid_cmd_file);
2189         if (sprev == NULL)
2190                 SLIST_INSERT_HEAD(&swhead, stmp, sw_nextp);
2191         else
2192                 SLIST_INSERT_AFTER(sprev, stmp, sw_nextp);
2193         return (stmp);
2194 }
2195
2196 /*
2197  * Save information on any file we need to compress.  We may see the same
2198  * file multiple times, so check the full list to avoid duplicates.  The
2199  * list itself is sorted smallest-to-largest, because that's the order we
2200  * want to compress the files.  If the partition is very low on disk space,
2201  * then the smallest files are the most likely to compress, and compressing
2202  * them first will free up more space for the larger files.
2203  */
2204 static struct zipwork_entry *
2205 save_zipwork(const struct conf_entry *ent, const struct sigwork_entry *swork,
2206     int zsize, const char *zipfname)
2207 {
2208         struct zipwork_entry *zprev, *ztmp;
2209         int ndiff;
2210         size_t tmpsiz;
2211
2212         /* Compute the size if the caller did not know it. */
2213         if (zsize < 0)
2214                 zsize = sizefile(zipfname);
2215
2216         zprev = NULL;
2217         ndiff = 1;
2218         SLIST_FOREACH(ztmp, &zwhead, zw_nextp) {
2219                 ndiff = strcmp(zipfname, ztmp->zw_fname);
2220                 if (ndiff == 0)
2221                         break;
2222                 if (zsize > ztmp->zw_fsize)
2223                         zprev = ztmp;
2224         }
2225         if (ztmp != NULL && ndiff == 0)
2226                 return (ztmp);
2227
2228         tmpsiz = sizeof(struct zipwork_entry) + strlen(zipfname) + 1;
2229         ztmp = malloc(tmpsiz);
2230         ztmp->zw_conf = ent;
2231         ztmp->zw_swork = swork;
2232         ztmp->zw_fsize = zsize;
2233         strcpy(ztmp->zw_fname, zipfname);
2234         if (zprev == NULL)
2235                 SLIST_INSERT_HEAD(&zwhead, ztmp, zw_nextp);
2236         else
2237                 SLIST_INSERT_AFTER(zprev, ztmp, zw_nextp);
2238         return (ztmp);
2239 }
2240
2241 /* Send a signal to the pid specified by pidfile */
2242 static void
2243 set_swpid(struct sigwork_entry *swork, const struct conf_entry *ent)
2244 {
2245         FILE *f;
2246         long minok, maxok, rval;
2247         char *endp, *linep, line[BUFSIZ];
2248
2249         minok = MIN_PID;
2250         maxok = MAX_PID;
2251         swork->sw_pidok = 0;
2252         swork->sw_pid = 0;
2253         swork->sw_pidtype = "daemon";
2254         if (ent->flags & CE_SIGNALGROUP) {
2255                 /*
2256                  * If we are expected to signal a process-group when
2257                  * rotating this logfile, then the value read in should
2258                  * be the negative of a valid process ID.
2259                  */
2260                 minok = -MAX_PID;
2261                 maxok = -MIN_PID;
2262                 swork->sw_pidtype = "process-group";
2263         }
2264
2265         f = fopen(ent->pid_cmd_file, "r");
2266         if (f == NULL) {
2267                 if (errno == ENOENT && enforcepid == 0) {
2268                         /*
2269                          * Warn if the PID file doesn't exist, but do
2270                          * not consider it an error.  Most likely it
2271                          * means the process has been terminated,
2272                          * so it should be safe to rotate any log
2273                          * files that the process would have been using.
2274                          */
2275                         swork->sw_pidok = 1;
2276                         warnx("pid file doesn't exist: %s", ent->pid_cmd_file);
2277                 } else
2278                         warn("can't open pid file: %s", ent->pid_cmd_file);
2279                 return;
2280         }
2281
2282         if (fgets(line, BUFSIZ, f) == NULL) {
2283                 /*
2284                  * Warn if the PID file is empty, but do not consider
2285                  * it an error.  Most likely it means the process has
2286                  * has terminated, so it should be safe to rotate any
2287                  * log files that the process would have been using.
2288                  */
2289                 if (feof(f) && enforcepid == 0) {
2290                         swork->sw_pidok = 1;
2291                         warnx("pid/cmd file is empty: %s", ent->pid_cmd_file);
2292                 } else
2293                         warn("can't read from pid file: %s", ent->pid_cmd_file);
2294                 (void)fclose(f);
2295                 return;
2296         }
2297         (void)fclose(f);
2298
2299         errno = 0;
2300         linep = line;
2301         while (*linep == ' ')
2302                 linep++;
2303         rval = strtol(linep, &endp, 10);
2304         if (*endp != '\0' && !isspacech(*endp)) {
2305                 warnx("pid file does not start with a valid number: %s",
2306                     ent->pid_cmd_file);
2307         } else if (rval < minok || rval > maxok) {
2308                 warnx("bad value '%ld' for process number in %s",
2309                     rval, ent->pid_cmd_file);
2310                 if (verbose)
2311                         warnx("\t(expecting value between %ld and %ld)",
2312                             minok, maxok);
2313         } else {
2314                 swork->sw_pidok = 1;
2315                 swork->sw_pid = rval;
2316         }
2317
2318         return;
2319 }
2320
2321 /* Log the fact that the logs were turned over */
2322 static int
2323 log_trim(const char *logname, const struct conf_entry *log_ent)
2324 {
2325         FILE *f;
2326         const char *xtra;
2327
2328         if ((f = fopen(logname, "a")) == NULL)
2329                 return (-1);
2330         xtra = "";
2331         if (log_ent->def_cfg)
2332                 xtra = " using <default> rule";
2333         if (log_ent->flags & CE_RFC5424) {
2334                 if (log_ent->firstcreate) {
2335                         fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s\n",
2336                             LOG_MAKEPRI(LOG_USER, LOG_INFO),
2337                             daytime_rfc5424, hostname, getpid(),
2338                             "logfile first created", xtra);
2339                 } else if (log_ent->r_reason != NULL) {
2340                         fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s%s\n",
2341                             LOG_MAKEPRI(LOG_USER, LOG_INFO),
2342                             daytime_rfc5424, hostname, getpid(),
2343                             "logfile turned over", log_ent->r_reason, xtra);
2344                 } else {
2345                         fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s\n",
2346                             LOG_MAKEPRI(LOG_USER, LOG_INFO),
2347                             daytime_rfc5424, hostname, getpid(),
2348                             "logfile turned over", xtra);
2349                 }
2350         } else {
2351                 if (log_ent->firstcreate)
2352                         fprintf(f,
2353                             "%s %.*s newsyslog[%d]: logfile first created%s\n",
2354                             daytime, (int)hostname_shortlen, hostname, getpid(),
2355                             xtra);
2356                 else if (log_ent->r_reason != NULL)
2357                         fprintf(f,
2358                             "%s %.*s newsyslog[%d]: logfile turned over%s%s\n",
2359                             daytime, (int)hostname_shortlen, hostname, getpid(),
2360                             log_ent->r_reason, xtra);
2361                 else
2362                         fprintf(f,
2363                             "%s %.*s newsyslog[%d]: logfile turned over%s\n",
2364                             daytime, (int)hostname_shortlen, hostname, getpid(),
2365                             xtra);
2366         }
2367         if (fclose(f) == EOF)
2368                 err(1, "log_trim: fclose");
2369         return (0);
2370 }
2371
2372 /* Return size in kilobytes of a file */
2373 static int
2374 sizefile(const char *file)
2375 {
2376         struct stat sb;
2377
2378         if (stat(file, &sb) < 0)
2379                 return (-1);
2380         return (kbytes(sb.st_size));
2381 }
2382
2383 /*
2384  * Return the mtime of the most recent archive of the logfile, using timestamp
2385  * based filenames.
2386  */
2387 static time_t
2388 mtime_old_timelog(const char *file)
2389 {
2390         struct stat sb;
2391         struct tm tm;
2392         int dir_fd;
2393         time_t t;
2394         struct dirent *dp;
2395         DIR *dirp;
2396         char *logfname, *logfnamebuf, *dir, *dirbuf;
2397
2398         t = -1;
2399
2400         if ((dirbuf = strdup(file)) == NULL) {
2401                 warn("strdup() of '%s'", file);
2402                 return (t);
2403         }
2404         dir = dirname(dirbuf);
2405         if ((logfnamebuf = strdup(file)) == NULL) {
2406                 warn("strdup() of '%s'", file);
2407                 free(dirbuf);
2408                 return (t);
2409         }
2410         logfname = basename(logfnamebuf);
2411         if (logfname[0] == '/') {
2412                 warnx("Invalid log filename '%s'", logfname);
2413                 goto out;
2414         }
2415
2416         if ((dirp = opendir(dir)) == NULL) {
2417                 warn("Cannot open log directory '%s'", dir);
2418                 goto out;
2419         }
2420         dir_fd = dirfd(dirp);
2421         /* Open the archive dir and find the most recent archive of logfname. */
2422         while ((dp = readdir(dirp)) != NULL) {
2423                 if (validate_old_timelog(dir_fd, dp, logfname, &tm) == 0)
2424                         continue;
2425
2426                 if (fstatat(dir_fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
2427                         warn("Cannot stat '%s'", file);
2428                         continue;
2429                 }
2430                 if (t < sb.st_mtime)
2431                         t = sb.st_mtime;
2432         }
2433         closedir(dirp);
2434
2435 out:
2436         free(dirbuf);
2437         free(logfnamebuf);
2438         return (t);
2439 }
2440
2441 /* Return the age in hours of the most recent archive of the logfile. */
2442 static int
2443 age_old_log(const char *file)
2444 {
2445         struct stat sb;
2446         const char *logfile_suffix;
2447         char tmp[MAXPATHLEN + sizeof(".0") + COMPRESS_SUFFIX_MAXLEN + 1];
2448         time_t mtime;
2449
2450         if (archtodir) {
2451                 char *p;
2452
2453                 /* build name of archive directory into tmp */
2454                 if (*archdirname == '/') {      /* absolute */
2455                         strlcpy(tmp, archdirname, sizeof(tmp));
2456                 } else {        /* relative */
2457                         /* get directory part of logfile */
2458                         strlcpy(tmp, file, sizeof(tmp));
2459                         if ((p = strrchr(tmp, '/')) == NULL)
2460                                 tmp[0] = '\0';
2461                         else
2462                                 *(p + 1) = '\0';
2463                         strlcat(tmp, archdirname, sizeof(tmp));
2464                 }
2465
2466                 strlcat(tmp, "/", sizeof(tmp));
2467
2468                 /* get filename part of logfile */
2469                 if ((p = strrchr(file, '/')) == NULL)
2470                         strlcat(tmp, file, sizeof(tmp));
2471                 else
2472                         strlcat(tmp, p + 1, sizeof(tmp));
2473         } else {
2474                 (void) strlcpy(tmp, file, sizeof(tmp));
2475         }
2476
2477         if (timefnamefmt != NULL) {
2478                 mtime = mtime_old_timelog(tmp);
2479                 if (mtime == -1)
2480                         return (-1);
2481         } else {
2482                 strlcat(tmp, ".0", sizeof(tmp));
2483                 logfile_suffix = get_logfile_suffix(tmp);
2484                 if (logfile_suffix == NULL)
2485                         return (-1);
2486                 (void) strlcat(tmp, logfile_suffix, sizeof(tmp));
2487                 if (stat(tmp, &sb) < 0)
2488                         return (-1);
2489                 mtime = sb.st_mtime;
2490         }
2491
2492         return ((int)(ptimeget_secs(timenow) - mtime + 1800) / 3600);
2493 }
2494
2495 /* Skip Over Blanks */
2496 static char *
2497 sob(char *p)
2498 {
2499         while (p && *p && isspace(*p))
2500                 p++;
2501         return (p);
2502 }
2503
2504 /* Skip Over Non-Blanks */
2505 static char *
2506 son(char *p)
2507 {
2508         while (p && *p && !isspace(*p))
2509                 p++;
2510         return (p);
2511 }
2512
2513 /* Check if string is actually a number */
2514 static int
2515 isnumberstr(const char *string)
2516 {
2517         while (*string) {
2518                 if (!isdigitch(*string++))
2519                         return (0);
2520         }
2521         return (1);
2522 }
2523
2524 /* Check if string contains a glob */
2525 static int
2526 isglobstr(const char *string)
2527 {
2528         char chr;
2529
2530         while ((chr = *string++)) {
2531                 if (chr == '*' || chr == '?' || chr == '[')
2532                         return (1);
2533         }
2534         return (0);
2535 }
2536
2537 /*
2538  * Save the active log file under a new name.  A link to the new name
2539  * is the quick-and-easy way to do this.  If that fails (which it will
2540  * if the destination is on another partition), then make a copy of
2541  * the file to the new location.
2542  */
2543 static void
2544 savelog(char *from, char *to)
2545 {
2546         FILE *src, *dst;
2547         int c, res;
2548
2549         res = link(from, to);
2550         if (res == 0)
2551                 return;
2552
2553         if ((src = fopen(from, "r")) == NULL)
2554                 err(1, "can't fopen %s for reading", from);
2555         if ((dst = fopen(to, "w")) == NULL)
2556                 err(1, "can't fopen %s for writing", to);
2557
2558         while ((c = getc(src)) != EOF) {
2559                 if ((putc(c, dst)) == EOF)
2560                         err(1, "error writing to %s", to);
2561         }
2562
2563         if (ferror(src))
2564                 err(1, "error reading from %s", from);
2565         if ((fclose(src)) != 0)
2566                 err(1, "can't fclose %s", to);
2567         if ((fclose(dst)) != 0)
2568                 err(1, "can't fclose %s", from);
2569 }
2570
2571 /* create one or more directory components of a path */
2572 static void
2573 createdir(const struct conf_entry *ent, char *dirpart)
2574 {
2575         int res;
2576         char *s, *d;
2577         char mkdirpath[MAXPATHLEN];
2578         struct stat st;
2579
2580         s = dirpart;
2581         d = mkdirpath;
2582
2583         for (;;) {
2584                 *d++ = *s++;
2585                 if (*s != '/' && *s != '\0')
2586                         continue;
2587                 *d = '\0';
2588                 res = lstat(mkdirpath, &st);
2589                 if (res != 0) {
2590                         if (noaction) {
2591                                 printf("\tmkdir %s\n", mkdirpath);
2592                         } else {
2593                                 res = mkdir(mkdirpath, 0755);
2594                                 if (res != 0)
2595                                         err(1, "Error on mkdir(\"%s\") for -a",
2596                                             mkdirpath);
2597                         }
2598                 }
2599                 if (*s == '\0')
2600                         break;
2601         }
2602         if (verbose) {
2603                 if (ent->firstcreate)
2604                         printf("Created directory '%s' for new %s\n",
2605                             dirpart, ent->log);
2606                 else
2607                         printf("Created directory '%s' for -a\n", dirpart);
2608         }
2609 }
2610
2611 /*
2612  * Create a new log file, destroying any currently-existing version
2613  * of the log file in the process.  If the caller wants a backup copy
2614  * of the file to exist, they should call 'link(logfile,logbackup)'
2615  * before calling this routine.
2616  */
2617 void
2618 createlog(const struct conf_entry *ent)
2619 {
2620         int fd, failed;
2621         struct stat st;
2622         char *realfile, *slash, tempfile[MAXPATHLEN];
2623
2624         fd = -1;
2625         realfile = ent->log;
2626
2627         /*
2628          * If this log file is being created for the first time (-C option),
2629          * then it may also be true that the parent directory does not exist
2630          * yet.  Check, and create that directory if it is missing.
2631          */
2632         if (ent->firstcreate) {
2633                 strlcpy(tempfile, realfile, sizeof(tempfile));
2634                 slash = strrchr(tempfile, '/');
2635                 if (slash != NULL) {
2636                         *slash = '\0';
2637                         failed = stat(tempfile, &st);
2638                         if (failed && errno != ENOENT)
2639                                 err(1, "Error on stat(%s)", tempfile);
2640                         if (failed)
2641                                 createdir(ent, tempfile);
2642                         else if (!S_ISDIR(st.st_mode))
2643                                 errx(1, "%s exists but is not a directory",
2644                                     tempfile);
2645                 }
2646         }
2647
2648         /*
2649          * First create an unused filename, so it can be chown'ed and
2650          * chmod'ed before it is moved into the real location.  mkstemp
2651          * will create the file mode=600 & owned by us.  Note that all
2652          * temp files will have a suffix of '.z<something>'.
2653          */
2654         strlcpy(tempfile, realfile, sizeof(tempfile));
2655         strlcat(tempfile, ".zXXXXXX", sizeof(tempfile));
2656         if (noaction)
2657                 printf("\tmktemp %s\n", tempfile);
2658         else {
2659                 fd = mkstemp(tempfile);
2660                 if (fd < 0)
2661                         err(1, "can't mkstemp logfile %s", tempfile);
2662
2663                 /*
2664                  * Add status message to what will become the new log file.
2665                  */
2666                 if (!(ent->flags & CE_BINARY)) {
2667                         if (log_trim(tempfile, ent))
2668                                 err(1, "can't add status message to log");
2669                 }
2670         }
2671
2672         /* Change the owner/group, if we are supposed to */
2673         if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2674                 if (noaction)
2675                         printf("\tchown %u:%u %s\n", ent->uid, ent->gid,
2676                             tempfile);
2677                 else {
2678                         failed = fchown(fd, ent->uid, ent->gid);
2679                         if (failed)
2680                                 err(1, "can't fchown temp file %s", tempfile);
2681                 }
2682         }
2683
2684         /* Turn on NODUMP if it was requested in the config-file. */
2685         if (ent->flags & CE_NODUMP) {
2686                 if (noaction)
2687                         printf("\tchflags nodump %s\n", tempfile);
2688                 else {
2689                         failed = fchflags(fd, UF_NODUMP);
2690                         if (failed) {
2691                                 warn("log_trim: fchflags(NODUMP)");
2692                         }
2693                 }
2694         }
2695
2696         /*
2697          * Note that if the real logfile still exists, and if the call
2698          * to rename() fails, then "neither the old file nor the new
2699          * file shall be changed or created" (to quote the standard).
2700          * If the call succeeds, then the file will be replaced without
2701          * any window where some other process might find that the file
2702          * did not exist.
2703          * XXX - ? It may be that for some error conditions, we could
2704          *      retry by first removing the realfile and then renaming.
2705          */
2706         if (noaction) {
2707                 printf("\tchmod %o %s\n", ent->permissions, tempfile);
2708                 printf("\tmv %s %s\n", tempfile, realfile);
2709         } else {
2710                 failed = fchmod(fd, ent->permissions);
2711                 if (failed)
2712                         err(1, "can't fchmod temp file '%s'", tempfile);
2713                 failed = rename(tempfile, realfile);
2714                 if (failed)
2715                         err(1, "can't mv %s to %s", tempfile, realfile);
2716         }
2717
2718         if (fd >= 0)
2719                 close(fd);
2720 }
2721
2722 /*
2723  * Change the attributes of a given filename to what was specified in
2724  * the newsyslog.conf entry.  This routine is only called for files
2725  * that newsyslog expects that it has created, and thus it is a fatal
2726  * error if this routine finds that the file does not exist.
2727  */
2728 static void
2729 change_attrs(const char *fname, const struct conf_entry *ent)
2730 {
2731         int failed;
2732
2733         if (noaction) {
2734                 printf("\tchmod %o %s\n", ent->permissions, fname);
2735
2736                 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
2737                         printf("\tchown %u:%u %s\n",
2738                             ent->uid, ent->gid, fname);
2739
2740                 if (ent->flags & CE_NODUMP)
2741                         printf("\tchflags nodump %s\n", fname);
2742                 return;
2743         }
2744
2745         failed = chmod(fname, ent->permissions);
2746         if (failed) {
2747                 if (errno != EPERM)
2748                         err(1, "chmod(%s) in change_attrs", fname);
2749                 warn("change_attrs couldn't chmod(%s)", fname);
2750         }
2751
2752         if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2753                 failed = chown(fname, ent->uid, ent->gid);
2754                 if (failed)
2755                         warn("can't chown %s", fname);
2756         }
2757
2758         if (ent->flags & CE_NODUMP) {
2759                 failed = chflags(fname, UF_NODUMP);
2760                 if (failed)
2761                         warn("can't chflags %s NODUMP", fname);
2762         }
2763 }
2764
2765 /*
2766  * Parse a signal number or signal name. Returns the signal number parsed or -1
2767  * on failure.
2768  */
2769 static int
2770 parse_signal(const char *str)
2771 {
2772         int sig, i;
2773         const char *errstr;
2774
2775         sig = strtonum(str, 1, sys_nsig - 1, &errstr);
2776
2777         if (errstr == NULL)
2778                 return (sig);
2779         if (strncasecmp(str, "SIG", 3) == 0)
2780                 str += 3;
2781
2782         for (i = 1; i < sys_nsig; i++) {
2783                 if (strcasecmp(str, sys_signame[i]) == 0)
2784                         return (i);
2785         }
2786
2787         return (-1);
2788 }