newsyslog.c revision 229654
1145522Sdarrenr/*-
2145522Sdarrenr * ------+---------+---------+-------- + --------+---------+---------+---------*
353642Sguido * This file includes significant modifications done by:
4145522Sdarrenr * Copyright (c) 2003, 2004  - Garance Alistair Drosehn <gad@FreeBSD.org>.
553642Sguido * All rights reserved.
680482Sdarrenr *
753642Sguido * Redistribution and use in source and binary forms, with or without
8145522Sdarrenr * modification, are permitted provided that the following conditions
9145522Sdarrenr * are met:
10145522Sdarrenr *   1. Redistributions of source code must retain the above copyright
11145522Sdarrenr *      notice, this list of conditions and the following disclaimer.
12145522Sdarrenr *   2. Redistributions in binary form must reproduce the above copyright
1353642Sguido *      notice, this list of conditions and the following disclaimer in the
1453642Sguido *      documentation and/or other materials provided with the distribution.
1553642Sguido *
1653642Sguido * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
1753642Sguido * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1853642Sguido * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1953642Sguido * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20145522Sdarrenr * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2153642Sguido * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2253642Sguido * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2353642Sguido * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24145522Sdarrenr * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25145522Sdarrenr * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26145522Sdarrenr * SUCH DAMAGE.
27145522Sdarrenr *
28145522Sdarrenr * ------+---------+---------+-------- + --------+---------+---------+---------*
29145522Sdarrenr */
30145522Sdarrenr
3153642Sguido/*
32145522Sdarrenr * This file contains changes from the Open Software Foundation.
3353642Sguido */
3453642Sguido
3553642Sguido/*
3653642Sguido * Copyright 1988, 1989 by the Massachusetts Institute of Technology
37145522Sdarrenr *
38145522Sdarrenr * Permission to use, copy, modify, and distribute this software and its
39145522Sdarrenr * documentation for any purpose and without fee is hereby granted, provided
4053642Sguido * that the above copyright notice appear in all copies and that both that
41145522Sdarrenr * copyright notice and this permission notice appear in supporting
42145522Sdarrenr * documentation, and that the names of M.I.T. and the M.I.T. S.I.P.B. not be
4353642Sguido * used in advertising or publicity pertaining to distribution of the
4453642Sguido * software without specific, written prior permission. M.I.T. and the M.I.T.
45145522Sdarrenr * S.I.P.B. make no representations about the suitability of this software
46145522Sdarrenr * for any purpose.  It is provided "as is" without express or implied
47145522Sdarrenr * warranty.
48145522Sdarrenr *
49145522Sdarrenr */
50145522Sdarrenr
51145522Sdarrenr/*
5253642Sguido * newsyslog - roll over selected logs at the appropriate time, keeping the a
53145522Sdarrenr * specified number of backup files around.
54145522Sdarrenr */
55145522Sdarrenr
5653642Sguido#include <sys/cdefs.h>
5753642Sguido__FBSDID("$FreeBSD: head/usr.sbin/newsyslog/newsyslog.c 229654 2012-01-05 21:36:36Z uqs $");
5853642Sguido
5953642Sguido#define	OSF
6053642Sguido
6153642Sguido#include <sys/param.h>
6253642Sguido#include <sys/queue.h>
6353642Sguido#include <sys/stat.h>
6453642Sguido#include <sys/wait.h>
6553642Sguido
6653642Sguido#include <assert.h>
6753642Sguido#include <ctype.h>
6853642Sguido#include <err.h>
6953642Sguido#include <errno.h>
7053642Sguido#include <dirent.h>
7153642Sguido#include <fcntl.h>
7253642Sguido#include <fnmatch.h>
7353642Sguido#include <glob.h>
7453642Sguido#include <grp.h>
7553642Sguido#include <paths.h>
7653642Sguido#include <pwd.h>
7753642Sguido#include <signal.h>
7853642Sguido#include <stdio.h>
7953642Sguido#include <libgen.h>
8053642Sguido#include <stdlib.h>
8153642Sguido#include <string.h>
8253642Sguido#include <time.h>
8353642Sguido#include <unistd.h>
8453642Sguido
8592685Sdarrenr#include "pathnames.h"
8653642Sguido#include "extern.h"
8753642Sguido
8853642Sguido/*
8953642Sguido * Compression suffixes
90145522Sdarrenr */
91145522Sdarrenr#ifndef	COMPRESS_SUFFIX_GZ
92145522Sdarrenr#define	COMPRESS_SUFFIX_GZ	".gz"
93145522Sdarrenr#endif
94145522Sdarrenr
95145522Sdarrenr#ifndef	COMPRESS_SUFFIX_BZ2
96145522Sdarrenr#define	COMPRESS_SUFFIX_BZ2	".bz2"
97145522Sdarrenr#endif
98145522Sdarrenr
99145522Sdarrenr#ifndef	COMPRESS_SUFFIX_XZ
100145522Sdarrenr#define	COMPRESS_SUFFIX_XZ	".xz"
10180482Sdarrenr#endif
102145522Sdarrenr
103145522Sdarrenr#define	COMPRESS_SUFFIX_MAXLEN	MAX(MAX(sizeof(COMPRESS_SUFFIX_GZ),sizeof(COMPRESS_SUFFIX_BZ2)),sizeof(COMPRESS_SUFFIX_XZ))
10453642Sguido
105145522Sdarrenr/*
106145522Sdarrenr * Compression types
107145522Sdarrenr */
108145522Sdarrenr#define	COMPRESS_TYPES  4	/* Number of supported compression types */
10992685Sdarrenr
11080482Sdarrenr#define	COMPRESS_NONE	0
11153642Sguido#define	COMPRESS_GZIP	1
11253642Sguido#define	COMPRESS_BZIP2	2
11353642Sguido#define	COMPRESS_XZ	3
11453642Sguido
11592685Sdarrenr/*
116145522Sdarrenr * Bit-values for the 'flags' parsed from a config-file entry.
117145522Sdarrenr */
118145522Sdarrenr#define	CE_BINARY	0x0008	/* Logfile is in binary, do not add status */
11953642Sguido				/*    messages to logfile(s) when rotating. */
12053642Sguido#define	CE_NOSIGNAL	0x0010	/* There is no process to signal when */
12153642Sguido				/*    trimming this file. */
12260855Sdarrenr#define	CE_TRIMAT	0x0020	/* trim file at a specific time. */
12353642Sguido#define	CE_GLOB		0x0040	/* name of the log is file name pattern. */
12453642Sguido#define	CE_SIGNALGROUP	0x0080	/* Signal a process-group instead of a single */
125145522Sdarrenr				/*    process when trimming this file. */
12692685Sdarrenr#define	CE_CREATE	0x0100	/* Create the log file if it does not exist. */
12753642Sguido#define	CE_NODUMP	0x0200	/* Set 'nodump' on newly created log file. */
128145522Sdarrenr#define	CE_PID2CMD	0x0400	/* Replace PID file with a shell command.*/
129145522Sdarrenr
130145522Sdarrenr#define	MIN_PID         5	/* Don't touch pids lower than this */
131145522Sdarrenr#define	MAX_PID		99999	/* was lower, see /usr/include/sys/proc.h */
13253642Sguido
133145522Sdarrenr#define	kbytes(size)  (((size) + 1023) >> 10)
134145522Sdarrenr
13553642Sguido#define	DEFAULT_MARKER	"<default>"
13653642Sguido#define	DEBUG_MARKER	"<debug>"
137145522Sdarrenr#define	INCLUDE_MARKER	"<include>"
138145522Sdarrenr#define	DEFAULT_TIMEFNAME_FMT	"%Y%m%dT%H%M%S"
13953642Sguido
140145522Sdarrenr#define	MAX_OLDLOGS 65536	/* Default maximum number of old logfiles */
141145522Sdarrenr
142145522Sdarrenrstruct compress_types {
14392685Sdarrenr	const char *flag;	/* Flag in configuration file */
14492685Sdarrenr	const char *suffix;	/* Compression suffix */
145145522Sdarrenr	const char *path;	/* Path to compression program */
146145522Sdarrenr};
14792685Sdarrenr
148145522Sdarrenrconst struct compress_types compress_type[COMPRESS_TYPES] = {
149145522Sdarrenr	{ "", "", "" },					/* no compression */
150145522Sdarrenr	{ "Z", COMPRESS_SUFFIX_GZ, _PATH_GZIP },	/* gzip compression */
151145522Sdarrenr	{ "J", COMPRESS_SUFFIX_BZ2, _PATH_BZIP2 },	/* bzip2 compression */
152145522Sdarrenr	{ "X", COMPRESS_SUFFIX_XZ, _PATH_XZ }		/* xz compression */
153145522Sdarrenr};
154145522Sdarrenr
155145522Sdarrenrstruct conf_entry {
156145522Sdarrenr	STAILQ_ENTRY(conf_entry) cf_nextp;
157145522Sdarrenr	char *log;		/* Name of the log */
15892685Sdarrenr	char *pid_cmd_file;		/* PID or command file */
159145522Sdarrenr	char *r_reason;		/* The reason this file is being rotated */
160145522Sdarrenr	int firstcreate;	/* Creating log for the first time (-C). */
161145522Sdarrenr	int rotate;		/* Non-zero if this file should be rotated */
162145522Sdarrenr	int fsize;		/* size found for the log file */
163145522Sdarrenr	uid_t uid;		/* Owner of log */
164145522Sdarrenr	gid_t gid;		/* Group of log */
165145522Sdarrenr	int numlogs;		/* Number of logs to keep */
166145522Sdarrenr	int trsize;		/* Size cutoff to trigger trimming the log */
167145522Sdarrenr	int hours;		/* Hours between log trimming */
168145522Sdarrenr	struct ptime_data *trim_at;	/* Specific time to do trimming */
169145522Sdarrenr	unsigned int permissions;	/* File permissions on the log */
170145522Sdarrenr	int flags;		/* CE_BINARY */
171145522Sdarrenr	int compress;		/* Compression */
172145522Sdarrenr	int sig;		/* Signal to send */
173145522Sdarrenr	int def_cfg;		/* Using the <default> rule for this file */
174145522Sdarrenr};
17553642Sguido
17653642Sguidostruct sigwork_entry {
17792685Sdarrenr	SLIST_ENTRY(sigwork_entry) sw_nextp;
17892685Sdarrenr	int	 sw_signum;		/* the signal to send */
17992685Sdarrenr	int	 sw_pidok;		/* true if pid value is valid */
18092685Sdarrenr	pid_t	 sw_pid;		/* the process id from the PID file */
18160855Sdarrenr	const char *sw_pidtype;		/* "daemon" or "process group" */
18260855Sdarrenr	int	 run_cmd;		/* run command or send PID to signal */
18360855Sdarrenr	char	 sw_fname[1];		/* file the PID was read from or shell cmd */
18460855Sdarrenr};
18560855Sdarrenr
18660855Sdarrenrstruct zipwork_entry {
18760855Sdarrenr	SLIST_ENTRY(zipwork_entry) zw_nextp;
18860855Sdarrenr	const struct conf_entry *zw_conf;	/* for chown/perm/flag info */
189145522Sdarrenr	const struct sigwork_entry *zw_swork;	/* to know success of signal */
190145522Sdarrenr	int	 zw_fsize;		/* size of the file to compress */
191145522Sdarrenr	char	 zw_fname[1];		/* the file to compress */
192145522Sdarrenr};
19360855Sdarrenr
194145522Sdarrenrstruct include_entry {
19560855Sdarrenr	STAILQ_ENTRY(include_entry) inc_nextp;
196145522Sdarrenr	const char *file;	/* Name of file to process */
19760855Sdarrenr};
19860855Sdarrenr
199145522Sdarrenrstruct oldlog_entry {
200145522Sdarrenr	char *fname;		/* Filename of the log file */
201145522Sdarrenr	time_t t;		/* Parsed timestamp of the logfile */
202145522Sdarrenr};
20360855Sdarrenr
204145522Sdarrenrtypedef enum {
20560855Sdarrenr	FREE_ENT, KEEP_ENT
20660855Sdarrenr}	fk_entry;
207145522Sdarrenr
208145522SdarrenrSTAILQ_HEAD(cflist, conf_entry);
209145522SdarrenrSLIST_HEAD(swlisthead, sigwork_entry) swhead = SLIST_HEAD_INITIALIZER(swhead);
21060855SdarrenrSLIST_HEAD(zwlisthead, zipwork_entry) zwhead = SLIST_HEAD_INITIALIZER(zwhead);
21160855SdarrenrSTAILQ_HEAD(ilist, include_entry);
21260855Sdarrenr
21392685Sdarrenrint dbg_at_times;		/* -D Show details of 'trim_at' code */
214145522Sdarrenr
215145522Sdarrenrint archtodir = 0;		/* Archive old logfiles to other directory */
216145522Sdarrenrint createlogs;			/* Create (non-GLOB) logfiles which do not */
217145522Sdarrenr				/*    already exist.  1=='for entries with */
218145522Sdarrenr				/*    C flag', 2=='for all entries'. */
219145522Sdarrenrint verbose = 0;		/* Print out what's going on */
220145522Sdarrenrint needroot = 1;		/* Root privs are necessary */
221145522Sdarrenrint noaction = 0;		/* Don't do anything, just show it */
222145522Sdarrenrint norotate = 0;		/* Don't rotate */
223145522Sdarrenrint nosignal;			/* Do not send any signals */
224145522Sdarrenrint enforcepid = 0;		/* If PID file does not exist or empty, do nothing */
225145522Sdarrenrint force = 0;			/* Force the trim no matter what */
226145522Sdarrenrint rotatereq = 0;		/* -R = Always rotate the file(s) as given */
227145522Sdarrenr				/*    on the command (this also requires   */
228145522Sdarrenr				/*    that a list of files *are* given on  */
229145522Sdarrenr				/*    the run command). */
230145522Sdarrenrchar *requestor;		/* The name given on a -R request */
231145522Sdarrenrchar *timefnamefmt = NULL;	/* Use time based filenames instead of .0 etc */
232145522Sdarrenrchar *archdirname;		/* Directory path to old logfiles archive */
233145522Sdarrenrchar *destdir = NULL;		/* Directory to treat at root for logs */
234145522Sdarrenrconst char *conf;		/* Configuration file to use */
235145522Sdarrenr
236145522Sdarrenrstruct ptime_data *dbg_timenow;	/* A "timenow" value set via -D option */
237145522Sdarrenrstruct ptime_data *timenow;	/* The time to use for checking at-fields */
238145522Sdarrenr
239145522Sdarrenr#define	DAYTIME_LEN	16
240145522Sdarrenrchar daytime[DAYTIME_LEN];	/* The current time in human readable form,
241145522Sdarrenr				 * used for rotation-tracking messages. */
242145522Sdarrenrchar hostname[MAXHOSTNAMELEN];	/* hostname */
243145522Sdarrenr
244145522Sdarrenrconst char *path_syslogpid = _PATH_SYSLOGPID;
245145522Sdarrenr
24692685Sdarrenrstatic struct cflist *get_worklist(char **files);
24792685Sdarrenrstatic void parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
24892685Sdarrenr		    struct conf_entry *defconf_p, struct ilist *inclist);
24992685Sdarrenrstatic void add_to_queue(const char *fname, struct ilist *inclist);
25060855Sdarrenrstatic char *sob(char *p);
25160855Sdarrenrstatic char *son(char *p);
25260855Sdarrenrstatic int isnumberstr(const char *);
25360855Sdarrenrstatic int isglobstr(const char *);
25460855Sdarrenrstatic char *missing_field(char *p, char *errline);
255145522Sdarrenrstatic void	 change_attrs(const char *, const struct conf_entry *);
25660855Sdarrenrstatic const char *get_logfile_suffix(const char *logfile);
25792685Sdarrenrstatic fk_entry	 do_entry(struct conf_entry *);
25892685Sdarrenrstatic fk_entry	 do_rotate(const struct conf_entry *);
259145522Sdarrenrstatic void	 do_sigwork(struct sigwork_entry *);
260145522Sdarrenrstatic void	 do_zipwork(struct zipwork_entry *);
261145522Sdarrenrstatic struct sigwork_entry *
262145522Sdarrenr		 save_sigwork(const struct conf_entry *);
26360855Sdarrenrstatic struct zipwork_entry *
264145522Sdarrenr		 save_zipwork(const struct conf_entry *, const struct
26560855Sdarrenr		    sigwork_entry *, int, const char *);
26660855Sdarrenrstatic void	 set_swpid(struct sigwork_entry *, const struct conf_entry *);
267145522Sdarrenrstatic int	 sizefile(const char *);
268145522Sdarrenrstatic void expand_globs(struct cflist *work_p, struct cflist *glob_p);
26960855Sdarrenrstatic void free_clist(struct cflist *list);
27060855Sdarrenrstatic void free_entry(struct conf_entry *ent);
27160855Sdarrenrstatic struct conf_entry *init_entry(const char *fname,
27260855Sdarrenr		struct conf_entry *src_entry);
27392685Sdarrenrstatic void parse_args(int argc, char **argv);
27492685Sdarrenrstatic int parse_doption(const char *doption);
27592685Sdarrenrstatic void usage(void);
276145522Sdarrenrstatic int log_trim(const char *logname, const struct conf_entry *log_ent);
277145522Sdarrenrstatic int age_old_log(char *file);
27853642Sguidostatic void savelog(char *from, char *to);
27953642Sguidostatic void createdir(const struct conf_entry *ent, char *dirpart);
28053642Sguidostatic void createlog(const struct conf_entry *ent);
28153642Sguido
28253642Sguido/*
28353642Sguido * All the following take a parameter of 'int', but expect values in the
28492685Sdarrenr * range of unsigned char.  Define wrappers which take values of type 'char',
285145522Sdarrenr * whether signed or unsigned, and ensure they end up in the right range.
28653642Sguido */
287145522Sdarrenr#define	isdigitch(Anychar) isdigit((u_char)(Anychar))
28853642Sguido#define	isprintch(Anychar) isprint((u_char)(Anychar))
28953642Sguido#define	isspacech(Anychar) isspace((u_char)(Anychar))
29053642Sguido#define	tolowerch(Anychar) tolower((u_char)(Anychar))
29153642Sguido
29253642Sguidoint
293145522Sdarrenrmain(int argc, char **argv)
294145522Sdarrenr{
295145522Sdarrenr	struct cflist *worklist;
296145522Sdarrenr	struct conf_entry *p;
297145522Sdarrenr	struct sigwork_entry *stmp;
298145522Sdarrenr	struct zipwork_entry *ztmp;
299145522Sdarrenr
300145522Sdarrenr	SLIST_INIT(&swhead);
301145522Sdarrenr	SLIST_INIT(&zwhead);
302145522Sdarrenr
303145522Sdarrenr	parse_args(argc, argv);
304145522Sdarrenr	argc -= optind;
305145522Sdarrenr	argv += optind;
306145522Sdarrenr
307145522Sdarrenr	if (needroot && getuid() && geteuid())
308145522Sdarrenr		errx(1, "must have root privs");
309145522Sdarrenr	worklist = get_worklist(argv);
310145522Sdarrenr
311145522Sdarrenr	/*
312145522Sdarrenr	 * Rotate all the files which need to be rotated.  Note that
313145522Sdarrenr	 * some users have *hundreds* of entries in newsyslog.conf!
314145522Sdarrenr	 */
315145522Sdarrenr	while (!STAILQ_EMPTY(worklist)) {
316145522Sdarrenr		p = STAILQ_FIRST(worklist);
317145522Sdarrenr		STAILQ_REMOVE_HEAD(worklist, cf_nextp);
318145522Sdarrenr		if (do_entry(p) == FREE_ENT)
319145522Sdarrenr			free_entry(p);
320145522Sdarrenr	}
321145522Sdarrenr
322145522Sdarrenr	/*
323145522Sdarrenr	 * Send signals to any processes which need a signal to tell
324145522Sdarrenr	 * them to close and re-open the log file(s) we have rotated.
325145522Sdarrenr	 * Note that zipwork_entries include pointers to these
326145522Sdarrenr	 * sigwork_entry's, so we can not free the entries here.
327145522Sdarrenr	 */
328145522Sdarrenr	if (!SLIST_EMPTY(&swhead)) {
329145522Sdarrenr		if (noaction || verbose)
330145522Sdarrenr			printf("Signal all daemon process(es)...\n");
331145522Sdarrenr		SLIST_FOREACH(stmp, &swhead, sw_nextp)
332145522Sdarrenr			do_sigwork(stmp);
333145522Sdarrenr		if (noaction)
334145522Sdarrenr			printf("\tsleep 10\n");
335145522Sdarrenr		else {
336145522Sdarrenr			if (verbose)
337145522Sdarrenr				printf("Pause 10 seconds to allow daemon(s)"
338145522Sdarrenr				    " to close log file(s)\n");
339145522Sdarrenr			sleep(10);
340145522Sdarrenr		}
34153642Sguido	}
34292685Sdarrenr	/*
34392685Sdarrenr	 * Compress all files that we're expected to compress, now
34492685Sdarrenr	 * that all processes should have closed the files which
34592685Sdarrenr	 * have been rotated.
34692685Sdarrenr	 */
34792685Sdarrenr	if (!SLIST_EMPTY(&zwhead)) {
34892685Sdarrenr		if (noaction || verbose)
34992685Sdarrenr			printf("Compress all rotated log file(s)...\n");
35092685Sdarrenr		while (!SLIST_EMPTY(&zwhead)) {
351145522Sdarrenr			ztmp = SLIST_FIRST(&zwhead);
35292685Sdarrenr			do_zipwork(ztmp);
35392685Sdarrenr			SLIST_REMOVE_HEAD(&zwhead, zw_nextp);
354145522Sdarrenr			free(ztmp);
355145522Sdarrenr		}
356145522Sdarrenr	}
357145522Sdarrenr	/* Now free all the sigwork entries. */
358145522Sdarrenr	while (!SLIST_EMPTY(&swhead)) {
359145522Sdarrenr		stmp = SLIST_FIRST(&swhead);
360145522Sdarrenr		SLIST_REMOVE_HEAD(&swhead, sw_nextp);
361145522Sdarrenr		free(stmp);
362145522Sdarrenr	}
36392685Sdarrenr
364145522Sdarrenr	while (wait(NULL) > 0 || errno == EINTR)
365145522Sdarrenr		;
36692685Sdarrenr	return (0);
367145522Sdarrenr}
368145522Sdarrenr
369145522Sdarrenrstatic struct conf_entry *
370145522Sdarrenrinit_entry(const char *fname, struct conf_entry *src_entry)
37192685Sdarrenr{
372145522Sdarrenr	struct conf_entry *tempwork;
373145522Sdarrenr
374145522Sdarrenr	if (verbose > 4)
375145522Sdarrenr		printf("\t--> [creating entry for %s]\n", fname);
376145522Sdarrenr
377145522Sdarrenr	tempwork = malloc(sizeof(struct conf_entry));
378145522Sdarrenr	if (tempwork == NULL)
37992685Sdarrenr		err(1, "malloc of conf_entry for %s", fname);
380145522Sdarrenr
381145522Sdarrenr	if (destdir == NULL || fname[0] != '/')
38292685Sdarrenr		tempwork->log = strdup(fname);
38392685Sdarrenr	else
38492685Sdarrenr		asprintf(&tempwork->log, "%s%s", destdir, fname);
38592685Sdarrenr	if (tempwork->log == NULL)
38692685Sdarrenr		err(1, "strdup for %s", fname);
38753642Sguido
38853642Sguido	if (src_entry != NULL) {
38953642Sguido		tempwork->pid_cmd_file = NULL;
39053642Sguido		if (src_entry->pid_cmd_file)
391145522Sdarrenr			tempwork->pid_cmd_file = strdup(src_entry->pid_cmd_file);
39292685Sdarrenr		tempwork->r_reason = NULL;
39353642Sguido		tempwork->firstcreate = 0;
39453642Sguido		tempwork->rotate = 0;
39553642Sguido		tempwork->fsize = -1;
39692685Sdarrenr		tempwork->uid = src_entry->uid;
39753642Sguido		tempwork->gid = src_entry->gid;
398145522Sdarrenr		tempwork->numlogs = src_entry->numlogs;
399145522Sdarrenr		tempwork->trsize = src_entry->trsize;
400145522Sdarrenr		tempwork->hours = src_entry->hours;
401145522Sdarrenr		tempwork->trim_at = NULL;
402145522Sdarrenr		if (src_entry->trim_at != NULL)
403145522Sdarrenr			tempwork->trim_at = ptime_init(src_entry->trim_at);
404145522Sdarrenr		tempwork->permissions = src_entry->permissions;
40592685Sdarrenr		tempwork->flags = src_entry->flags;
406145522Sdarrenr		tempwork->compress = src_entry->compress;
40792685Sdarrenr		tempwork->sig = src_entry->sig;
40892685Sdarrenr		tempwork->def_cfg = src_entry->def_cfg;
40992685Sdarrenr	} else {
410145522Sdarrenr		/* Initialize as a "do-nothing" entry */
411145522Sdarrenr		tempwork->pid_cmd_file = NULL;
412145522Sdarrenr		tempwork->r_reason = NULL;
413145522Sdarrenr		tempwork->firstcreate = 0;
414145522Sdarrenr		tempwork->rotate = 0;
41592685Sdarrenr		tempwork->fsize = -1;
416145522Sdarrenr		tempwork->uid = (uid_t)-1;
41753642Sguido		tempwork->gid = (gid_t)-1;
41853642Sguido		tempwork->numlogs = 1;
419145522Sdarrenr		tempwork->trsize = -1;
420145522Sdarrenr		tempwork->hours = -1;
421145522Sdarrenr		tempwork->trim_at = NULL;
422145522Sdarrenr		tempwork->permissions = 0;
42392685Sdarrenr		tempwork->flags = 0;
424145522Sdarrenr		tempwork->compress = COMPRESS_NONE;
425145522Sdarrenr		tempwork->sig = SIGHUP;
42653642Sguido		tempwork->def_cfg = 0;
427145522Sdarrenr	}
42853642Sguido
42953642Sguido	return (tempwork);
43053642Sguido}
43160855Sdarrenr
432145522Sdarrenrstatic void
43392685Sdarrenrfree_entry(struct conf_entry *ent)
43492685Sdarrenr{
43592685Sdarrenr
43660855Sdarrenr	if (ent == NULL)
437145522Sdarrenr		return;
438145522Sdarrenr
439145522Sdarrenr	if (ent->log != NULL) {
44092685Sdarrenr		if (verbose > 4)
44160855Sdarrenr			printf("\t--> [freeing entry for %s]\n", ent->log);
44260855Sdarrenr		free(ent->log);
44360855Sdarrenr		ent->log = NULL;
44453642Sguido	}
44592685Sdarrenr
44692685Sdarrenr	if (ent->pid_cmd_file != NULL) {
44792685Sdarrenr		free(ent->pid_cmd_file);
44853642Sguido		ent->pid_cmd_file = NULL;
44953642Sguido	}
45053642Sguido
45153642Sguido	if (ent->r_reason != NULL) {
452145522Sdarrenr		free(ent->r_reason);
453145522Sdarrenr		ent->r_reason = NULL;
454145522Sdarrenr	}
455145522Sdarrenr
45653642Sguido	if (ent->trim_at != NULL) {
457145522Sdarrenr		ptime_free(ent->trim_at);
45853642Sguido		ent->trim_at = NULL;
45953642Sguido	}
46053642Sguido
46180482Sdarrenr	free(ent);
462145522Sdarrenr}
463145522Sdarrenr
464145522Sdarrenrstatic void
46580482Sdarrenrfree_clist(struct cflist *list)
46680482Sdarrenr{
46780482Sdarrenr	struct conf_entry *ent;
468145522Sdarrenr
46953642Sguido	while (!STAILQ_EMPTY(list)) {
47053642Sguido		ent = STAILQ_FIRST(list);
471145522Sdarrenr		STAILQ_REMOVE_HEAD(list, cf_nextp);
47260855Sdarrenr		free_entry(ent);
47353642Sguido	}
474145522Sdarrenr
475145522Sdarrenr	free(list);
476145522Sdarrenr	list = NULL;
47753642Sguido}
478145522Sdarrenr
479145522Sdarrenrstatic fk_entry
480145522Sdarrenrdo_entry(struct conf_entry * ent)
481145522Sdarrenr{
482145522Sdarrenr#define	REASON_MAX	80
483145522Sdarrenr	int modtime;
484145522Sdarrenr	fk_entry free_or_keep;
485145522Sdarrenr	double diffsecs;
486145522Sdarrenr	char temp_reason[REASON_MAX];
487145522Sdarrenr
488145522Sdarrenr	free_or_keep = FREE_ENT;
489145522Sdarrenr	if (verbose)
490145522Sdarrenr		printf("%s <%d%s>: ", ent->log, ent->numlogs,
491145522Sdarrenr		    compress_type[ent->compress].flag);
492145522Sdarrenr	ent->fsize = sizefile(ent->log);
493145522Sdarrenr	modtime = age_old_log(ent->log);
494145522Sdarrenr	ent->rotate = 0;
49553642Sguido	ent->firstcreate = 0;
496145522Sdarrenr	if (ent->fsize < 0) {
497145522Sdarrenr		/*
498145522Sdarrenr		 * If either the C flag or the -C option was specified,
499145522Sdarrenr		 * and if we won't be creating the file, then have the
500145522Sdarrenr		 * verbose message include a hint as to why the file
501145522Sdarrenr		 * will not be created.
502145522Sdarrenr		 */
503145522Sdarrenr		temp_reason[0] = '\0';
504145522Sdarrenr		if (createlogs > 1)
505145522Sdarrenr			ent->firstcreate = 1;
506145522Sdarrenr		else if ((ent->flags & CE_CREATE) && createlogs)
507145522Sdarrenr			ent->firstcreate = 1;
508145522Sdarrenr		else if (ent->flags & CE_CREATE)
509145522Sdarrenr			strlcpy(temp_reason, " (no -C option)", REASON_MAX);
510145522Sdarrenr		else if (createlogs)
511145522Sdarrenr			strlcpy(temp_reason, " (no C flag)", REASON_MAX);
512145522Sdarrenr
513145522Sdarrenr		if (ent->firstcreate) {
51453642Sguido			if (verbose)
515145522Sdarrenr				printf("does not exist -> will create.\n");
516145522Sdarrenr			createlog(ent);
517145522Sdarrenr		} else if (verbose) {
518145522Sdarrenr			printf("does not exist, skipped%s.\n", temp_reason);
51980482Sdarrenr		}
52053642Sguido	} else {
521102520Sdarrenr		if (ent->flags & CE_TRIMAT && !force && !rotatereq) {
522110916Sdarrenr			diffsecs = ptimeget_diff(timenow, ent->trim_at);
523110916Sdarrenr			if (diffsecs < 0.0) {
524102520Sdarrenr				/* trim_at is some time in the future. */
525145522Sdarrenr				if (verbose) {
526145522Sdarrenr					ptime_adjust4dst(ent->trim_at,
527145522Sdarrenr					    timenow);
528145522Sdarrenr					printf("--> will trim at %s",
529145522Sdarrenr					    ptimeget_ctime(ent->trim_at));
530145522Sdarrenr				}
531145522Sdarrenr				return (free_or_keep);
532145522Sdarrenr			} else if (diffsecs >= 3600.0) {
53353642Sguido				/*
53453642Sguido				 * trim_at is more than an hour in the past,
53553642Sguido				 * so find the next valid trim_at time, and
53653642Sguido				 * tell the user what that will be.
53753642Sguido				 */
53853642Sguido				if (verbose && dbg_at_times)
539145522Sdarrenr					printf("\n\t--> prev trim at %s\t",
54053642Sguido					    ptimeget_ctime(ent->trim_at));
54153642Sguido				if (verbose) {
542145522Sdarrenr					ptimeset_nxtime(ent->trim_at);
54353642Sguido					printf("--> will trim at %s",
54453642Sguido					    ptimeget_ctime(ent->trim_at));
54560855Sdarrenr				}
546145522Sdarrenr				return (free_or_keep);
547145522Sdarrenr			} else if (verbose && noaction && dbg_at_times) {
548145522Sdarrenr				/*
549145522Sdarrenr				 * If we are just debugging at-times, then
550145522Sdarrenr				 * a detailed message is helpful.  Also
55192685Sdarrenr				 * skip "doing" any commands, since they
552145522Sdarrenr				 * would all be turned off by no-action.
55392685Sdarrenr				 */
55492685Sdarrenr				printf("\n\t--> timematch at %s",
55592685Sdarrenr				    ptimeget_ctime(ent->trim_at));
55692685Sdarrenr				return (free_or_keep);
55792685Sdarrenr			} else if (verbose && ent->hours <= 0) {
55860855Sdarrenr				printf("--> time is up\n");
559145522Sdarrenr			}
560145522Sdarrenr		}
561145522Sdarrenr		if (verbose && (ent->trsize > 0))
562145522Sdarrenr			printf("size (Kb): %d [%d] ", ent->fsize, ent->trsize);
563145522Sdarrenr		if (verbose && (ent->hours > 0))
564145522Sdarrenr			printf(" age (hr): %d [%d] ", modtime, ent->hours);
565145522Sdarrenr
566145522Sdarrenr		/*
567145522Sdarrenr		 * Figure out if this logfile needs to be rotated.
568145522Sdarrenr		 */
569145522Sdarrenr		temp_reason[0] = '\0';
570145522Sdarrenr		if (rotatereq) {
571145522Sdarrenr			ent->rotate = 1;
572145522Sdarrenr			snprintf(temp_reason, REASON_MAX, " due to -R from %s",
573145522Sdarrenr			    requestor);
574145522Sdarrenr		} else if (force) {
575145522Sdarrenr			ent->rotate = 1;
576145522Sdarrenr			snprintf(temp_reason, REASON_MAX, " due to -F request");
577145522Sdarrenr		} else if ((ent->trsize > 0) && (ent->fsize >= ent->trsize)) {
578145522Sdarrenr			ent->rotate = 1;
579145522Sdarrenr			snprintf(temp_reason, REASON_MAX, " due to size>%dK",
580145522Sdarrenr			    ent->trsize);
581145522Sdarrenr		} else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) {
582145522Sdarrenr			ent->rotate = 1;
583145522Sdarrenr		} else if ((ent->hours > 0) && ((modtime >= ent->hours) ||
58453642Sguido		    (modtime < 0))) {
58560855Sdarrenr			ent->rotate = 1;
58680482Sdarrenr		}
58780482Sdarrenr
588145522Sdarrenr		/*
589145522Sdarrenr		 * If the file needs to be rotated, then rotate it.
59053642Sguido		 */
591145522Sdarrenr		if (ent->rotate && !norotate) {
592145522Sdarrenr			if (temp_reason[0] != '\0')
59353642Sguido				ent->r_reason = strdup(temp_reason);
594145522Sdarrenr			if (verbose)
595145522Sdarrenr				printf("--> trimming log....\n");
596145522Sdarrenr			if (noaction && !verbose)
597145522Sdarrenr				printf("%s <%d%s>: trimming\n", ent->log,
598145522Sdarrenr				    ent->numlogs,
599145522Sdarrenr				    compress_type[ent->compress].flag);
600145522Sdarrenr			free_or_keep = do_rotate(ent);
601145522Sdarrenr		} else {
602145522Sdarrenr			if (verbose)
60353642Sguido				printf("--> skipping\n");
604145522Sdarrenr		}
60553642Sguido	}
60660855Sdarrenr	return (free_or_keep);
60753642Sguido#undef REASON_MAX
60860855Sdarrenr}
60953642Sguido
61053642Sguidostatic void
61153642Sguidoparse_args(int argc, char **argv)
61292685Sdarrenr{
61392685Sdarrenr	int ch;
61492685Sdarrenr	char *p;
61592685Sdarrenr
61653642Sguido	timenow = ptime_init(NULL);
61753642Sguido	ptimeset_time(timenow, time(NULL));
61853642Sguido	strlcpy(daytime, ptimeget_ctime(timenow) + 4, DAYTIME_LEN);
61953642Sguido
62053642Sguido	/* Let's get our hostname */
621145522Sdarrenr	(void)gethostname(hostname, sizeof(hostname));
622145522Sdarrenr
623145522Sdarrenr	/* Truncate domain */
62453642Sguido	if ((p = strchr(hostname, '.')) != NULL)
62553642Sguido		*p = '\0';
62653642Sguido
62753642Sguido	/* Parse command line options. */
62853642Sguido	while ((ch = getopt(argc, argv, "a:d:f:nrst:vCD:FNPR:S:")) != -1)
62953642Sguido		switch (ch) {
63060855Sdarrenr		case 'a':
63160855Sdarrenr			archtodir++;
63260855Sdarrenr			archdirname = optarg;
63360855Sdarrenr			break;
63460855Sdarrenr		case 'd':
63560855Sdarrenr			destdir = optarg;
63660855Sdarrenr			break;
637145522Sdarrenr		case 'f':
638145522Sdarrenr			conf = optarg;
63953642Sguido			break;
64053642Sguido		case 'n':
64153642Sguido			noaction++;
64253642Sguido			break;
64353642Sguido		case 'r':
64453642Sguido			needroot = 0;
64553642Sguido			break;
64653642Sguido		case 's':
64753642Sguido			nosignal = 1;
64853642Sguido			break;
64953642Sguido		case 't':
65053642Sguido			if (optarg[0] == '\0' ||
65153642Sguido			    strcmp(optarg, "DEFAULT") == 0)
65253642Sguido				timefnamefmt = strdup(DEFAULT_TIMEFNAME_FMT);
65353642Sguido			else
65492685Sdarrenr				timefnamefmt = strdup(optarg);
65553642Sguido			break;
65653642Sguido		case 'v':
65753642Sguido			verbose++;
65853642Sguido			break;
659145522Sdarrenr		case 'C':
66053642Sguido			/* Useful for things like rc.diskless... */
66153642Sguido			createlogs++;
66253642Sguido			break;
66353642Sguido		case 'D':
66453642Sguido			/*
66592685Sdarrenr			 * Set some debugging option.  The specific option
66692685Sdarrenr			 * depends on the value of optarg.  These options
66792685Sdarrenr			 * may come and go without notice or documentation.
668110916Sdarrenr			 */
66960855Sdarrenr			if (parse_doption(optarg))
67060855Sdarrenr				break;
67160855Sdarrenr			usage();
67253642Sguido			/* NOTREACHED */
67353642Sguido		case 'F':
67453642Sguido			force++;
675102520Sdarrenr			break;
676102520Sdarrenr		case 'N':
677102520Sdarrenr			norotate++;
67853642Sguido			break;
67953642Sguido		case 'P':
68053642Sguido			enforcepid++;
68153642Sguido			break;
68253642Sguido		case 'R':
68353642Sguido			rotatereq++;
68453642Sguido			requestor = strdup(optarg);
68553642Sguido			break;
68653642Sguido		case 'S':
68798004Sdarrenr			path_syslogpid = optarg;
68853642Sguido			break;
68953642Sguido		case 'm':	/* Used by OpenBSD for "monitor mode" */
69053642Sguido		default:
691102520Sdarrenr			usage();
692102520Sdarrenr			/* NOTREACHED */
693102520Sdarrenr		}
69453642Sguido
695145522Sdarrenr	if (force && norotate) {
696102520Sdarrenr		warnx("Only one of -F and -N may be specified.");
69798004Sdarrenr		usage();
69898004Sdarrenr		/* NOTREACHED */
69953642Sguido	}
70053642Sguido
70153642Sguido	if (rotatereq) {
70253642Sguido		if (optind == argc) {
70353642Sguido			warnx("At least one filename must be given when -R is specified.");
70453642Sguido			usage();
70553642Sguido			/* NOTREACHED */
706102520Sdarrenr		}
707145522Sdarrenr		/* Make sure "requestor" value is safe for a syslog message. */
708145522Sdarrenr		for (p = requestor; *p != '\0'; p++) {
709145522Sdarrenr			if (!isprintch(*p) && (*p != '\t'))
710145522Sdarrenr				*p = '.';
71153642Sguido		}
712110916Sdarrenr	}
71353642Sguido
71453642Sguido	if (dbg_timenow) {
71553642Sguido		/*
71653642Sguido		 * Note that the 'daytime' variable is not changed.
71753642Sguido		 * That is only used in messages that track when a
71853642Sguido		 * logfile is rotated, and if a file *is* rotated,
71953642Sguido		 * then it will still rotated at the "real now" time.
72053642Sguido		 */
72153642Sguido		ptime_free(timenow);
72253642Sguido		timenow = dbg_timenow;
72353642Sguido		fprintf(stderr, "Debug: Running as if TimeNow is %s",
72453642Sguido		    ptimeget_ctime(dbg_timenow));
725102520Sdarrenr	}
726102520Sdarrenr
727145522Sdarrenr}
728145522Sdarrenr
729145522Sdarrenr/*
730145522Sdarrenr * These debugging options are mainly meant for developer use, such
73153642Sguido * as writing regression-tests.  They would not be needed by users
73253642Sguido * during normal operation of newsyslog...
73353642Sguido */
73453642Sguidostatic int
73553642Sguidoparse_doption(const char *doption)
73653642Sguido{
73753642Sguido	const char TN[] = "TN=";
73853642Sguido	int res;
73953642Sguido
740102520Sdarrenr	if (strncmp(doption, TN, sizeof(TN) - 1) == 0) {
741145522Sdarrenr		/*
742145522Sdarrenr		 * The "TimeNow" debugging option.  This might be off
743145522Sdarrenr		 * by an hour when crossing a timezone change.
744145522Sdarrenr		 */
74553642Sguido		dbg_timenow = ptime_init(NULL);
746110916Sdarrenr		res = ptime_relparse(dbg_timenow, PTM_PARSE_ISO8601,
74753642Sguido		    time(NULL), doption + sizeof(TN) - 1);
74853642Sguido		if (res == -2) {
74953642Sguido			warnx("Non-existent time specified on -D %s", doption);
75053642Sguido			return (0);			/* failure */
75153642Sguido		} else if (res < 0) {
75253642Sguido			warnx("Malformed time given on -D %s", doption);
75353642Sguido			return (0);			/* failure */
75453642Sguido		}
75553642Sguido		return (1);			/* successfully parsed */
75653642Sguido
75753642Sguido	}
75853642Sguido
759102520Sdarrenr	if (strcmp(doption, "ats") == 0) {
760145522Sdarrenr		dbg_at_times++;
761145522Sdarrenr		return (1);			/* successfully parsed */
762145522Sdarrenr	}
76353642Sguido
764110916Sdarrenr	/* XXX - This check could probably be dropped. */
76553642Sguido	if ((strcmp(doption, "neworder") == 0) || (strcmp(doption, "oldorder")
76653642Sguido	    == 0)) {
767102520Sdarrenr		warnx("NOTE: newsyslog always uses 'neworder'.");
76853642Sguido		return (1);			/* successfully parsed */
76953642Sguido	}
77053642Sguido
77153642Sguido	warnx("Unknown -D (debug) option: '%s'", doption);
77253642Sguido	return (0);				/* failure */
77353642Sguido}
77453642Sguido
77553642Sguidostatic void
77653642Sguidousage(void)
77753642Sguido{
77853642Sguido
779145522Sdarrenr	fprintf(stderr,
780145522Sdarrenr	    "usage: newsyslog [-CFNPnrsv] [-a directory] [-d directory] [-f config_file]\n"
781145522Sdarrenr	    "                 [-S pidfile] [-t timefmt] [[-R tagname] file ...]\n");
782145522Sdarrenr	exit(1);
783145522Sdarrenr}
78453642Sguido
78553642Sguido/*
78653642Sguido * Parse a configuration file and return a linked list of all the logs
78753642Sguido * which should be processed.
78853642Sguido */
78953642Sguidostatic struct cflist *
79053642Sguidoget_worklist(char **files)
79153642Sguido{
79253642Sguido	FILE *f;
793102520Sdarrenr	char **given;
794145522Sdarrenr	struct cflist *cmdlist, *filelist, *globlist;
795145522Sdarrenr	struct conf_entry *defconf, *dupent, *ent;
796145522Sdarrenr	struct ilist inclist;
79753642Sguido	struct include_entry *inc;
798110916Sdarrenr	int gmatch, fnres;
79953642Sguido
800102520Sdarrenr	defconf = NULL;
801145522Sdarrenr	STAILQ_INIT(&inclist);
802145522Sdarrenr
803145522Sdarrenr	filelist = malloc(sizeof(struct cflist));
804145522Sdarrenr	if (filelist == NULL)
805102520Sdarrenr		err(1, "malloc of filelist");
806102520Sdarrenr	STAILQ_INIT(filelist);
807102520Sdarrenr	globlist = malloc(sizeof(struct cflist));
808102520Sdarrenr	if (globlist == NULL)
809102520Sdarrenr		err(1, "malloc of globlist");
81053642Sguido	STAILQ_INIT(globlist);
81153642Sguido
812145522Sdarrenr	inc = malloc(sizeof(struct include_entry));
813145522Sdarrenr	if (inc == NULL)
814145522Sdarrenr		err(1, "malloc of inc");
815145522Sdarrenr	inc->file = conf;
81653642Sguido	if (inc->file == NULL)
81753642Sguido		inc->file = _PATH_CONF;
81853642Sguido	STAILQ_INSERT_TAIL(&inclist, inc, inc_nextp);
81953642Sguido
82092685Sdarrenr	STAILQ_FOREACH(inc, &inclist, inc_nextp) {
82192685Sdarrenr		if (strcmp(inc->file, "-") != 0)
82292685Sdarrenr			f = fopen(inc->file, "r");
82392685Sdarrenr		else {
82453642Sguido			f = stdin;
82553642Sguido			inc->file = "<stdin>";
82653642Sguido		}
82753642Sguido		if (!f)
82853642Sguido			err(1, "%s", inc->file);
82953642Sguido
830145522Sdarrenr		if (verbose)
831145522Sdarrenr			printf("Processing %s\n", inc->file);
832145522Sdarrenr		parse_file(f, filelist, globlist, defconf, &inclist);
833145522Sdarrenr		(void) fclose(f);
834145522Sdarrenr	}
83553642Sguido
83653642Sguido	/*
83753642Sguido	 * All config-file information has been read in and turned into
83860855Sdarrenr	 * a filelist and a globlist.  If there were no specific files
83960855Sdarrenr	 * given on the run command, then the only thing left to do is to
84092685Sdarrenr	 * call a routine which finds all files matched by the globlist
84192685Sdarrenr	 * and adds them to the filelist.  Then return the worklist.
84292685Sdarrenr	 */
84392685Sdarrenr	if (*files == NULL) {
84460855Sdarrenr		expand_globs(filelist, globlist);
84560855Sdarrenr		free_clist(globlist);
84660855Sdarrenr		if (defconf != NULL)
84760855Sdarrenr			free_entry(defconf);
84860855Sdarrenr		return (filelist);
849145522Sdarrenr		/* NOTREACHED */
85060855Sdarrenr	}
85160855Sdarrenr
852145522Sdarrenr	/*
85360855Sdarrenr	 * If newsyslog was given a specific list of files to process,
85460855Sdarrenr	 * it may be that some of those files were not listed in any
855	 * config file.  Those unlisted files should get the default
856	 * rotation action.  First, create the default-rotation action
857	 * if none was found in a system config file.
858	 */
859	if (defconf == NULL) {
860		defconf = init_entry(DEFAULT_MARKER, NULL);
861		defconf->numlogs = 3;
862		defconf->trsize = 50;
863		defconf->permissions = S_IRUSR|S_IWUSR;
864	}
865
866	/*
867	 * If newsyslog was run with a list of specific filenames,
868	 * then create a new worklist which has only those files in
869	 * it, picking up the rotation-rules for those files from
870	 * the original filelist.
871	 *
872	 * XXX - Note that this will copy multiple rules for a single
873	 *	logfile, if multiple entries are an exact match for
874	 *	that file.  That matches the historic behavior, but do
875	 *	we want to continue to allow it?  If so, it should
876	 *	probably be handled more intelligently.
877	 */
878	cmdlist = malloc(sizeof(struct cflist));
879	if (cmdlist == NULL)
880		err(1, "malloc of cmdlist");
881	STAILQ_INIT(cmdlist);
882
883	for (given = files; *given; ++given) {
884		/*
885		 * First try to find exact-matches for this given file.
886		 */
887		gmatch = 0;
888		STAILQ_FOREACH(ent, filelist, cf_nextp) {
889			if (strcmp(ent->log, *given) == 0) {
890				gmatch++;
891				dupent = init_entry(*given, ent);
892				STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
893			}
894		}
895		if (gmatch) {
896			if (verbose > 2)
897				printf("\t+ Matched entry %s\n", *given);
898			continue;
899		}
900
901		/*
902		 * There was no exact-match for this given file, so look
903		 * for a "glob" entry which does match.
904		 */
905		gmatch = 0;
906		if (verbose > 2 && globlist != NULL)
907			printf("\t+ Checking globs for %s\n", *given);
908		STAILQ_FOREACH(ent, globlist, cf_nextp) {
909			fnres = fnmatch(ent->log, *given, FNM_PATHNAME);
910			if (verbose > 2)
911				printf("\t+    = %d for pattern %s\n", fnres,
912				    ent->log);
913			if (fnres == 0) {
914				gmatch++;
915				dupent = init_entry(*given, ent);
916				/* This new entry is not a glob! */
917				dupent->flags &= ~CE_GLOB;
918				STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
919				/* Only allow a match to one glob-entry */
920				break;
921			}
922		}
923		if (gmatch) {
924			if (verbose > 2)
925				printf("\t+ Matched %s via %s\n", *given,
926				    ent->log);
927			continue;
928		}
929
930		/*
931		 * This given file was not found in any config file, so
932		 * add a worklist item based on the default entry.
933		 */
934		if (verbose > 2)
935			printf("\t+ No entry matched %s  (will use %s)\n",
936			    *given, DEFAULT_MARKER);
937		dupent = init_entry(*given, defconf);
938		/* Mark that it was *not* found in a config file */
939		dupent->def_cfg = 1;
940		STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
941	}
942
943	/*
944	 * Free all the entries in the original work list, the list of
945	 * glob entries, and the default entry.
946	 */
947	free_clist(filelist);
948	free_clist(globlist);
949	free_entry(defconf);
950
951	/* And finally, return a worklist which matches the given files. */
952	return (cmdlist);
953}
954
955/*
956 * Expand the list of entries with filename patterns, and add all files
957 * which match those glob-entries onto the worklist.
958 */
959static void
960expand_globs(struct cflist *work_p, struct cflist *glob_p)
961{
962	int gmatch, gres;
963	size_t i;
964	char *mfname;
965	struct conf_entry *dupent, *ent, *globent;
966	glob_t pglob;
967	struct stat st_fm;
968
969	/*
970	 * The worklist contains all fully-specified (non-GLOB) names.
971	 *
972	 * Now expand the list of filename-pattern (GLOB) entries into
973	 * a second list, which (by definition) will only match files
974	 * that already exist.  Do not add a glob-related entry for any
975	 * file which already exists in the fully-specified list.
976	 */
977	STAILQ_FOREACH(globent, glob_p, cf_nextp) {
978		gres = glob(globent->log, GLOB_NOCHECK, NULL, &pglob);
979		if (gres != 0) {
980			warn("cannot expand pattern (%d): %s", gres,
981			    globent->log);
982			continue;
983		}
984
985		if (verbose > 2)
986			printf("\t+ Expanding pattern %s\n", globent->log);
987		for (i = 0; i < pglob.gl_matchc; i++) {
988			mfname = pglob.gl_pathv[i];
989
990			/* See if this file already has a specific entry. */
991			gmatch = 0;
992			STAILQ_FOREACH(ent, work_p, cf_nextp) {
993				if (strcmp(mfname, ent->log) == 0) {
994					gmatch++;
995					break;
996				}
997			}
998			if (gmatch)
999				continue;
1000
1001			/* Make sure the named matched is a file. */
1002			gres = lstat(mfname, &st_fm);
1003			if (gres != 0) {
1004				/* Error on a file that glob() matched?!? */
1005				warn("Skipping %s - lstat() error", mfname);
1006				continue;
1007			}
1008			if (!S_ISREG(st_fm.st_mode)) {
1009				/* We only rotate files! */
1010				if (verbose > 2)
1011					printf("\t+  . skipping %s (!file)\n",
1012					    mfname);
1013				continue;
1014			}
1015
1016			if (verbose > 2)
1017				printf("\t+  . add file %s\n", mfname);
1018			dupent = init_entry(mfname, globent);
1019			/* This new entry is not a glob! */
1020			dupent->flags &= ~CE_GLOB;
1021
1022			/* Add to the worklist. */
1023			STAILQ_INSERT_TAIL(work_p, dupent, cf_nextp);
1024		}
1025		globfree(&pglob);
1026		if (verbose > 2)
1027			printf("\t+ Done with pattern %s\n", globent->log);
1028	}
1029}
1030
1031/*
1032 * Parse a configuration file and update a linked list of all the logs to
1033 * process.
1034 */
1035static void
1036parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
1037    struct conf_entry *defconf_p, struct ilist *inclist)
1038{
1039	char line[BUFSIZ], *parse, *q;
1040	char *cp, *errline, *group;
1041	struct conf_entry *working;
1042	struct passwd *pwd;
1043	struct group *grp;
1044	glob_t pglob;
1045	int eol, ptm_opts, res, special;
1046	size_t i;
1047
1048	errline = NULL;
1049	while (fgets(line, BUFSIZ, cf)) {
1050		if ((line[0] == '\n') || (line[0] == '#') ||
1051		    (strlen(line) == 0))
1052			continue;
1053		if (errline != NULL)
1054			free(errline);
1055		errline = strdup(line);
1056		for (cp = line + 1; *cp != '\0'; cp++) {
1057			if (*cp != '#')
1058				continue;
1059			if (*(cp - 1) == '\\') {
1060				strcpy(cp - 1, cp);
1061				cp--;
1062				continue;
1063			}
1064			*cp = '\0';
1065			break;
1066		}
1067
1068		q = parse = missing_field(sob(line), errline);
1069		parse = son(line);
1070		if (!*parse)
1071			errx(1, "malformed line (missing fields):\n%s",
1072			    errline);
1073		*parse = '\0';
1074
1075		/*
1076		 * Allow people to set debug options via the config file.
1077		 * (NOTE: debug options are undocumented, and may disappear
1078		 * at any time, etc).
1079		 */
1080		if (strcasecmp(DEBUG_MARKER, q) == 0) {
1081			q = parse = missing_field(sob(++parse), errline);
1082			parse = son(parse);
1083			if (!*parse)
1084				warnx("debug line specifies no option:\n%s",
1085				    errline);
1086			else {
1087				*parse = '\0';
1088				parse_doption(q);
1089			}
1090			continue;
1091		} else if (strcasecmp(INCLUDE_MARKER, q) == 0) {
1092			if (verbose)
1093				printf("Found: %s", errline);
1094			q = parse = missing_field(sob(++parse), errline);
1095			parse = son(parse);
1096			if (!*parse) {
1097				warnx("include line missing argument:\n%s",
1098				    errline);
1099				continue;
1100			}
1101
1102			*parse = '\0';
1103
1104			if (isglobstr(q)) {
1105				res = glob(q, GLOB_NOCHECK, NULL, &pglob);
1106				if (res != 0) {
1107					warn("cannot expand pattern (%d): %s",
1108					    res, q);
1109					continue;
1110				}
1111
1112				if (verbose > 2)
1113					printf("\t+ Expanding pattern %s\n", q);
1114
1115				for (i = 0; i < pglob.gl_matchc; i++)
1116					add_to_queue(pglob.gl_pathv[i],
1117					    inclist);
1118				globfree(&pglob);
1119			} else
1120				add_to_queue(q, inclist);
1121			continue;
1122		}
1123
1124		special = 0;
1125		working = init_entry(q, NULL);
1126		if (strcasecmp(DEFAULT_MARKER, q) == 0) {
1127			special = 1;
1128			if (defconf_p != NULL) {
1129				warnx("Ignoring duplicate entry for %s!", q);
1130				free_entry(working);
1131				continue;
1132			}
1133			defconf_p = working;
1134		}
1135
1136		q = parse = missing_field(sob(++parse), errline);
1137		parse = son(parse);
1138		if (!*parse)
1139			errx(1, "malformed line (missing fields):\n%s",
1140			    errline);
1141		*parse = '\0';
1142		if ((group = strchr(q, ':')) != NULL ||
1143		    (group = strrchr(q, '.')) != NULL) {
1144			*group++ = '\0';
1145			if (*q) {
1146				if (!(isnumberstr(q))) {
1147					if ((pwd = getpwnam(q)) == NULL)
1148						errx(1,
1149				     "error in config file; unknown user:\n%s",
1150						    errline);
1151					working->uid = pwd->pw_uid;
1152				} else
1153					working->uid = atoi(q);
1154			} else
1155				working->uid = (uid_t)-1;
1156
1157			q = group;
1158			if (*q) {
1159				if (!(isnumberstr(q))) {
1160					if ((grp = getgrnam(q)) == NULL)
1161						errx(1,
1162				    "error in config file; unknown group:\n%s",
1163						    errline);
1164					working->gid = grp->gr_gid;
1165				} else
1166					working->gid = atoi(q);
1167			} else
1168				working->gid = (gid_t)-1;
1169
1170			q = parse = missing_field(sob(++parse), errline);
1171			parse = son(parse);
1172			if (!*parse)
1173				errx(1, "malformed line (missing fields):\n%s",
1174				    errline);
1175			*parse = '\0';
1176		} else {
1177			working->uid = (uid_t)-1;
1178			working->gid = (gid_t)-1;
1179		}
1180
1181		if (!sscanf(q, "%o", &working->permissions))
1182			errx(1, "error in config file; bad permissions:\n%s",
1183			    errline);
1184
1185		q = parse = missing_field(sob(++parse), errline);
1186		parse = son(parse);
1187		if (!*parse)
1188			errx(1, "malformed line (missing fields):\n%s",
1189			    errline);
1190		*parse = '\0';
1191		if (!sscanf(q, "%d", &working->numlogs) || working->numlogs < 0)
1192			errx(1, "error in config file; bad value for count of logs to save:\n%s",
1193			    errline);
1194
1195		q = parse = missing_field(sob(++parse), errline);
1196		parse = son(parse);
1197		if (!*parse)
1198			errx(1, "malformed line (missing fields):\n%s",
1199			    errline);
1200		*parse = '\0';
1201		if (isdigitch(*q))
1202			working->trsize = atoi(q);
1203		else if (strcmp(q, "*") == 0)
1204			working->trsize = -1;
1205		else {
1206			warnx("Invalid value of '%s' for 'size' in line:\n%s",
1207			    q, errline);
1208			working->trsize = -1;
1209		}
1210
1211		working->flags = 0;
1212		working->compress = COMPRESS_NONE;
1213		q = parse = missing_field(sob(++parse), errline);
1214		parse = son(parse);
1215		eol = !*parse;
1216		*parse = '\0';
1217		{
1218			char *ep;
1219			u_long ul;
1220
1221			ul = strtoul(q, &ep, 10);
1222			if (ep == q)
1223				working->hours = 0;
1224			else if (*ep == '*')
1225				working->hours = -1;
1226			else if (ul > INT_MAX)
1227				errx(1, "interval is too large:\n%s", errline);
1228			else
1229				working->hours = ul;
1230
1231			if (*ep == '\0' || strcmp(ep, "*") == 0)
1232				goto no_trimat;
1233			if (*ep != '@' && *ep != '$')
1234				errx(1, "malformed interval/at:\n%s", errline);
1235
1236			working->flags |= CE_TRIMAT;
1237			working->trim_at = ptime_init(NULL);
1238			ptm_opts = PTM_PARSE_ISO8601;
1239			if (*ep == '$')
1240				ptm_opts = PTM_PARSE_DWM;
1241			ptm_opts |= PTM_PARSE_MATCHDOM;
1242			res = ptime_relparse(working->trim_at, ptm_opts,
1243			    ptimeget_secs(timenow), ep + 1);
1244			if (res == -2)
1245				errx(1, "nonexistent time for 'at' value:\n%s",
1246				    errline);
1247			else if (res < 0)
1248				errx(1, "malformed 'at' value:\n%s", errline);
1249		}
1250no_trimat:
1251
1252		if (eol)
1253			q = NULL;
1254		else {
1255			q = parse = sob(++parse);	/* Optional field */
1256			parse = son(parse);
1257			if (!*parse)
1258				eol = 1;
1259			*parse = '\0';
1260		}
1261
1262		for (; q && *q && !isspacech(*q); q++) {
1263			switch (tolowerch(*q)) {
1264			case 'b':
1265				working->flags |= CE_BINARY;
1266				break;
1267			case 'c':
1268				/*
1269				 * XXX - 	Ick! Ugly! Remove ASAP!
1270				 * We want `c' and `C' for "create".  But we
1271				 * will temporarily treat `c' as `g', because
1272				 * FreeBSD releases <= 4.8 have a typo of
1273				 * checking  ('G' || 'c')  for CE_GLOB.
1274				 */
1275				if (*q == 'c') {
1276					warnx("Assuming 'g' for 'c' in flags for line:\n%s",
1277					    errline);
1278					warnx("The 'c' flag will eventually mean 'CREATE'");
1279					working->flags |= CE_GLOB;
1280					break;
1281				}
1282				working->flags |= CE_CREATE;
1283				break;
1284			case 'd':
1285				working->flags |= CE_NODUMP;
1286				break;
1287			case 'g':
1288				working->flags |= CE_GLOB;
1289				break;
1290			case 'j':
1291				working->compress = COMPRESS_BZIP2;
1292				break;
1293			case 'n':
1294				working->flags |= CE_NOSIGNAL;
1295				break;
1296			case 'r':
1297				working->flags |= CE_PID2CMD;
1298				break;
1299			case 'u':
1300				working->flags |= CE_SIGNALGROUP;
1301				break;
1302			case 'w':
1303				/* Depreciated flag - keep for compatibility purposes */
1304				break;
1305			case 'x':
1306				working->compress = COMPRESS_XZ;
1307				break;
1308			case 'z':
1309				working->compress = COMPRESS_GZIP;
1310				break;
1311			case '-':
1312				break;
1313			case 'f':	/* Used by OpenBSD for "CE_FOLLOW" */
1314			case 'm':	/* Used by OpenBSD for "CE_MONITOR" */
1315			case 'p':	/* Used by NetBSD  for "CE_PLAIN0" */
1316			default:
1317				errx(1, "illegal flag in config file -- %c",
1318				    *q);
1319			}
1320		}
1321
1322		if (eol)
1323			q = NULL;
1324		else {
1325			q = parse = sob(++parse);	/* Optional field */
1326			parse = son(parse);
1327			if (!*parse)
1328				eol = 1;
1329			*parse = '\0';
1330		}
1331
1332		working->pid_cmd_file = NULL;
1333		if (q && *q) {
1334			if (*q == '/')
1335				working->pid_cmd_file = strdup(q);
1336			else if (isdigit(*q))
1337				goto got_sig;
1338			else
1339				errx(1,
1340			"illegal pid file or signal number in config file:\n%s",
1341				    errline);
1342		}
1343		if (eol)
1344			q = NULL;
1345		else {
1346			q = parse = sob(++parse);	/* Optional field */
1347			*(parse = son(parse)) = '\0';
1348		}
1349
1350		working->sig = SIGHUP;
1351		if (q && *q) {
1352			if (isdigit(*q)) {
1353		got_sig:
1354				working->sig = atoi(q);
1355			} else {
1356		err_sig:
1357				errx(1,
1358				    "illegal signal number in config file:\n%s",
1359				    errline);
1360			}
1361			if (working->sig < 1 || working->sig >= NSIG)
1362				goto err_sig;
1363		}
1364
1365		/*
1366		 * Finish figuring out what pid-file to use (if any) in
1367		 * later processing if this logfile needs to be rotated.
1368		 */
1369		if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) {
1370			/*
1371			 * This config-entry specified 'n' for nosignal,
1372			 * see if it also specified an explicit pid_cmd_file.
1373			 * This would be a pretty pointless combination.
1374			 */
1375			if (working->pid_cmd_file != NULL) {
1376				warnx("Ignoring '%s' because flag 'n' was specified in line:\n%s",
1377				    working->pid_cmd_file, errline);
1378				free(working->pid_cmd_file);
1379				working->pid_cmd_file = NULL;
1380			}
1381		} else if (working->pid_cmd_file == NULL) {
1382			/*
1383			 * This entry did not specify the 'n' flag, which
1384			 * means it should signal syslogd unless it had
1385			 * specified some other pid-file (and obviously the
1386			 * syslog pid-file will not be for a process-group).
1387			 * Also, we should only try to notify syslog if we
1388			 * are root.
1389			 */
1390			if (working->flags & CE_SIGNALGROUP) {
1391				warnx("Ignoring flag 'U' in line:\n%s",
1392				    errline);
1393				working->flags &= ~CE_SIGNALGROUP;
1394			}
1395			if (needroot)
1396				working->pid_cmd_file = strdup(path_syslogpid);
1397		}
1398
1399		/*
1400		 * Add this entry to the appropriate list of entries, unless
1401		 * it was some kind of special entry (eg: <default>).
1402		 */
1403		if (special) {
1404			;			/* Do not add to any list */
1405		} else if (working->flags & CE_GLOB) {
1406			STAILQ_INSERT_TAIL(glob_p, working, cf_nextp);
1407		} else {
1408			STAILQ_INSERT_TAIL(work_p, working, cf_nextp);
1409		}
1410	}
1411	if (errline != NULL)
1412		free(errline);
1413}
1414
1415static char *
1416missing_field(char *p, char *errline)
1417{
1418
1419	if (!p || !*p)
1420		errx(1, "missing field in config file:\n%s", errline);
1421	return (p);
1422}
1423
1424/*
1425 * In our sort we return it in the reverse of what qsort normally
1426 * would do, as we want the newest files first.  If we have two
1427 * entries with the same time we don't really care about order.
1428 *
1429 * Support function for qsort() in delete_oldest_timelog().
1430 */
1431static int
1432oldlog_entry_compare(const void *a, const void *b)
1433{
1434	const struct oldlog_entry *ola = a, *olb = b;
1435
1436	if (ola->t > olb->t)
1437		return (-1);
1438	else if (ola->t < olb->t)
1439		return (1);
1440	else
1441		return (0);
1442}
1443
1444/*
1445 * Delete the oldest logfiles, when using time based filenames.
1446 */
1447static void
1448delete_oldest_timelog(const struct conf_entry *ent, const char *archive_dir)
1449{
1450	char *logfname, *s, *dir, errbuf[80];
1451	int dirfd, i, logcnt, max_logcnt, valid;
1452	struct oldlog_entry *oldlogs;
1453	size_t logfname_len;
1454	struct dirent *dp;
1455	const char *cdir;
1456	struct tm tm;
1457	DIR *dirp;
1458	int c;
1459
1460	oldlogs = malloc(MAX_OLDLOGS * sizeof(struct oldlog_entry));
1461	max_logcnt = MAX_OLDLOGS;
1462	logcnt = 0;
1463
1464	if (archive_dir != NULL && archive_dir[0] != '\0')
1465		cdir = archive_dir;
1466	else
1467		if ((cdir = dirname(ent->log)) == NULL)
1468			err(1, "dirname()");
1469	if ((dir = strdup(cdir)) == NULL)
1470		err(1, "strdup()");
1471
1472	if ((s = basename(ent->log)) == NULL)
1473		err(1, "basename()");
1474	if ((logfname = strdup(s)) == NULL)
1475		err(1, "strdup()");
1476	logfname_len = strlen(logfname);
1477	if (strcmp(logfname, "/") == 0)
1478		errx(1, "Invalid log filename - became '/'");
1479
1480	if (verbose > 2)
1481		printf("Searching for old logs in %s\n", dir);
1482
1483	/* First we create a 'list' of all archived logfiles */
1484	if ((dirp = opendir(dir)) == NULL)
1485		err(1, "Cannot open log directory '%s'", dir);
1486	dirfd = dirfd(dirp);
1487	while ((dp = readdir(dirp)) != NULL) {
1488		if (dp->d_type != DT_REG)
1489			continue;
1490
1491		/* Ignore everything but files with our logfile prefix */
1492		if (strncmp(dp->d_name, logfname, logfname_len) != 0)
1493			continue;
1494		/* Ignore the actual non-rotated logfile */
1495		if (dp->d_namlen == logfname_len)
1496			continue;
1497		/*
1498		 * Make sure we created have found a logfile, so the
1499		 * postfix is valid, IE format is: '.<time>(.[bg]z)?'.
1500		 */
1501		if (dp->d_name[logfname_len] != '.') {
1502			if (verbose)
1503				printf("Ignoring %s which has unexpected "
1504				    "extension '%s'\n", dp->d_name,
1505				    &dp->d_name[logfname_len]);
1506			continue;
1507		}
1508		if ((s = strptime(&dp->d_name[logfname_len + 1],
1509			    timefnamefmt, &tm)) == NULL) {
1510			/*
1511			 * We could special case "old" sequentially
1512			 * named logfiles here, but we do not as that
1513			 * would require special handling to decide
1514			 * which one was the oldest compared to "new"
1515			 * time based logfiles.
1516			 */
1517			if (verbose)
1518				printf("Ignoring %s which does not "
1519				    "match time format\n", dp->d_name);
1520			continue;
1521		}
1522
1523		for (c = 0; c < COMPRESS_TYPES; c++)
1524			if (strcmp(s, compress_type[c].suffix) == 0)
1525				valid = 1;
1526		if (valid != 1) {
1527			if (verbose)
1528				printf("Ignoring %s which has unexpected "
1529				    "extension '%s'\n", dp->d_name, s);
1530			continue;
1531		}
1532
1533		/*
1534		 * We should now have old an old rotated logfile, so
1535		 * add it to the 'list'.
1536		 */
1537		if ((oldlogs[logcnt].t = timegm(&tm)) == -1)
1538			err(1, "Could not convert time string to time value");
1539		if ((oldlogs[logcnt].fname = strdup(dp->d_name)) == NULL)
1540			err(1, "strdup()");
1541		logcnt++;
1542
1543		/*
1544		 * It is very unlikely we ever run out of space in the
1545		 * logfile array from the default size, but lets
1546		 * handle it anyway...
1547		 */
1548		if (logcnt >= max_logcnt) {
1549			max_logcnt *= 4;
1550			/* Detect integer overflow */
1551			if (max_logcnt < logcnt)
1552				errx(1, "Too many old logfiles found");
1553			oldlogs = realloc(oldlogs,
1554			    max_logcnt * sizeof(struct oldlog_entry));
1555			if (oldlogs == NULL)
1556				err(1, "realloc()");
1557		}
1558	}
1559
1560	/* Second, if needed we delete oldest archived logfiles */
1561	if (logcnt > 0 && logcnt >= ent->numlogs && ent->numlogs > 1) {
1562		oldlogs = realloc(oldlogs, logcnt *
1563		    sizeof(struct oldlog_entry));
1564		if (oldlogs == NULL)
1565			err(1, "realloc()");
1566
1567		/*
1568		 * We now sort the logs in the order of newest to
1569		 * oldest.  That way we can simply skip over the
1570		 * number of records we want to keep.
1571		 */
1572		qsort(oldlogs, logcnt, sizeof(struct oldlog_entry),
1573		    oldlog_entry_compare);
1574		for (i = ent->numlogs - 1; i < logcnt; i++) {
1575			if (noaction)
1576				printf("\trm -f %s/%s\n", dir,
1577				    oldlogs[i].fname);
1578			else if (unlinkat(dirfd, oldlogs[i].fname, 0) != 0) {
1579				snprintf(errbuf, sizeof(errbuf),
1580				    "Could not delet old logfile '%s'",
1581				    oldlogs[i].fname);
1582				perror(errbuf);
1583			}
1584		}
1585	} else if (verbose > 1)
1586		printf("No old logs to delete for logfile %s\n", ent->log);
1587
1588	/* Third, cleanup */
1589	closedir(dirp);
1590	for (i = 0; i < logcnt; i++) {
1591		assert(oldlogs[i].fname != NULL);
1592		free(oldlogs[i].fname);
1593	}
1594	free(oldlogs);
1595	free(logfname);
1596	free(dir);
1597}
1598
1599/*
1600 * Generate a log filename, when using classic filenames.
1601 */
1602static void
1603gen_classiclog_fname(char *fname, size_t fname_sz, const char *archive_dir,
1604    const char *namepart, int numlogs_c)
1605{
1606
1607	if (archive_dir[0] != '\0')
1608		(void) snprintf(fname, fname_sz, "%s/%s.%d", archive_dir,
1609		    namepart, numlogs_c);
1610	else
1611		(void) snprintf(fname, fname_sz, "%s.%d", namepart, numlogs_c);
1612}
1613
1614/*
1615 * Delete a rotated logfile, when using classic filenames.
1616 */
1617static void
1618delete_classiclog(const char *archive_dir, const char *namepart, int numlog_c)
1619{
1620	char file1[MAXPATHLEN], zfile1[MAXPATHLEN];
1621	int c;
1622
1623	gen_classiclog_fname(file1, sizeof(file1), archive_dir, namepart,
1624	    numlog_c);
1625
1626	for (c = 0; c < COMPRESS_TYPES; c++) {
1627		(void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1628		    compress_type[c].suffix);
1629		if (noaction)
1630			printf("\trm -f %s\n", zfile1);
1631		else
1632			(void) unlink(zfile1);
1633	}
1634}
1635
1636/*
1637 * Only add to the queue if the file hasn't already been added. This is
1638 * done to prevent circular include loops.
1639 */
1640static void
1641add_to_queue(const char *fname, struct ilist *inclist)
1642{
1643	struct include_entry *inc;
1644
1645	STAILQ_FOREACH(inc, inclist, inc_nextp) {
1646		if (strcmp(fname, inc->file) == 0) {
1647			warnx("duplicate include detected: %s", fname);
1648			return;
1649		}
1650	}
1651
1652	inc = malloc(sizeof(struct include_entry));
1653	if (inc == NULL)
1654		err(1, "malloc of inc");
1655	inc->file = strdup(fname);
1656
1657	if (verbose > 2)
1658		printf("\t+ Adding %s to the processing queue.\n", fname);
1659
1660	STAILQ_INSERT_TAIL(inclist, inc, inc_nextp);
1661}
1662
1663/*
1664 * Search for logfile and return its compression suffix (if supported)
1665 * The suffix detection is first-match in the order of compress_types
1666 *
1667 * Note: if logfile without suffix exists (uncompressed, COMPRESS_NONE)
1668 * a zero-length string is returned
1669 */
1670static const char *
1671get_logfile_suffix(const char *logfile)
1672{
1673	struct stat st;
1674	char zfile[MAXPATHLEN];
1675	int c;
1676
1677	for (c = 0; c < COMPRESS_TYPES; c++) {
1678		(void) strlcpy(zfile, logfile, MAXPATHLEN);
1679		(void) strlcat(zfile, compress_type[c].suffix, MAXPATHLEN);
1680		if (lstat(zfile, &st) == 0)
1681			return (compress_type[c].suffix);
1682	}
1683	return (NULL);
1684}
1685
1686static fk_entry
1687do_rotate(const struct conf_entry *ent)
1688{
1689	char dirpart[MAXPATHLEN], namepart[MAXPATHLEN];
1690	char file1[MAXPATHLEN], file2[MAXPATHLEN];
1691	char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN];
1692	const char *logfile_suffix;
1693	char datetimestr[30];
1694	int flags, numlogs_c;
1695	fk_entry free_or_keep;
1696	struct sigwork_entry *swork;
1697	struct stat st;
1698	struct tm tm;
1699	time_t now;
1700
1701	flags = ent->flags;
1702	free_or_keep = FREE_ENT;
1703
1704	if (archtodir) {
1705		char *p;
1706
1707		/* build complete name of archive directory into dirpart */
1708		if (*archdirname == '/') {	/* absolute */
1709			strlcpy(dirpart, archdirname, sizeof(dirpart));
1710		} else {	/* relative */
1711			/* get directory part of logfile */
1712			strlcpy(dirpart, ent->log, sizeof(dirpart));
1713			if ((p = strrchr(dirpart, '/')) == NULL)
1714				dirpart[0] = '\0';
1715			else
1716				*(p + 1) = '\0';
1717			strlcat(dirpart, archdirname, sizeof(dirpart));
1718		}
1719
1720		/* check if archive directory exists, if not, create it */
1721		if (lstat(dirpart, &st))
1722			createdir(ent, dirpart);
1723
1724		/* get filename part of logfile */
1725		if ((p = strrchr(ent->log, '/')) == NULL)
1726			strlcpy(namepart, ent->log, sizeof(namepart));
1727		else
1728			strlcpy(namepart, p + 1, sizeof(namepart));
1729	} else {
1730		/*
1731		 * Tell utility functions we are not using an archive
1732		 * dir.
1733		 */
1734		dirpart[0] = '\0';
1735		strlcpy(namepart, ent->log, sizeof(namepart));
1736	}
1737
1738	/* Delete old logs */
1739	if (timefnamefmt != NULL)
1740		delete_oldest_timelog(ent, dirpart);
1741	else {
1742		/*
1743		 * Handle cleaning up after legacy newsyslog where we
1744		 * kept ent->numlogs + 1 files.  This code can go away
1745		 * at some point in the future.
1746		 */
1747		delete_classiclog(dirpart, namepart, ent->numlogs);
1748
1749		if (ent->numlogs > 0)
1750			delete_classiclog(dirpart, namepart, ent->numlogs - 1);
1751
1752	}
1753
1754	if (timefnamefmt != NULL) {
1755		/* If time functions fails we can't really do any sensible */
1756		if (time(&now) == (time_t)-1 ||
1757		    localtime_r(&now, &tm) == NULL)
1758			bzero(&tm, sizeof(tm));
1759
1760		strftime(datetimestr, sizeof(datetimestr), timefnamefmt, &tm);
1761		if (archtodir)
1762			(void) snprintf(file1, sizeof(file1), "%s/%s.%s",
1763			    dirpart, namepart, datetimestr);
1764		else
1765			(void) snprintf(file1, sizeof(file1), "%s.%s",
1766			    ent->log, datetimestr);
1767
1768		/* Don't run the code to move down logs */
1769		numlogs_c = -1;
1770	} else {
1771		gen_classiclog_fname(file1, sizeof(file1), dirpart, namepart,
1772		    ent->numlogs - 1);
1773		numlogs_c = ent->numlogs - 2;		/* copy for countdown */
1774	}
1775
1776	/* Move down log files */
1777	for (; numlogs_c >= 0; numlogs_c--) {
1778		(void) strlcpy(file2, file1, sizeof(file2));
1779
1780		gen_classiclog_fname(file1, sizeof(file1), dirpart, namepart,
1781		    numlogs_c);
1782
1783		logfile_suffix = get_logfile_suffix(file1);
1784		if (logfile_suffix == NULL)
1785			continue;
1786		(void) strlcpy(zfile1, file1, MAXPATHLEN);
1787		(void) strlcpy(zfile2, file2, MAXPATHLEN);
1788		(void) strlcat(zfile1, logfile_suffix, MAXPATHLEN);
1789		(void) strlcat(zfile2, logfile_suffix, MAXPATHLEN);
1790
1791		if (noaction)
1792			printf("\tmv %s %s\n", zfile1, zfile2);
1793		else {
1794			/* XXX - Ought to be checking for failure! */
1795			(void)rename(zfile1, zfile2);
1796		}
1797		change_attrs(zfile2, ent);
1798	}
1799
1800	if (ent->numlogs > 0) {
1801		if (noaction) {
1802			/*
1803			 * Note that savelog() may succeed with using link()
1804			 * for the archtodir case, but there is no good way
1805			 * of knowing if it will when doing "noaction", so
1806			 * here we claim that it will have to do a copy...
1807			 */
1808			if (archtodir)
1809				printf("\tcp %s %s\n", ent->log, file1);
1810			else
1811				printf("\tln %s %s\n", ent->log, file1);
1812		} else {
1813			if (!(flags & CE_BINARY)) {
1814				/* Report the trimming to the old log */
1815				log_trim(ent->log, ent);
1816			}
1817			savelog(ent->log, file1);
1818		}
1819		change_attrs(file1, ent);
1820	}
1821
1822	/* Create the new log file and move it into place */
1823	if (noaction)
1824		printf("Start new log...\n");
1825	createlog(ent);
1826
1827	/*
1828	 * Save all signalling and file-compression to be done after log
1829	 * files from all entries have been rotated.  This way any one
1830	 * process will not be sent the same signal multiple times when
1831	 * multiple log files had to be rotated.
1832	 */
1833	swork = NULL;
1834	if (ent->pid_cmd_file != NULL)
1835		swork = save_sigwork(ent);
1836	if (ent->numlogs > 0 && ent->compress > COMPRESS_NONE) {
1837		/*
1838		 * The zipwork_entry will include a pointer to this
1839		 * conf_entry, so the conf_entry should not be freed.
1840		 */
1841		free_or_keep = KEEP_ENT;
1842		save_zipwork(ent, swork, ent->fsize, file1);
1843	}
1844
1845	return (free_or_keep);
1846}
1847
1848static void
1849do_sigwork(struct sigwork_entry *swork)
1850{
1851	struct sigwork_entry *nextsig;
1852	int kres, secs;
1853	char *tmp;
1854
1855	if (!(swork->sw_pidok) || swork->sw_pid == 0)
1856		return;			/* no work to do... */
1857
1858	/*
1859	 * If nosignal (-s) was specified, then do not signal any process.
1860	 * Note that a nosignal request triggers a warning message if the
1861	 * rotated logfile needs to be compressed, *unless* -R was also
1862	 * specified.  We assume that an `-sR' request came from a process
1863	 * which writes to the logfile, and as such, we assume that process
1864	 * has already made sure the logfile is not presently in use.  This
1865	 * just sets swork->sw_pidok to a special value, and do_zipwork
1866	 * will print any necessary warning(s).
1867	 */
1868	if (nosignal) {
1869		if (!rotatereq)
1870			swork->sw_pidok = -1;
1871		return;
1872	}
1873
1874	/*
1875	 * Compute the pause between consecutive signals.  Use a longer
1876	 * sleep time if we will be sending two signals to the same
1877	 * deamon or process-group.
1878	 */
1879	secs = 0;
1880	nextsig = SLIST_NEXT(swork, sw_nextp);
1881	if (nextsig != NULL) {
1882		if (swork->sw_pid == nextsig->sw_pid)
1883			secs = 10;
1884		else
1885			secs = 1;
1886	}
1887
1888	if (noaction) {
1889		printf("\tkill -%d %d \t\t# %s\n", swork->sw_signum,
1890		    (int)swork->sw_pid, swork->sw_fname);
1891		if (secs > 0)
1892			printf("\tsleep %d\n", secs);
1893		return;
1894	}
1895
1896	if (swork->run_cmd) {
1897		asprintf(&tmp, "%s %d", swork->sw_fname, swork->sw_signum);
1898		if (tmp == NULL) {
1899			warn("can't allocate memory to run %s",
1900			    swork->sw_fname);
1901			return;
1902		}
1903		if (verbose)
1904			printf("Run command: %s\n", tmp);
1905		kres = system(tmp);
1906		if (kres) {
1907			warnx("%s: returned non-zero exit code: %d",
1908			    tmp, kres);
1909		}
1910		free(tmp);
1911		return;
1912	}
1913
1914	kres = kill(swork->sw_pid, swork->sw_signum);
1915	if (kres != 0) {
1916		/*
1917		 * Assume that "no such process" (ESRCH) is something
1918		 * to warn about, but is not an error.  Presumably the
1919		 * process which writes to the rotated log file(s) is
1920		 * gone, in which case we should have no problem with
1921		 * compressing the rotated log file(s).
1922		 */
1923		if (errno != ESRCH)
1924			swork->sw_pidok = 0;
1925		warn("can't notify %s, pid %d", swork->sw_pidtype,
1926		    (int)swork->sw_pid);
1927	} else {
1928		if (verbose)
1929			printf("Notified %s pid %d = %s\n", swork->sw_pidtype,
1930			    (int)swork->sw_pid, swork->sw_fname);
1931		if (secs > 0) {
1932			if (verbose)
1933				printf("Pause %d second(s) between signals\n",
1934				    secs);
1935			sleep(secs);
1936		}
1937	}
1938}
1939
1940static void
1941do_zipwork(struct zipwork_entry *zwork)
1942{
1943	const char *pgm_name, *pgm_path;
1944	int errsav, fcount, zstatus;
1945	pid_t pidzip, wpid;
1946	char zresult[MAXPATHLEN];
1947	int c;
1948
1949	assert(zwork != NULL);
1950	pgm_path = NULL;
1951	strlcpy(zresult, zwork->zw_fname, sizeof(zresult));
1952	if (zwork->zw_conf != NULL &&
1953	    zwork->zw_conf->compress > COMPRESS_NONE)
1954		for (c = 1; c < COMPRESS_TYPES; c++) {
1955			if (zwork->zw_conf->compress == c) {
1956				pgm_path = compress_type[c].path;
1957				(void) strlcat(zresult,
1958				    compress_type[c].suffix, sizeof(zresult));
1959				break;
1960			}
1961		}
1962	if (pgm_path == NULL) {
1963		warnx("invalid entry for %s in do_zipwork", zwork->zw_fname);
1964		return;
1965	}
1966	pgm_name = strrchr(pgm_path, '/');
1967	if (pgm_name == NULL)
1968		pgm_name = pgm_path;
1969	else
1970		pgm_name++;
1971
1972	if (zwork->zw_swork != NULL && zwork->zw_swork->sw_pidok <= 0) {
1973		warnx(
1974		    "log %s not compressed because daemon(s) not notified",
1975		    zwork->zw_fname);
1976		change_attrs(zwork->zw_fname, zwork->zw_conf);
1977		return;
1978	}
1979
1980	if (noaction) {
1981		printf("\t%s %s\n", pgm_name, zwork->zw_fname);
1982		change_attrs(zresult, zwork->zw_conf);
1983		return;
1984	}
1985
1986	fcount = 1;
1987	pidzip = fork();
1988	while (pidzip < 0) {
1989		/*
1990		 * The fork failed.  If the failure was due to a temporary
1991		 * problem, then wait a short time and try it again.
1992		 */
1993		errsav = errno;
1994		warn("fork() for `%s %s'", pgm_name, zwork->zw_fname);
1995		if (errsav != EAGAIN || fcount > 5)
1996			errx(1, "Exiting...");
1997		sleep(fcount * 12);
1998		fcount++;
1999		pidzip = fork();
2000	}
2001	if (!pidzip) {
2002		/* The child process executes the compression command */
2003		execl(pgm_path, pgm_path, "-f", zwork->zw_fname, (char *)0);
2004		err(1, "execl(`%s -f %s')", pgm_path, zwork->zw_fname);
2005	}
2006
2007	wpid = waitpid(pidzip, &zstatus, 0);
2008	if (wpid == -1) {
2009		/* XXX - should this be a fatal error? */
2010		warn("%s: waitpid(%d)", pgm_path, pidzip);
2011		return;
2012	}
2013	if (!WIFEXITED(zstatus)) {
2014		warnx("`%s -f %s' did not terminate normally", pgm_name,
2015		    zwork->zw_fname);
2016		return;
2017	}
2018	if (WEXITSTATUS(zstatus)) {
2019		warnx("`%s -f %s' terminated with a non-zero status (%d)",
2020		    pgm_name, zwork->zw_fname, WEXITSTATUS(zstatus));
2021		return;
2022	}
2023
2024	/* Compression was successful, set file attributes on the result. */
2025	change_attrs(zresult, zwork->zw_conf);
2026}
2027
2028/*
2029 * Save information on any process we need to signal.  Any single
2030 * process may need to be sent different signal-values for different
2031 * log files, but usually a single signal-value will cause the process
2032 * to close and re-open all of it's log files.
2033 */
2034static struct sigwork_entry *
2035save_sigwork(const struct conf_entry *ent)
2036{
2037	struct sigwork_entry *sprev, *stmp;
2038	int ndiff;
2039	size_t tmpsiz;
2040
2041	sprev = NULL;
2042	ndiff = 1;
2043	SLIST_FOREACH(stmp, &swhead, sw_nextp) {
2044		ndiff = strcmp(ent->pid_cmd_file, stmp->sw_fname);
2045		if (ndiff > 0)
2046			break;
2047		if (ndiff == 0) {
2048			if (ent->sig == stmp->sw_signum)
2049				break;
2050			if (ent->sig > stmp->sw_signum) {
2051				ndiff = 1;
2052				break;
2053			}
2054		}
2055		sprev = stmp;
2056	}
2057	if (stmp != NULL && ndiff == 0)
2058		return (stmp);
2059
2060	tmpsiz = sizeof(struct sigwork_entry) + strlen(ent->pid_cmd_file) + 1;
2061	stmp = malloc(tmpsiz);
2062
2063	stmp->run_cmd = 0;
2064	/* If this is a command to run we just set the flag and run command */
2065	if (ent->flags & CE_PID2CMD) {
2066		stmp->run_cmd = 1;
2067	} else {
2068		set_swpid(stmp, ent);
2069	}
2070	stmp->sw_signum = ent->sig;
2071	strcpy(stmp->sw_fname, ent->pid_cmd_file);
2072	if (sprev == NULL)
2073		SLIST_INSERT_HEAD(&swhead, stmp, sw_nextp);
2074	else
2075		SLIST_INSERT_AFTER(sprev, stmp, sw_nextp);
2076	return (stmp);
2077}
2078
2079/*
2080 * Save information on any file we need to compress.  We may see the same
2081 * file multiple times, so check the full list to avoid duplicates.  The
2082 * list itself is sorted smallest-to-largest, because that's the order we
2083 * want to compress the files.  If the partition is very low on disk space,
2084 * then the smallest files are the most likely to compress, and compressing
2085 * them first will free up more space for the larger files.
2086 */
2087static struct zipwork_entry *
2088save_zipwork(const struct conf_entry *ent, const struct sigwork_entry *swork,
2089    int zsize, const char *zipfname)
2090{
2091	struct zipwork_entry *zprev, *ztmp;
2092	int ndiff;
2093	size_t tmpsiz;
2094
2095	/* Compute the size if the caller did not know it. */
2096	if (zsize < 0)
2097		zsize = sizefile(zipfname);
2098
2099	zprev = NULL;
2100	ndiff = 1;
2101	SLIST_FOREACH(ztmp, &zwhead, zw_nextp) {
2102		ndiff = strcmp(zipfname, ztmp->zw_fname);
2103		if (ndiff == 0)
2104			break;
2105		if (zsize > ztmp->zw_fsize)
2106			zprev = ztmp;
2107	}
2108	if (ztmp != NULL && ndiff == 0)
2109		return (ztmp);
2110
2111	tmpsiz = sizeof(struct zipwork_entry) + strlen(zipfname) + 1;
2112	ztmp = malloc(tmpsiz);
2113	ztmp->zw_conf = ent;
2114	ztmp->zw_swork = swork;
2115	ztmp->zw_fsize = zsize;
2116	strcpy(ztmp->zw_fname, zipfname);
2117	if (zprev == NULL)
2118		SLIST_INSERT_HEAD(&zwhead, ztmp, zw_nextp);
2119	else
2120		SLIST_INSERT_AFTER(zprev, ztmp, zw_nextp);
2121	return (ztmp);
2122}
2123
2124/* Send a signal to the pid specified by pidfile */
2125static void
2126set_swpid(struct sigwork_entry *swork, const struct conf_entry *ent)
2127{
2128	FILE *f;
2129	long minok, maxok, rval;
2130	char *endp, *linep, line[BUFSIZ];
2131
2132	minok = MIN_PID;
2133	maxok = MAX_PID;
2134	swork->sw_pidok = 0;
2135	swork->sw_pid = 0;
2136	swork->sw_pidtype = "daemon";
2137	if (ent->flags & CE_SIGNALGROUP) {
2138		/*
2139		 * If we are expected to signal a process-group when
2140		 * rotating this logfile, then the value read in should
2141		 * be the negative of a valid process ID.
2142		 */
2143		minok = -MAX_PID;
2144		maxok = -MIN_PID;
2145		swork->sw_pidtype = "process-group";
2146	}
2147
2148	f = fopen(ent->pid_cmd_file, "r");
2149	if (f == NULL) {
2150		if (errno == ENOENT && enforcepid == 0) {
2151			/*
2152			 * Warn if the PID file doesn't exist, but do
2153			 * not consider it an error.  Most likely it
2154			 * means the process has been terminated,
2155			 * so it should be safe to rotate any log
2156			 * files that the process would have been using.
2157			 */
2158			swork->sw_pidok = 1;
2159			warnx("pid file doesn't exist: %s", ent->pid_cmd_file);
2160		} else
2161			warn("can't open pid file: %s", ent->pid_cmd_file);
2162		return;
2163	}
2164
2165	if (fgets(line, BUFSIZ, f) == NULL) {
2166		/*
2167		 * Warn if the PID file is empty, but do not consider
2168		 * it an error.  Most likely it means the process has
2169		 * has terminated, so it should be safe to rotate any
2170		 * log files that the process would have been using.
2171		 */
2172		if (feof(f) && enforcepid == 0) {
2173			swork->sw_pidok = 1;
2174			warnx("pid/cmd file is empty: %s", ent->pid_cmd_file);
2175		} else
2176			warn("can't read from pid file: %s", ent->pid_cmd_file);
2177		(void)fclose(f);
2178		return;
2179	}
2180	(void)fclose(f);
2181
2182	errno = 0;
2183	linep = line;
2184	while (*linep == ' ')
2185		linep++;
2186	rval = strtol(linep, &endp, 10);
2187	if (*endp != '\0' && !isspacech(*endp)) {
2188		warnx("pid file does not start with a valid number: %s",
2189		    ent->pid_cmd_file);
2190	} else if (rval < minok || rval > maxok) {
2191		warnx("bad value '%ld' for process number in %s",
2192		    rval, ent->pid_cmd_file);
2193		if (verbose)
2194			warnx("\t(expecting value between %ld and %ld)",
2195			    minok, maxok);
2196	} else {
2197		swork->sw_pidok = 1;
2198		swork->sw_pid = rval;
2199	}
2200
2201	return;
2202}
2203
2204/* Log the fact that the logs were turned over */
2205static int
2206log_trim(const char *logname, const struct conf_entry *log_ent)
2207{
2208	FILE *f;
2209	const char *xtra;
2210
2211	if ((f = fopen(logname, "a")) == NULL)
2212		return (-1);
2213	xtra = "";
2214	if (log_ent->def_cfg)
2215		xtra = " using <default> rule";
2216	if (log_ent->firstcreate)
2217		fprintf(f, "%s %s newsyslog[%d]: logfile first created%s\n",
2218		    daytime, hostname, (int) getpid(), xtra);
2219	else if (log_ent->r_reason != NULL)
2220		fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s%s\n",
2221		    daytime, hostname, (int) getpid(), log_ent->r_reason, xtra);
2222	else
2223		fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s\n",
2224		    daytime, hostname, (int) getpid(), xtra);
2225	if (fclose(f) == EOF)
2226		err(1, "log_trim: fclose");
2227	return (0);
2228}
2229
2230/* Return size in kilobytes of a file */
2231static int
2232sizefile(const char *file)
2233{
2234	struct stat sb;
2235
2236	if (stat(file, &sb) < 0)
2237		return (-1);
2238	return (kbytes(dbtob(sb.st_blocks)));
2239}
2240
2241/* Return the age of old log file (file.0) */
2242static int
2243age_old_log(char *file)
2244{
2245	struct stat sb;
2246	const char *logfile_suffix;
2247	char tmp[MAXPATHLEN + sizeof(".0") + COMPRESS_SUFFIX_MAXLEN + 1];
2248
2249	if (archtodir) {
2250		char *p;
2251
2252		/* build name of archive directory into tmp */
2253		if (*archdirname == '/') {	/* absolute */
2254			strlcpy(tmp, archdirname, sizeof(tmp));
2255		} else {	/* relative */
2256			/* get directory part of logfile */
2257			strlcpy(tmp, file, sizeof(tmp));
2258			if ((p = strrchr(tmp, '/')) == NULL)
2259				tmp[0] = '\0';
2260			else
2261				*(p + 1) = '\0';
2262			strlcat(tmp, archdirname, sizeof(tmp));
2263		}
2264
2265		strlcat(tmp, "/", sizeof(tmp));
2266
2267		/* get filename part of logfile */
2268		if ((p = strrchr(file, '/')) == NULL)
2269			strlcat(tmp, file, sizeof(tmp));
2270		else
2271			strlcat(tmp, p + 1, sizeof(tmp));
2272	} else {
2273		(void) strlcpy(tmp, file, sizeof(tmp));
2274	}
2275
2276	strlcat(tmp, ".0", sizeof(tmp));
2277	logfile_suffix = get_logfile_suffix(tmp);
2278	if (logfile_suffix == NULL)
2279		return (-1);
2280	(void) strlcat(tmp, logfile_suffix, sizeof(tmp));
2281	if (stat(tmp, &sb) < 0)
2282		return (-1);
2283	return ((int)(ptimeget_secs(timenow) - sb.st_mtime + 1800) / 3600);
2284}
2285
2286/* Skip Over Blanks */
2287static char *
2288sob(char *p)
2289{
2290	while (p && *p && isspace(*p))
2291		p++;
2292	return (p);
2293}
2294
2295/* Skip Over Non-Blanks */
2296static char *
2297son(char *p)
2298{
2299	while (p && *p && !isspace(*p))
2300		p++;
2301	return (p);
2302}
2303
2304/* Check if string is actually a number */
2305static int
2306isnumberstr(const char *string)
2307{
2308	while (*string) {
2309		if (!isdigitch(*string++))
2310			return (0);
2311	}
2312	return (1);
2313}
2314
2315/* Check if string contains a glob */
2316static int
2317isglobstr(const char *string)
2318{
2319	char chr;
2320
2321	while ((chr = *string++)) {
2322		if (chr == '*' || chr == '?' || chr == '[')
2323			return (1);
2324	}
2325	return (0);
2326}
2327
2328/*
2329 * Save the active log file under a new name.  A link to the new name
2330 * is the quick-and-easy way to do this.  If that fails (which it will
2331 * if the destination is on another partition), then make a copy of
2332 * the file to the new location.
2333 */
2334static void
2335savelog(char *from, char *to)
2336{
2337	FILE *src, *dst;
2338	int c, res;
2339
2340	res = link(from, to);
2341	if (res == 0)
2342		return;
2343
2344	if ((src = fopen(from, "r")) == NULL)
2345		err(1, "can't fopen %s for reading", from);
2346	if ((dst = fopen(to, "w")) == NULL)
2347		err(1, "can't fopen %s for writing", to);
2348
2349	while ((c = getc(src)) != EOF) {
2350		if ((putc(c, dst)) == EOF)
2351			err(1, "error writing to %s", to);
2352	}
2353
2354	if (ferror(src))
2355		err(1, "error reading from %s", from);
2356	if ((fclose(src)) != 0)
2357		err(1, "can't fclose %s", to);
2358	if ((fclose(dst)) != 0)
2359		err(1, "can't fclose %s", from);
2360}
2361
2362/* create one or more directory components of a path */
2363static void
2364createdir(const struct conf_entry *ent, char *dirpart)
2365{
2366	int res;
2367	char *s, *d;
2368	char mkdirpath[MAXPATHLEN];
2369	struct stat st;
2370
2371	s = dirpart;
2372	d = mkdirpath;
2373
2374	for (;;) {
2375		*d++ = *s++;
2376		if (*s != '/' && *s != '\0')
2377			continue;
2378		*d = '\0';
2379		res = lstat(mkdirpath, &st);
2380		if (res != 0) {
2381			if (noaction) {
2382				printf("\tmkdir %s\n", mkdirpath);
2383			} else {
2384				res = mkdir(mkdirpath, 0755);
2385				if (res != 0)
2386					err(1, "Error on mkdir(\"%s\") for -a",
2387					    mkdirpath);
2388			}
2389		}
2390		if (*s == '\0')
2391			break;
2392	}
2393	if (verbose) {
2394		if (ent->firstcreate)
2395			printf("Created directory '%s' for new %s\n",
2396			    dirpart, ent->log);
2397		else
2398			printf("Created directory '%s' for -a\n", dirpart);
2399	}
2400}
2401
2402/*
2403 * Create a new log file, destroying any currently-existing version
2404 * of the log file in the process.  If the caller wants a backup copy
2405 * of the file to exist, they should call 'link(logfile,logbackup)'
2406 * before calling this routine.
2407 */
2408void
2409createlog(const struct conf_entry *ent)
2410{
2411	int fd, failed;
2412	struct stat st;
2413	char *realfile, *slash, tempfile[MAXPATHLEN];
2414
2415	fd = -1;
2416	realfile = ent->log;
2417
2418	/*
2419	 * If this log file is being created for the first time (-C option),
2420	 * then it may also be true that the parent directory does not exist
2421	 * yet.  Check, and create that directory if it is missing.
2422	 */
2423	if (ent->firstcreate) {
2424		strlcpy(tempfile, realfile, sizeof(tempfile));
2425		slash = strrchr(tempfile, '/');
2426		if (slash != NULL) {
2427			*slash = '\0';
2428			failed = stat(tempfile, &st);
2429			if (failed && errno != ENOENT)
2430				err(1, "Error on stat(%s)", tempfile);
2431			if (failed)
2432				createdir(ent, tempfile);
2433			else if (!S_ISDIR(st.st_mode))
2434				errx(1, "%s exists but is not a directory",
2435				    tempfile);
2436		}
2437	}
2438
2439	/*
2440	 * First create an unused filename, so it can be chown'ed and
2441	 * chmod'ed before it is moved into the real location.  mkstemp
2442	 * will create the file mode=600 & owned by us.  Note that all
2443	 * temp files will have a suffix of '.z<something>'.
2444	 */
2445	strlcpy(tempfile, realfile, sizeof(tempfile));
2446	strlcat(tempfile, ".zXXXXXX", sizeof(tempfile));
2447	if (noaction)
2448		printf("\tmktemp %s\n", tempfile);
2449	else {
2450		fd = mkstemp(tempfile);
2451		if (fd < 0)
2452			err(1, "can't mkstemp logfile %s", tempfile);
2453
2454		/*
2455		 * Add status message to what will become the new log file.
2456		 */
2457		if (!(ent->flags & CE_BINARY)) {
2458			if (log_trim(tempfile, ent))
2459				err(1, "can't add status message to log");
2460		}
2461	}
2462
2463	/* Change the owner/group, if we are supposed to */
2464	if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2465		if (noaction)
2466			printf("\tchown %u:%u %s\n", ent->uid, ent->gid,
2467			    tempfile);
2468		else {
2469			failed = fchown(fd, ent->uid, ent->gid);
2470			if (failed)
2471				err(1, "can't fchown temp file %s", tempfile);
2472		}
2473	}
2474
2475	/* Turn on NODUMP if it was requested in the config-file. */
2476	if (ent->flags & CE_NODUMP) {
2477		if (noaction)
2478			printf("\tchflags nodump %s\n", tempfile);
2479		else {
2480			failed = fchflags(fd, UF_NODUMP);
2481			if (failed) {
2482				warn("log_trim: fchflags(NODUMP)");
2483			}
2484		}
2485	}
2486
2487	/*
2488	 * Note that if the real logfile still exists, and if the call
2489	 * to rename() fails, then "neither the old file nor the new
2490	 * file shall be changed or created" (to quote the standard).
2491	 * If the call succeeds, then the file will be replaced without
2492	 * any window where some other process might find that the file
2493	 * did not exist.
2494	 * XXX - ? It may be that for some error conditions, we could
2495	 *	retry by first removing the realfile and then renaming.
2496	 */
2497	if (noaction) {
2498		printf("\tchmod %o %s\n", ent->permissions, tempfile);
2499		printf("\tmv %s %s\n", tempfile, realfile);
2500	} else {
2501		failed = fchmod(fd, ent->permissions);
2502		if (failed)
2503			err(1, "can't fchmod temp file '%s'", tempfile);
2504		failed = rename(tempfile, realfile);
2505		if (failed)
2506			err(1, "can't mv %s to %s", tempfile, realfile);
2507	}
2508
2509	if (fd >= 0)
2510		close(fd);
2511}
2512
2513/*
2514 * Change the attributes of a given filename to what was specified in
2515 * the newsyslog.conf entry.  This routine is only called for files
2516 * that newsyslog expects that it has created, and thus it is a fatal
2517 * error if this routine finds that the file does not exist.
2518 */
2519static void
2520change_attrs(const char *fname, const struct conf_entry *ent)
2521{
2522	int failed;
2523
2524	if (noaction) {
2525		printf("\tchmod %o %s\n", ent->permissions, fname);
2526
2527		if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
2528			printf("\tchown %u:%u %s\n",
2529			    ent->uid, ent->gid, fname);
2530
2531		if (ent->flags & CE_NODUMP)
2532			printf("\tchflags nodump %s\n", fname);
2533		return;
2534	}
2535
2536	failed = chmod(fname, ent->permissions);
2537	if (failed) {
2538		if (errno != EPERM)
2539			err(1, "chmod(%s) in change_attrs", fname);
2540		warn("change_attrs couldn't chmod(%s)", fname);
2541	}
2542
2543	if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2544		failed = chown(fname, ent->uid, ent->gid);
2545		if (failed)
2546			warn("can't chown %s", fname);
2547	}
2548
2549	if (ent->flags & CE_NODUMP) {
2550		failed = chflags(fname, UF_NODUMP);
2551		if (failed)
2552			warn("can't chflags %s NODUMP", fname);
2553	}
2554}
2555