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