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