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