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