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