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