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