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