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