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