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