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