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