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