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