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