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