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