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