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