newsyslog - Signal result checking unneeded
[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 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 SLIST_HEAD(swlisthead, sigwork_entry) swhead = SLIST_HEAD_INITIALIZER(swhead);
209 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 int archtodir = 0;              /* Archive old logfiles to other directory */
215 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 int needroot = 1;               /* Root privs are necessary */
220 int noaction = 0;               /* Don't do anything, just show it */
221 int norotate = 0;               /* Don't rotate */
222 int nosignal;                   /* Do not send any signals */
223 int enforcepid = 0;             /* If PID file does not exist or empty, do nothing */
224 int force = 0;                  /* Force the trim no matter what */
225 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 char *requestor;                /* The name given on a -R request */
230 char *timefnamefmt = NULL;      /* Use time based filenames instead of .0 etc */
231 char *archdirname;              /* Directory path to old logfiles archive */
232 char *destdir = NULL;           /* Directory to treat at root for logs */
233 const char *conf;               /* Configuration file to use */
234
235 struct ptime_data *dbg_timenow; /* A "timenow" value set via -D option */
236 struct ptime_data *timenow;     /* The time to use for checking at-fields */
237
238 #define DAYTIME_LEN     16
239 char daytime[DAYTIME_LEN];      /* The current time in human readable form,
240                                  * used for rotation-tracking messages. */
241 char hostname[MAXHOSTNAMELEN];  /* hostname */
242
243 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                         break;
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                 } else {
1815                         if (!(flags & CE_BINARY)) {
1816                                 /* Report the trimming to the old log */
1817                                 log_trim(ent->log, ent);
1818                         }
1819                         savelog(ent->log, file1);
1820                 }
1821                 change_attrs(file1, ent);
1822         }
1823
1824         /* Create the new log file and move it into place */
1825         if (noaction)
1826                 printf("Start new log...\n");
1827         createlog(ent);
1828
1829         /*
1830          * Save all signalling and file-compression to be done after log
1831          * files from all entries have been rotated.  This way any one
1832          * process will not be sent the same signal multiple times when
1833          * multiple log files had to be rotated.
1834          */
1835         swork = NULL;
1836         if (ent->pid_cmd_file != NULL)
1837                 swork = save_sigwork(ent);
1838         if (ent->numlogs > 0 && ent->compress > COMPRESS_NONE) {
1839                 /*
1840                  * The zipwork_entry will include a pointer to this
1841                  * conf_entry, so the conf_entry should not be freed.
1842                  */
1843                 free_or_keep = KEEP_ENT;
1844                 save_zipwork(ent, swork, ent->fsize, file1);
1845         }
1846
1847         return (free_or_keep);
1848 }
1849
1850 static void
1851 do_sigwork(struct sigwork_entry *swork)
1852 {
1853         struct sigwork_entry *nextsig;
1854         int kres, secs;
1855         char *tmp;
1856
1857         if (!(swork->sw_pidok) || swork->sw_pid == 0)
1858                 return;                 /* no work to do... */
1859
1860         /*
1861          * If nosignal (-s) was specified, then do not signal any process.
1862          * Note that a nosignal request triggers a warning message if the
1863          * rotated logfile needs to be compressed, *unless* -R was also
1864          * specified.  We assume that an `-sR' request came from a process
1865          * which writes to the logfile, and as such, we assume that process
1866          * has already made sure the logfile is not presently in use.  This
1867          * just sets swork->sw_pidok to a special value, and do_zipwork
1868          * will print any necessary warning(s).
1869          */
1870         if (nosignal) {
1871                 if (!rotatereq)
1872                         swork->sw_pidok = -1;
1873                 return;
1874         }
1875
1876         /*
1877          * Compute the pause between consecutive signals.  Use a longer
1878          * sleep time if we will be sending two signals to the same
1879          * deamon or process-group.
1880          */
1881         secs = 0;
1882         nextsig = SLIST_NEXT(swork, sw_nextp);
1883         if (nextsig != NULL) {
1884                 if (swork->sw_pid == nextsig->sw_pid)
1885                         secs = 10;
1886                 else
1887                         secs = 1;
1888         }
1889
1890         if (noaction) {
1891                 printf("\tkill -%d %d \t\t# %s\n", swork->sw_signum,
1892                     (int)swork->sw_pid, swork->sw_fname);
1893                 if (secs > 0)
1894                         printf("\tsleep %d\n", secs);
1895                 return;
1896         }
1897
1898         if (swork->run_cmd) {
1899                 asprintf(&tmp, "%s %d", swork->sw_fname, swork->sw_signum);
1900                 if (tmp == NULL) {
1901                         warn("can't allocate memory to run %s",
1902                             swork->sw_fname);
1903                         return;
1904                 }
1905                 if (verbose)
1906                         printf("Run command: %s\n", tmp);
1907                 kres = system(tmp);
1908                 if (kres) {
1909                         warnx("%s: returned non-zero exit code: %d",
1910                             tmp, kres);
1911                 }
1912                 free(tmp);
1913                 return;
1914         }
1915
1916         kres = kill(swork->sw_pid, swork->sw_signum);
1917         if (kres != 0) {
1918                 /*
1919                  * Assume that "no such process" (ESRCH) is something
1920                  * to warn about, but is not an error.  Presumably the
1921                  * process which writes to the rotated log file(s) is
1922                  * gone, in which case we should have no problem with
1923                  * compressing the rotated log file(s).
1924                  */
1925                 if (errno != ESRCH)
1926                         swork->sw_pidok = 0;
1927                 warn("can't notify %s, pid %d", swork->sw_pidtype,
1928                     (int)swork->sw_pid);
1929         } else {
1930                 if (verbose)
1931                         printf("Notified %s pid %d = %s\n", swork->sw_pidtype,
1932                             (int)swork->sw_pid, swork->sw_fname);
1933                 if (secs > 0) {
1934                         if (verbose)
1935                                 printf("Pause %d second(s) between signals\n",
1936                                     secs);
1937                         sleep(secs);
1938                 }
1939         }
1940 }
1941
1942 static void
1943 do_zipwork(struct zipwork_entry *zwork)
1944 {
1945         const char *pgm_name, *pgm_path;
1946         int errsav, fcount, zstatus;
1947         pid_t pidzip, wpid;
1948         char zresult[MAXPATHLEN];
1949         int c;
1950
1951         assert(zwork != NULL);
1952         pgm_path = NULL;
1953         strlcpy(zresult, zwork->zw_fname, sizeof(zresult));
1954         if (zwork->zw_conf != NULL &&
1955             zwork->zw_conf->compress > COMPRESS_NONE)
1956                 for (c = 1; c < COMPRESS_TYPES; c++) {
1957                         if (zwork->zw_conf->compress == c) {
1958                                 pgm_path = compress_type[c].path;
1959                                 strlcat(zresult,
1960                                     compress_type[c].suffix, sizeof(zresult));
1961                                 break;
1962                         }
1963                 }
1964         if (pgm_path == NULL) {
1965                 warnx("invalid entry for %s in do_zipwork", zwork->zw_fname);
1966                 return;
1967         }
1968         pgm_name = strrchr(pgm_path, '/');
1969         if (pgm_name == NULL)
1970                 pgm_name = pgm_path;
1971         else
1972                 pgm_name++;
1973
1974
1975         if (zwork->zw_swork != NULL && zwork->zw_swork->run_cmd == 0 &&
1976             zwork->zw_swork->sw_pidok <= 0) {
1977                 warnx(
1978                     "log %s not compressed because daemon(s) not notified",
1979                     zwork->zw_fname);
1980                 change_attrs(zwork->zw_fname, zwork->zw_conf);
1981                 return;
1982         }
1983
1984         if (noaction) {
1985                 printf("\t%s %s\n", pgm_name, zwork->zw_fname);
1986                 change_attrs(zresult, zwork->zw_conf);
1987                 return;
1988         }
1989
1990         fcount = 1;
1991         pidzip = fork();
1992         while (pidzip < 0) {
1993                 /*
1994                  * The fork failed.  If the failure was due to a temporary
1995                  * problem, then wait a short time and try it again.
1996                  */
1997                 errsav = errno;
1998                 warn("fork() for `%s %s'", pgm_name, zwork->zw_fname);
1999                 if (errsav != EAGAIN || fcount > 5)
2000                         errx(1, "Exiting...");
2001                 sleep(fcount * 12);
2002                 fcount++;
2003                 pidzip = fork();
2004         }
2005         if (!pidzip) {
2006                 /* The child process executes the compression command */
2007                 execl(pgm_path, pgm_path, "-f", zwork->zw_fname, NULL);
2008                 err(1, "execl(`%s -f %s')", pgm_path, zwork->zw_fname);
2009         }
2010
2011         wpid = waitpid(pidzip, &zstatus, 0);
2012         if (wpid == -1) {
2013                 /* XXX - should this be a fatal error? */
2014                 warn("%s: waitpid(%d)", pgm_path, pidzip);
2015                 return;
2016         }
2017         if (!WIFEXITED(zstatus)) {
2018                 warnx("`%s -f %s' did not terminate normally", pgm_name,
2019                     zwork->zw_fname);
2020                 return;
2021         }
2022         if (WEXITSTATUS(zstatus)) {
2023                 warnx("`%s -f %s' terminated with a non-zero status (%d)",
2024                     pgm_name, zwork->zw_fname, WEXITSTATUS(zstatus));
2025                 return;
2026         }
2027
2028         /* Compression was successful, set file attributes on the result. */
2029         change_attrs(zresult, zwork->zw_conf);
2030 }
2031
2032 /*
2033  * Save information on any process we need to signal.  Any single
2034  * process may need to be sent different signal-values for different
2035  * log files, but usually a single signal-value will cause the process
2036  * to close and re-open all of it's log files.
2037  */
2038 static struct sigwork_entry *
2039 save_sigwork(const struct conf_entry *ent)
2040 {
2041         struct sigwork_entry *sprev, *stmp;
2042         int ndiff;
2043         size_t tmpsiz;
2044
2045         sprev = NULL;
2046         ndiff = 1;
2047         SLIST_FOREACH(stmp, &swhead, sw_nextp) {
2048                 ndiff = strcmp(ent->pid_cmd_file, stmp->sw_fname);
2049                 if (ndiff > 0)
2050                         break;
2051                 if (ndiff == 0) {
2052                         if (ent->sig == stmp->sw_signum)
2053                                 break;
2054                         if (ent->sig > stmp->sw_signum) {
2055                                 ndiff = 1;
2056                                 break;
2057                         }
2058                 }
2059                 sprev = stmp;
2060         }
2061         if (stmp != NULL && ndiff == 0)
2062                 return (stmp);
2063
2064         tmpsiz = sizeof(struct sigwork_entry) + strlen(ent->pid_cmd_file) + 1;
2065         stmp = malloc(tmpsiz);
2066
2067         stmp->run_cmd = 0;
2068         /* If this is a command to run we just set the flag and run command */
2069         if (ent->flags & CE_PID2CMD) {
2070                 stmp->run_cmd = 1;
2071         } else {
2072                 set_swpid(stmp, ent);
2073         }
2074         stmp->sw_signum = ent->sig;
2075         strcpy(stmp->sw_fname, ent->pid_cmd_file);
2076         if (sprev == NULL)
2077                 SLIST_INSERT_HEAD(&swhead, stmp, sw_nextp);
2078         else
2079                 SLIST_INSERT_AFTER(sprev, stmp, sw_nextp);
2080         return (stmp);
2081 }
2082
2083 /*
2084  * Save information on any file we need to compress.  We may see the same
2085  * file multiple times, so check the full list to avoid duplicates.  The
2086  * list itself is sorted smallest-to-largest, because that's the order we
2087  * want to compress the files.  If the partition is very low on disk space,
2088  * then the smallest files are the most likely to compress, and compressing
2089  * them first will free up more space for the larger files.
2090  */
2091 static struct zipwork_entry *
2092 save_zipwork(const struct conf_entry *ent, const struct sigwork_entry *swork,
2093     int zsize, const char *zipfname)
2094 {
2095         struct zipwork_entry *zprev, *ztmp;
2096         int ndiff;
2097         size_t tmpsiz;
2098
2099         /* Compute the size if the caller did not know it. */
2100         if (zsize < 0)
2101                 zsize = sizefile(zipfname);
2102
2103         zprev = NULL;
2104         ndiff = 1;
2105         SLIST_FOREACH(ztmp, &zwhead, zw_nextp) {
2106                 ndiff = strcmp(zipfname, ztmp->zw_fname);
2107                 if (ndiff == 0)
2108                         break;
2109                 if (zsize > ztmp->zw_fsize)
2110                         zprev = ztmp;
2111         }
2112         if (ztmp != NULL && ndiff == 0)
2113                 return (ztmp);
2114
2115         tmpsiz = sizeof(struct zipwork_entry) + strlen(zipfname) + 1;
2116         ztmp = malloc(tmpsiz);
2117         ztmp->zw_conf = ent;
2118         ztmp->zw_swork = swork;
2119         ztmp->zw_fsize = zsize;
2120         strcpy(ztmp->zw_fname, zipfname);
2121         if (zprev == NULL)
2122                 SLIST_INSERT_HEAD(&zwhead, ztmp, zw_nextp);
2123         else
2124                 SLIST_INSERT_AFTER(zprev, ztmp, zw_nextp);
2125         return (ztmp);
2126 }
2127
2128 /* Send a signal to the pid specified by pidfile */
2129 static void
2130 set_swpid(struct sigwork_entry *swork, const struct conf_entry *ent)
2131 {
2132         FILE *f;
2133         long minok, maxok, rval;
2134         char *endp, *linep, line[BUFSIZ];
2135
2136         minok = MIN_PID;
2137         maxok = MAX_PID;
2138         swork->sw_pidok = 0;
2139         swork->sw_pid = 0;
2140         swork->sw_pidtype = "daemon";
2141         if (ent->flags & CE_SIGNALGROUP) {
2142                 /*
2143                  * If we are expected to signal a process-group when
2144                  * rotating this logfile, then the value read in should
2145                  * be the negative of a valid process ID.
2146                  */
2147                 minok = -MAX_PID;
2148                 maxok = -MIN_PID;
2149                 swork->sw_pidtype = "process-group";
2150         }
2151
2152         f = fopen(ent->pid_cmd_file, "r");
2153         if (f == NULL) {
2154                 if (errno == ENOENT && enforcepid == 0) {
2155                         /*
2156                          * Warn if the PID file doesn't exist, but do
2157                          * not consider it an error.  Most likely it
2158                          * means the process has been terminated,
2159                          * so it should be safe to rotate any log
2160                          * files that the process would have been using.
2161                          */
2162                         swork->sw_pidok = 1;
2163                         warnx("pid file doesn't exist: %s", ent->pid_cmd_file);
2164                 } else
2165                         warn("can't open pid file: %s", ent->pid_cmd_file);
2166                 return;
2167         }
2168
2169         if (fgets(line, BUFSIZ, f) == NULL) {
2170                 /*
2171                  * Warn if the PID file is empty, but do not consider
2172                  * it an error.  Most likely it means the process has
2173                  * has terminated, so it should be safe to rotate any
2174                  * log files that the process would have been using.
2175                  */
2176                 if (feof(f) && enforcepid == 0) {
2177                         swork->sw_pidok = 1;
2178                         warnx("pid/cmd file is empty: %s", ent->pid_cmd_file);
2179                 } else
2180                         warn("can't read from pid file: %s", ent->pid_cmd_file);
2181
2182                 fclose(f);
2183                 return;
2184         }
2185         fclose(f);
2186
2187         errno = 0;
2188         linep = line;
2189         while (*linep == ' ')
2190                 linep++;
2191         rval = strtol(linep, &endp, 10);
2192         if (*endp != '\0' && !isspacech(*endp)) {
2193                 warnx("pid file does not start with a valid number: %s",
2194                     ent->pid_cmd_file);
2195         } else if (rval < minok || rval > maxok) {
2196                 warnx("bad value '%ld' for process number in %s",
2197                     rval, ent->pid_cmd_file);
2198                 if (verbose)
2199                         warnx("\t(expecting value between %ld and %ld)",
2200                             minok, maxok);
2201         } else {
2202                 swork->sw_pidok = 1;
2203                 swork->sw_pid = rval;
2204         }
2205
2206         return;
2207 }
2208
2209 /* Log the fact that the logs were turned over */
2210 static int
2211 log_trim(const char *logname, const struct conf_entry *log_ent)
2212 {
2213         FILE *f;
2214         const char *xtra;
2215
2216         if ((f = fopen(logname, "a")) == NULL)
2217                 return (-1);
2218         xtra = "";
2219         if (log_ent->def_cfg)
2220                 xtra = " using <default> rule";
2221         if (log_ent->firstcreate)
2222                 fprintf(f, "%s %s newsyslog[%d]: logfile first created%s\n",
2223                     daytime, hostname, (int) getpid(), xtra);
2224         else if (log_ent->r_reason != NULL)
2225                 fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s%s\n",
2226                     daytime, hostname, (int) getpid(), log_ent->r_reason, xtra);
2227         else
2228                 fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s\n",
2229                     daytime, hostname, (int) getpid(), xtra);
2230         if (fclose(f) == EOF)
2231                 err(1, "log_trim: fclose");
2232         return (0);
2233 }
2234
2235 /* Return size in kilobytes of a file */
2236 static int
2237 sizefile(const char *file)
2238 {
2239         struct stat sb;
2240
2241         if (stat(file, &sb) < 0)
2242                 return (-1);
2243         return (kbytes(sb.st_size));
2244 }
2245
2246 /* Return the age of old log file (file.0) */
2247 static int
2248 age_old_log(char *file)
2249 {
2250         struct stat sb;
2251         const char *logfile_suffix;
2252         char tmp[MAXPATHLEN + sizeof(".0") + COMPRESS_SUFFIX_MAXLEN + 1];
2253
2254         if (archtodir) {
2255                 char *p;
2256
2257                 /* build name of archive directory into tmp */
2258                 if (*archdirname == '/') {      /* absolute */
2259                         strlcpy(tmp, archdirname, sizeof(tmp));
2260                 } else {        /* relative */
2261                         /* get directory part of logfile */
2262                         strlcpy(tmp, file, sizeof(tmp));
2263                         if ((p = strrchr(tmp, '/')) == NULL)
2264                                 tmp[0] = '\0';
2265                         else
2266                                 *(p + 1) = '\0';
2267                         strlcat(tmp, archdirname, sizeof(tmp));
2268                 }
2269
2270                 strlcat(tmp, "/", sizeof(tmp));
2271
2272                 /* get filename part of logfile */
2273                 if ((p = strrchr(file, '/')) == NULL)
2274                         strlcat(tmp, file, sizeof(tmp));
2275                 else
2276                         strlcat(tmp, p + 1, sizeof(tmp));
2277         } else {
2278                 strlcpy(tmp, file, sizeof(tmp));
2279         }
2280
2281         strlcat(tmp, ".0", sizeof(tmp));
2282         logfile_suffix = get_logfile_suffix(tmp);
2283         if (logfile_suffix == NULL)
2284                 return (-1);
2285         strlcat(tmp, logfile_suffix, sizeof(tmp));
2286         if (stat(tmp, &sb) < 0)
2287                 return (-1);
2288         return ((int)(ptimeget_secs(timenow) - sb.st_mtime + 1800) / 3600);
2289 }
2290
2291 /* Skip Over Blanks */
2292 static char *
2293 sob(char *p)
2294 {
2295         while (p && *p && isspace(*p))
2296                 p++;
2297         return (p);
2298 }
2299
2300 /* Skip Over Non-Blanks */
2301 static char *
2302 son(char *p)
2303 {
2304         while (p && *p && !isspace(*p))
2305                 p++;
2306         return (p);
2307 }
2308
2309 /* Check if string is actually a number */
2310 static int
2311 isnumberstr(const char *string)
2312 {
2313         while (*string) {
2314                 if (!isdigitch(*string++))
2315                         return (0);
2316         }
2317         return (1);
2318 }
2319
2320 /* Check if string contains a glob */
2321 static int
2322 isglobstr(const char *string)
2323 {
2324         char chr;
2325
2326         while ((chr = *string++)) {
2327                 if (chr == '*' || chr == '?' || chr == '[')
2328                         return (1);
2329         }
2330         return (0);
2331 }
2332
2333 /*
2334  * Save the active log file under a new name.  A link to the new name
2335  * is the quick-and-easy way to do this.  If that fails (which it will
2336  * if the destination is on another partition), then make a copy of
2337  * the file to the new location.
2338  */
2339 static void
2340 savelog(char *from, char *to)
2341 {
2342         FILE *src, *dst;
2343         int c, res;
2344
2345         res = link(from, to);
2346         if (res == 0)
2347                 return;
2348
2349         if ((src = fopen(from, "r")) == NULL)
2350                 err(1, "can't fopen %s for reading", from);
2351         if ((dst = fopen(to, "w")) == NULL)
2352                 err(1, "can't fopen %s for writing", to);
2353
2354         while ((c = getc(src)) != EOF) {
2355                 if ((putc(c, dst)) == EOF)
2356                         err(1, "error writing to %s", to);
2357         }
2358
2359         if (ferror(src))
2360                 err(1, "error reading from %s", from);
2361         if ((fclose(src)) != 0)
2362                 err(1, "can't fclose %s", to);
2363         if ((fclose(dst)) != 0)
2364                 err(1, "can't fclose %s", from);
2365 }
2366
2367 /* create one or more directory components of a path */
2368 static void
2369 createdir(const struct conf_entry *ent, char *dirpart)
2370 {
2371         int res;
2372         char *s, *d;
2373         char mkdirpath[MAXPATHLEN];
2374         struct stat st;
2375
2376         s = dirpart;
2377         d = mkdirpath;
2378
2379         for (;;) {
2380                 *d++ = *s++;
2381                 if (*s != '/' && *s != '\0')
2382                         continue;
2383                 *d = '\0';
2384                 res = lstat(mkdirpath, &st);
2385                 if (res != 0) {
2386                         if (noaction) {
2387                                 printf("\tmkdir %s\n", mkdirpath);
2388                         } else {
2389                                 res = mkdir(mkdirpath, 0755);
2390                                 if (res != 0)
2391                                         err(1, "Error on mkdir(\"%s\") for -a",
2392                                             mkdirpath);
2393                         }
2394                 }
2395                 if (*s == '\0')
2396                         break;
2397         }
2398         if (verbose) {
2399                 if (ent->firstcreate)
2400                         printf("Created directory '%s' for new %s\n",
2401                             dirpart, ent->log);
2402                 else
2403                         printf("Created directory '%s' for -a\n", dirpart);
2404         }
2405 }
2406
2407 /*
2408  * Create a new log file, destroying any currently-existing version
2409  * of the log file in the process.  If the caller wants a backup copy
2410  * of the file to exist, they should call 'link(logfile,logbackup)'
2411  * before calling this routine.
2412  */
2413 void
2414 createlog(const struct conf_entry *ent)
2415 {
2416         int fd, failed;
2417         struct stat st;
2418         char *realfile, *slash, tempfile[MAXPATHLEN];
2419
2420         fd = -1;
2421         realfile = ent->log;
2422
2423         /*
2424          * If this log file is being created for the first time (-C option),
2425          * then it may also be true that the parent directory does not exist
2426          * yet.  Check, and create that directory if it is missing.
2427          */
2428         if (ent->firstcreate) {
2429                 strlcpy(tempfile, realfile, sizeof(tempfile));
2430                 slash = strrchr(tempfile, '/');
2431                 if (slash != NULL) {
2432                         *slash = '\0';
2433                         failed = stat(tempfile, &st);
2434                         if (failed && errno != ENOENT)
2435                                 err(1, "Error on stat(%s)", tempfile);
2436                         if (failed)
2437                                 createdir(ent, tempfile);
2438                         else if (!S_ISDIR(st.st_mode))
2439                                 errx(1, "%s exists but is not a directory",
2440                                     tempfile);
2441                 }
2442         }
2443
2444         /*
2445          * First create an unused filename, so it can be chown'ed and
2446          * chmod'ed before it is moved into the real location.  mkstemp
2447          * will create the file mode=600 & owned by us.  Note that all
2448          * temp files will have a suffix of '.z<something>'.
2449          */
2450         strlcpy(tempfile, realfile, sizeof(tempfile));
2451         strlcat(tempfile, ".zXXXXXX", sizeof(tempfile));
2452         if (noaction)
2453                 printf("\tmktemp %s\n", tempfile);
2454         else {
2455                 fd = mkstemp(tempfile);
2456                 if (fd < 0)
2457                         err(1, "can't mkstemp logfile %s", tempfile);
2458
2459                 /*
2460                  * Add status message to what will become the new log file.
2461                  */
2462                 if (!(ent->flags & CE_BINARY)) {
2463                         if (log_trim(tempfile, ent))
2464                                 err(1, "can't add status message to log");
2465                 }
2466         }
2467
2468         /* Change the owner/group, if we are supposed to */
2469         if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2470                 if (noaction)
2471                         printf("\tchown %u:%u %s\n", ent->uid, ent->gid,
2472                             tempfile);
2473                 else {
2474                         failed = fchown(fd, ent->uid, ent->gid);
2475                         if (failed)
2476                                 err(1, "can't fchown temp file %s", tempfile);
2477                 }
2478         }
2479
2480         /* Turn on NODUMP if it was requested in the config-file. */
2481         if (ent->flags & CE_NODUMP) {
2482                 if (noaction)
2483                         printf("\tchflags nodump %s\n", tempfile);
2484                 else {
2485                         failed = fchflags(fd, UF_NODUMP);
2486                         if (failed) {
2487                                 warn("log_trim: fchflags(NODUMP)");
2488                         }
2489                 }
2490         }
2491
2492         /*
2493          * Note that if the real logfile still exists, and if the call
2494          * to rename() fails, then "neither the old file nor the new
2495          * file shall be changed or created" (to quote the standard).
2496          * If the call succeeds, then the file will be replaced without
2497          * any window where some other process might find that the file
2498          * did not exist.
2499          * XXX - ? It may be that for some error conditions, we could
2500          *      retry by first removing the realfile and then renaming.
2501          */
2502         if (noaction) {
2503                 printf("\tchmod %o %s\n", ent->permissions, tempfile);
2504                 printf("\tmv %s %s\n", tempfile, realfile);
2505         } else {
2506                 failed = fchmod(fd, ent->permissions);
2507                 if (failed)
2508                         err(1, "can't fchmod temp file '%s'", tempfile);
2509                 failed = rename(tempfile, realfile);
2510                 if (failed)
2511                         err(1, "can't mv %s to %s", tempfile, realfile);
2512         }
2513
2514         if (fd >= 0)
2515                 close(fd);
2516 }
2517
2518 /*
2519  * Change the attributes of a given filename to what was specified in
2520  * the newsyslog.conf entry.  This routine is only called for files
2521  * that newsyslog expects that it has created, and thus it is a fatal
2522  * error if this routine finds that the file does not exist.
2523  */
2524 static void
2525 change_attrs(const char *fname, const struct conf_entry *ent)
2526 {
2527         int failed;
2528
2529         if (noaction) {
2530                 printf("\tchmod %o %s\n", ent->permissions, fname);
2531
2532                 if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
2533                         printf("\tchown %u:%u %s\n",
2534                             ent->uid, ent->gid, fname);
2535
2536                 if (ent->flags & CE_NODUMP)
2537                         printf("\tchflags nodump %s\n", fname);
2538                 return;
2539         }
2540
2541         failed = chmod(fname, ent->permissions);
2542         if (failed) {
2543                 if (errno != EPERM)
2544                         err(1, "chmod(%s) in change_attrs", fname);
2545                 warn("change_attrs couldn't chmod(%s)", fname);
2546         }
2547
2548         if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2549                 failed = chown(fname, ent->uid, ent->gid);
2550                 if (failed)
2551                         warn("can't chown %s", fname);
2552         }
2553
2554         if (ent->flags & CE_NODUMP) {
2555                 failed = chflags(fname, UF_NODUMP);
2556                 if (failed)
2557                         warn("can't chflags %s NODUMP", fname);
2558         }
2559 }