1130167Sgad/*-
2130167Sgad * ------+---------+---------+-------- + --------+---------+---------+---------*
3130167Sgad * This file includes significant modifications done by:
4130167Sgad * Copyright (c) 2003, 2004  - Garance Alistair Drosehn <gad@FreeBSD.org>.
5130167Sgad * All rights reserved.
6130167Sgad *
7130167Sgad * Redistribution and use in source and binary forms, with or without
8130167Sgad * modification, are permitted provided that the following conditions
9130167Sgad * are met:
10130167Sgad *   1. Redistributions of source code must retain the above copyright
11130167Sgad *      notice, this list of conditions and the following disclaimer.
12130167Sgad *   2. Redistributions in binary form must reproduce the above copyright
13130167Sgad *      notice, this list of conditions and the following disclaimer in the
14130167Sgad *      documentation and/or other materials provided with the distribution.
15130167Sgad *
16130167Sgad * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17130167Sgad * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18130167Sgad * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19130167Sgad * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20130167Sgad * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21130167Sgad * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22130167Sgad * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23130167Sgad * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24130167Sgad * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25130167Sgad * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26130167Sgad * SUCH DAMAGE.
27130167Sgad *
28130167Sgad * ------+---------+---------+-------- + --------+---------+---------+---------*
29130167Sgad */
30130167Sgad
3113244Sgraichen/*
3213244Sgraichen * This file contains changes from the Open Software Foundation.
3313244Sgraichen */
3413244Sgraichen
3513244Sgraichen/*
3659004Shm * Copyright 1988, 1989 by the Massachusetts Institute of Technology
3759004Shm *
3859004Shm * Permission to use, copy, modify, and distribute this software and its
3959004Shm * documentation for any purpose and without fee is hereby granted, provided
4059004Shm * that the above copyright notice appear in all copies and that both that
4159004Shm * copyright notice and this permission notice appear in supporting
4259004Shm * documentation, and that the names of M.I.T. and the M.I.T. S.I.P.B. not be
4359004Shm * used in advertising or publicity pertaining to distribution of the
4459004Shm * software without specific, written prior permission. M.I.T. and the M.I.T.
4559004Shm * S.I.P.B. make no representations about the suitability of this software
4659004Shm * for any purpose.  It is provided "as is" without express or implied
4759004Shm * warranty.
4859004Shm *
4959004Shm */
5013244Sgraichen
5113244Sgraichen/*
5259004Shm * newsyslog - roll over selected logs at the appropriate time, keeping the a
5359004Shm * specified number of backup files around.
5413244Sgraichen */
5513244Sgraichen
56114601Sobrien#include <sys/cdefs.h>
57114601Sobrien__FBSDID("$FreeBSD: stable/10/usr.sbin/newsyslog/newsyslog.c 344882 2019-03-07 13:11:00Z dab $");
5813244Sgraichen
59130045Sgad#define	OSF
6013244Sgraichen
6196001Smaxim#include <sys/param.h>
62130167Sgad#include <sys/queue.h>
6396001Smaxim#include <sys/stat.h>
6496001Smaxim#include <sys/wait.h>
6596001Smaxim
66210372Ssimon#include <assert.h>
6730160Scharnier#include <ctype.h>
6830160Scharnier#include <err.h>
6995999Smaxim#include <errno.h>
70210372Ssimon#include <dirent.h>
7130160Scharnier#include <fcntl.h>
72111773Sgad#include <fnmatch.h>
73106905Ssobomax#include <glob.h>
7430160Scharnier#include <grp.h>
7543071Swollman#include <paths.h>
7630160Scharnier#include <pwd.h>
7730160Scharnier#include <signal.h>
7813244Sgraichen#include <stdio.h>
79210372Ssimon#include <libgen.h>
8013244Sgraichen#include <stdlib.h>
8113244Sgraichen#include <string.h>
82321263Sngie#include <syslog.h>
8343071Swollman#include <time.h>
8416240Salex#include <unistd.h>
8513244Sgraichen
8643071Swollman#include "pathnames.h"
87119998Sgad#include "extern.h"
8843071Swollman
89111768Sgad/*
90218127Smm * Compression suffixes
91218127Smm */
92218127Smm#ifndef	COMPRESS_SUFFIX_GZ
93218127Smm#define	COMPRESS_SUFFIX_GZ	".gz"
94218127Smm#endif
95218127Smm
96218127Smm#ifndef	COMPRESS_SUFFIX_BZ2
97218127Smm#define	COMPRESS_SUFFIX_BZ2	".bz2"
98218127Smm#endif
99218127Smm
100218127Smm#ifndef	COMPRESS_SUFFIX_XZ
101218127Smm#define	COMPRESS_SUFFIX_XZ	".xz"
102218127Smm#endif
103218127Smm
104218127Smm#define	COMPRESS_SUFFIX_MAXLEN	MAX(MAX(sizeof(COMPRESS_SUFFIX_GZ),sizeof(COMPRESS_SUFFIX_BZ2)),sizeof(COMPRESS_SUFFIX_XZ))
105218127Smm
106218127Smm/*
107218127Smm * Compression types
108218127Smm */
109218127Smm#define	COMPRESS_TYPES  4	/* Number of supported compression types */
110218127Smm
111218127Smm#define	COMPRESS_NONE	0
112218127Smm#define	COMPRESS_GZIP	1
113218127Smm#define	COMPRESS_BZIP2	2
114218127Smm#define	COMPRESS_XZ	3
115218127Smm
116218127Smm/*
117111768Sgad * Bit-values for the 'flags' parsed from a config-file entry.
118111768Sgad */
119130045Sgad#define	CE_BINARY	0x0008	/* Logfile is in binary, do not add status */
120111768Sgad				/*    messages to logfile(s) when rotating. */
121130045Sgad#define	CE_NOSIGNAL	0x0010	/* There is no process to signal when */
122111768Sgad				/*    trimming this file. */
123130045Sgad#define	CE_TRIMAT	0x0020	/* trim file at a specific time. */
124130045Sgad#define	CE_GLOB		0x0040	/* name of the log is file name pattern. */
125130045Sgad#define	CE_SIGNALGROUP	0x0080	/* Signal a process-group instead of a single */
126112003Sgad				/*    process when trimming this file. */
127130045Sgad#define	CE_CREATE	0x0100	/* Create the log file if it does not exist. */
128130043Sgad#define	CE_NODUMP	0x0200	/* Set 'nodump' on newly created log file. */
129221873Ssobomax#define	CE_PID2CMD	0x0400	/* Replace PID file with a shell command.*/
13043071Swollman
131321263Sngie#define	CE_RFC5424	0x0800	/* Use RFC5424 format rotation message */
132321263Sngie
133130045Sgad#define	MIN_PID         5	/* Don't touch pids lower than this */
134130045Sgad#define	MAX_PID		99999	/* was lower, see /usr/include/sys/proc.h */
135111781Sgad
136130045Sgad#define	kbytes(size)  (((size) + 1023) >> 10)
137111781Sgad
138130165Sgad#define	DEFAULT_MARKER	"<default>"
139130165Sgad#define	DEBUG_MARKER	"<debug>"
140208649Sgordon#define	INCLUDE_MARKER	"<include>"
141210372Ssimon#define	DEFAULT_TIMEFNAME_FMT	"%Y%m%dT%H%M%S"
142130165Sgad
143210372Ssimon#define	MAX_OLDLOGS 65536	/* Default maximum number of old logfiles */
144210372Ssimon
145218127Smmstruct compress_types {
146218127Smm	const char *flag;	/* Flag in configuration file */
147218127Smm	const char *suffix;	/* Compression suffix */
148218127Smm	const char *path;	/* Path to compression program */
149218127Smm};
150218127Smm
151241777Sedstatic const struct compress_types compress_type[COMPRESS_TYPES] = {
152218127Smm	{ "", "", "" },					/* no compression */
153218127Smm	{ "Z", COMPRESS_SUFFIX_GZ, _PATH_GZIP },	/* gzip compression */
154218127Smm	{ "J", COMPRESS_SUFFIX_BZ2, _PATH_BZIP2 },	/* bzip2 compression */
155218127Smm	{ "X", COMPRESS_SUFFIX_XZ, _PATH_XZ }		/* xz compression */
156218127Smm};
157218127Smm
15813244Sgraichenstruct conf_entry {
159208648Sgordon	STAILQ_ENTRY(conf_entry) cf_nextp;
16059003Shm	char *log;		/* Name of the log */
161221873Ssobomax	char *pid_cmd_file;		/* PID or command file */
162111772Sgad	char *r_reason;		/* The reason this file is being rotated */
163114137Sgad	int firstcreate;	/* Creating log for the first time (-C). */
164111772Sgad	int rotate;		/* Non-zero if this file should be rotated */
165130165Sgad	int fsize;		/* size found for the log file */
166111779Sgad	uid_t uid;		/* Owner of log */
167111779Sgad	gid_t gid;		/* Group of log */
16859003Shm	int numlogs;		/* Number of logs to keep */
169130165Sgad	int trsize;		/* Size cutoff to trigger trimming the log */
17059003Shm	int hours;		/* Hours between log trimming */
171120361Sgad	struct ptime_data *trim_at;	/* Specific time to do trimming */
172139655Sdelphij	unsigned int permissions;	/* File permissions on the log */
173218127Smm	int flags;		/* CE_BINARY */
174218127Smm	int compress;		/* Compression */
17559003Shm	int sig;		/* Signal to send */
176111388Sgad	int def_cfg;		/* Using the <default> rule for this file */
17713244Sgraichen};
17813244Sgraichen
179130167Sgadstruct sigwork_entry {
180130167Sgad	SLIST_ENTRY(sigwork_entry) sw_nextp;
181130167Sgad	int	 sw_signum;		/* the signal to send */
182130167Sgad	int	 sw_pidok;		/* true if pid value is valid */
183130167Sgad	pid_t	 sw_pid;		/* the process id from the PID file */
184130167Sgad	const char *sw_pidtype;		/* "daemon" or "process group" */
185245963Smarkj	int	 sw_runcmd;		/* run command or send PID to signal */
186221873Ssobomax	char	 sw_fname[1];		/* file the PID was read from or shell cmd */
187130167Sgad};
188130167Sgad
189130167Sgadstruct zipwork_entry {
190130167Sgad	SLIST_ENTRY(zipwork_entry) zw_nextp;
191130167Sgad	const struct conf_entry *zw_conf;	/* for chown/perm/flag info */
192130167Sgad	const struct sigwork_entry *zw_swork;	/* to know success of signal */
193130167Sgad	int	 zw_fsize;		/* size of the file to compress */
194130167Sgad	char	 zw_fname[1];		/* the file to compress */
195130167Sgad};
196130167Sgad
197208649Sgordonstruct include_entry {
198208649Sgordon	STAILQ_ENTRY(include_entry) inc_nextp;
199208649Sgordon	const char *file;	/* Name of file to process */
200208649Sgordon};
201208649Sgordon
202210372Ssimonstruct oldlog_entry {
203210372Ssimon	char *fname;		/* Filename of the log file */
204215625Ssimon	time_t t;		/* Parsed timestamp of the logfile */
205210372Ssimon};
206210372Ssimon
207130165Sgadtypedef enum {
208130165Sgad	FREE_ENT, KEEP_ENT
209130165Sgad}	fk_entry;
210111388Sgad
211208648SgordonSTAILQ_HEAD(cflist, conf_entry);
212241777Sedstatic SLIST_HEAD(swlisthead, sigwork_entry) swhead =
213241777Sed    SLIST_HEAD_INITIALIZER(swhead);
214241777Sedstatic SLIST_HEAD(zwlisthead, zipwork_entry) zwhead =
215241777Sed    SLIST_HEAD_INITIALIZER(zwhead);
216208649SgordonSTAILQ_HEAD(ilist, include_entry);
217130167Sgad
218120361Sgadint dbg_at_times;		/* -D Show details of 'trim_at' code */
219120361Sgad
220241777Sedstatic int archtodir = 0;	/* Archive old logfiles to other directory */
221241777Sedstatic int createlogs;		/* Create (non-GLOB) logfiles which do not */
222114137Sgad				/*    already exist.  1=='for entries with */
223114137Sgad				/*    C flag', 2=='for all entries'. */
22459003Shmint verbose = 0;		/* Print out what's going on */
225241777Sedstatic int needroot = 1;	/* Root privs are necessary */
22659003Shmint noaction = 0;		/* Don't do anything, just show it */
227241777Sedstatic int norotate = 0;	/* Don't rotate */
228241777Sedstatic int nosignal;		/* Do not send any signals */
229241777Sedstatic int enforcepid = 0;	/* If PID file does not exist or empty, do nothing */
230241777Sedstatic int force = 0;		/* Force the trim no matter what */
231241777Sedstatic int rotatereq = 0;	/* -R = Always rotate the file(s) as given */
232111772Sgad				/*    on the command (this also requires   */
233111772Sgad				/*    that a list of files *are* given on  */
234111772Sgad				/*    the run command). */
235241777Sedstatic char *requestor;		/* The name given on a -R request */
236241777Sedstatic char *timefnamefmt = NULL;/* Use time based filenames instead of .0 */
237241777Sedstatic char *archdirname;	/* Directory path to old logfiles archive */
238241777Sedstatic char *destdir = NULL;	/* Directory to treat at root for logs */
239241777Sedstatic const char *conf;	/* Configuration file to use */
24059003Shm
241120361Sgadstruct ptime_data *dbg_timenow;	/* A "timenow" value set via -D option */
242241777Sedstatic struct ptime_data *timenow; /* The time to use for checking at-fields */
243120361Sgad
244159998Sgad#define	DAYTIME_LEN	16
245241777Sedstatic char daytime[DAYTIME_LEN];/* The current time in human readable form,
246241777Sed				  * used for rotation-tracking messages. */
247321263Sngie
248321263Sngie/* Another buffer to hold the current time in RFC5424 format. Fractional
249321263Sngie * seconds are allowed by the RFC, but are not included in the
250321263Sngie * rotation-tracking messages written by newsyslog and so are not accounted for
251321263Sngie * in the length below.
252321263Sngie */
253321263Sngie#define	DAYTIME_RFC5424_LEN	sizeof("YYYY-MM-DDTHH:MM:SS+00:00")
254321263Sngiestatic char daytime_rfc5424[DAYTIME_RFC5424_LEN];
255321263Sngie
256241777Sedstatic char hostname[MAXHOSTNAMELEN]; /* hostname */
25713244Sgraichen
258241777Sedstatic const char *path_syslogpid = _PATH_SYSLOGPID;
259210407Sbrian
260208648Sgordonstatic struct cflist *get_worklist(char **files);
261208648Sgordonstatic void parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
262344882Sdab		    struct conf_entry **defconf, struct ilist *inclist);
263208649Sgordonstatic void add_to_queue(const char *fname, struct ilist *inclist);
26416240Salexstatic char *sob(char *p);
26516240Salexstatic char *son(char *p);
266119102Sgadstatic int isnumberstr(const char *);
267208649Sgordonstatic int isglobstr(const char *);
26859003Shmstatic char *missing_field(char *p, char *errline);
269130165Sgadstatic void	 change_attrs(const char *, const struct conf_entry *);
270218127Smmstatic const char *get_logfile_suffix(const char *logfile);
271130165Sgadstatic fk_entry	 do_entry(struct conf_entry *);
272130165Sgadstatic fk_entry	 do_rotate(const struct conf_entry *);
273130167Sgadstatic void	 do_sigwork(struct sigwork_entry *);
274130167Sgadstatic void	 do_zipwork(struct zipwork_entry *);
275130167Sgadstatic struct sigwork_entry *
276130167Sgad		 save_sigwork(const struct conf_entry *);
277130167Sgadstatic struct zipwork_entry *
278130167Sgad		 save_zipwork(const struct conf_entry *, const struct
279130167Sgad		    sigwork_entry *, int, const char *);
280130167Sgadstatic void	 set_swpid(struct sigwork_entry *, const struct conf_entry *);
281130165Sgadstatic int	 sizefile(const char *);
282208648Sgordonstatic void expand_globs(struct cflist *work_p, struct cflist *glob_p);
283208648Sgordonstatic void free_clist(struct cflist *list);
284111388Sgadstatic void free_entry(struct conf_entry *ent);
285111388Sgadstatic struct conf_entry *init_entry(const char *fname,
286111388Sgad		struct conf_entry *src_entry);
287111781Sgadstatic void parse_args(int argc, char **argv);
288119904Sgadstatic int parse_doption(const char *doption);
28980640Sobrienstatic void usage(void);
290119926Sgadstatic int log_trim(const char *logname, const struct conf_entry *log_ent);
291248776Smarkjstatic int age_old_log(const char *file);
292130038Sgadstatic void savelog(char *from, char *to);
293114137Sgadstatic void createdir(const struct conf_entry *ent, char *dirpart);
294114137Sgadstatic void createlog(const struct conf_entry *ent);
295290225Sbaptstatic int parse_signal(const char *str);
29613244Sgraichen
297111768Sgad/*
298129975Sgad * All the following take a parameter of 'int', but expect values in the
299129975Sgad * range of unsigned char.  Define wrappers which take values of type 'char',
300129975Sgad * whether signed or unsigned, and ensure they end up in the right range.
301111768Sgad */
302129975Sgad#define	isdigitch(Anychar) isdigit((u_char)(Anychar))
303129975Sgad#define	isprintch(Anychar) isprint((u_char)(Anychar))
304129975Sgad#define	isspacech(Anychar) isspace((u_char)(Anychar))
305129975Sgad#define	tolowerch(Anychar) tolower((u_char)(Anychar))
306111768Sgad
30759004Shmint
30859004Shmmain(int argc, char **argv)
30913244Sgraichen{
310208648Sgordon	struct cflist *worklist;
311208648Sgordon	struct conf_entry *p;
312130167Sgad	struct sigwork_entry *stmp;
313130167Sgad	struct zipwork_entry *ztmp;
31425443Sache
315130167Sgad	SLIST_INIT(&swhead);
316130167Sgad	SLIST_INIT(&zwhead);
317130167Sgad
318111781Sgad	parse_args(argc, argv);
319111773Sgad	argc -= optind;
320111773Sgad	argv += optind;
321111773Sgad
32259003Shm	if (needroot && getuid() && geteuid())
32359003Shm		errx(1, "must have root privs");
324208648Sgordon	worklist = get_worklist(argv);
32559003Shm
326130165Sgad	/*
327130165Sgad	 * Rotate all the files which need to be rotated.  Note that
328130165Sgad	 * some users have *hundreds* of entries in newsyslog.conf!
329130165Sgad	 */
330208648Sgordon	while (!STAILQ_EMPTY(worklist)) {
331208648Sgordon		p = STAILQ_FIRST(worklist);
332208648Sgordon		STAILQ_REMOVE_HEAD(worklist, cf_nextp);
333208648Sgordon		if (do_entry(p) == FREE_ENT)
334208648Sgordon			free_entry(p);
33559003Shm	}
336130165Sgad
337130167Sgad	/*
338130167Sgad	 * Send signals to any processes which need a signal to tell
339130167Sgad	 * them to close and re-open the log file(s) we have rotated.
340130167Sgad	 * Note that zipwork_entries include pointers to these
341130167Sgad	 * sigwork_entry's, so we can not free the entries here.
342130167Sgad	 */
343130167Sgad	if (!SLIST_EMPTY(&swhead)) {
344130204Sgad		if (noaction || verbose)
345130167Sgad			printf("Signal all daemon process(es)...\n");
346130167Sgad		SLIST_FOREACH(stmp, &swhead, sw_nextp)
347130167Sgad			do_sigwork(stmp);
348301926Svangyzen		if (!(rotatereq && nosignal)) {
349301926Svangyzen			if (noaction)
350301926Svangyzen				printf("\tsleep 10\n");
351301926Svangyzen			else {
352301926Svangyzen				if (verbose)
353301926Svangyzen					printf("Pause 10 seconds to allow "
354301926Svangyzen					    "daemon(s) to close log file(s)\n");
355301926Svangyzen				sleep(10);
356301926Svangyzen			}
357130204Sgad		}
358130167Sgad	}
359130167Sgad	/*
360130167Sgad	 * Compress all files that we're expected to compress, now
361130167Sgad	 * that all processes should have closed the files which
362130167Sgad	 * have been rotated.
363130167Sgad	 */
364130167Sgad	if (!SLIST_EMPTY(&zwhead)) {
365130204Sgad		if (noaction || verbose)
366130167Sgad			printf("Compress all rotated log file(s)...\n");
367130167Sgad		while (!SLIST_EMPTY(&zwhead)) {
368130167Sgad			ztmp = SLIST_FIRST(&zwhead);
369130167Sgad			do_zipwork(ztmp);
370130167Sgad			SLIST_REMOVE_HEAD(&zwhead, zw_nextp);
371130167Sgad			free(ztmp);
372130167Sgad		}
373130167Sgad	}
374130167Sgad	/* Now free all the sigwork entries. */
375130167Sgad	while (!SLIST_EMPTY(&swhead)) {
376130167Sgad		stmp = SLIST_FIRST(&swhead);
377130167Sgad		SLIST_REMOVE_HEAD(&swhead, sw_nextp);
378130167Sgad		free(stmp);
379130167Sgad	}
380130167Sgad
38195999Smaxim	while (wait(NULL) > 0 || errno == EINTR)
38295999Smaxim		;
38359003Shm	return (0);
38413244Sgraichen}
38513244Sgraichen
386111388Sgadstatic struct conf_entry *
387111388Sgadinit_entry(const char *fname, struct conf_entry *src_entry)
388111388Sgad{
389111388Sgad	struct conf_entry *tempwork;
390111388Sgad
391111388Sgad	if (verbose > 4)
392111388Sgad		printf("\t--> [creating entry for %s]\n", fname);
393111388Sgad
394111388Sgad	tempwork = malloc(sizeof(struct conf_entry));
395111388Sgad	if (tempwork == NULL)
396111388Sgad		err(1, "malloc of conf_entry for %s", fname);
397111388Sgad
398136174Sbrooks	if (destdir == NULL || fname[0] != '/')
399136127Sbrooks		tempwork->log = strdup(fname);
400136127Sbrooks	else
401136127Sbrooks		asprintf(&tempwork->log, "%s%s", destdir, fname);
402111388Sgad	if (tempwork->log == NULL)
403111388Sgad		err(1, "strdup for %s", fname);
404111388Sgad
405111388Sgad	if (src_entry != NULL) {
406221873Ssobomax		tempwork->pid_cmd_file = NULL;
407221873Ssobomax		if (src_entry->pid_cmd_file)
408221873Ssobomax			tempwork->pid_cmd_file = strdup(src_entry->pid_cmd_file);
409111772Sgad		tempwork->r_reason = NULL;
410114137Sgad		tempwork->firstcreate = 0;
411111772Sgad		tempwork->rotate = 0;
412130165Sgad		tempwork->fsize = -1;
413111388Sgad		tempwork->uid = src_entry->uid;
414111388Sgad		tempwork->gid = src_entry->gid;
415111388Sgad		tempwork->numlogs = src_entry->numlogs;
416130165Sgad		tempwork->trsize = src_entry->trsize;
417111388Sgad		tempwork->hours = src_entry->hours;
418120361Sgad		tempwork->trim_at = NULL;
419120361Sgad		if (src_entry->trim_at != NULL)
420120361Sgad			tempwork->trim_at = ptime_init(src_entry->trim_at);
421111388Sgad		tempwork->permissions = src_entry->permissions;
422111388Sgad		tempwork->flags = src_entry->flags;
423218127Smm		tempwork->compress = src_entry->compress;
424111388Sgad		tempwork->sig = src_entry->sig;
425111388Sgad		tempwork->def_cfg = src_entry->def_cfg;
426111388Sgad	} else {
427111388Sgad		/* Initialize as a "do-nothing" entry */
428221873Ssobomax		tempwork->pid_cmd_file = NULL;
429111772Sgad		tempwork->r_reason = NULL;
430114137Sgad		tempwork->firstcreate = 0;
431111772Sgad		tempwork->rotate = 0;
432130165Sgad		tempwork->fsize = -1;
433111779Sgad		tempwork->uid = (uid_t)-1;
434111779Sgad		tempwork->gid = (gid_t)-1;
435111388Sgad		tempwork->numlogs = 1;
436130165Sgad		tempwork->trsize = -1;
437111388Sgad		tempwork->hours = -1;
438120361Sgad		tempwork->trim_at = NULL;
439111388Sgad		tempwork->permissions = 0;
440111388Sgad		tempwork->flags = 0;
441218127Smm		tempwork->compress = COMPRESS_NONE;
442111388Sgad		tempwork->sig = SIGHUP;
443111388Sgad		tempwork->def_cfg = 0;
444111388Sgad	}
445111388Sgad
446111388Sgad	return (tempwork);
447111388Sgad}
448111388Sgad
44959004Shmstatic void
450111388Sgadfree_entry(struct conf_entry *ent)
451111388Sgad{
452111388Sgad
453111388Sgad	if (ent == NULL)
454111388Sgad		return;
455111388Sgad
456111388Sgad	if (ent->log != NULL) {
457111388Sgad		if (verbose > 4)
458111388Sgad			printf("\t--> [freeing entry for %s]\n", ent->log);
459111388Sgad		free(ent->log);
460111388Sgad		ent->log = NULL;
461111388Sgad	}
462111388Sgad
463221873Ssobomax	if (ent->pid_cmd_file != NULL) {
464221873Ssobomax		free(ent->pid_cmd_file);
465221873Ssobomax		ent->pid_cmd_file = NULL;
466111388Sgad	}
467111388Sgad
468111772Sgad	if (ent->r_reason != NULL) {
469111772Sgad		free(ent->r_reason);
470111772Sgad		ent->r_reason = NULL;
471111772Sgad	}
472111772Sgad
473120361Sgad	if (ent->trim_at != NULL) {
474120361Sgad		ptime_free(ent->trim_at);
475120361Sgad		ent->trim_at = NULL;
476120361Sgad	}
477120361Sgad
478111388Sgad	free(ent);
479111388Sgad}
480111388Sgad
481111388Sgadstatic void
482208648Sgordonfree_clist(struct cflist *list)
483112020Sgad{
484208648Sgordon	struct conf_entry *ent;
485112020Sgad
486208648Sgordon	while (!STAILQ_EMPTY(list)) {
487208648Sgordon		ent = STAILQ_FIRST(list);
488208648Sgordon		STAILQ_REMOVE_HEAD(list, cf_nextp);
489112020Sgad		free_entry(ent);
490112020Sgad	}
491208648Sgordon
492208648Sgordon	free(list);
493208648Sgordon	list = NULL;
494112020Sgad}
495112020Sgad
496130165Sgadstatic fk_entry
49759004Shmdo_entry(struct conf_entry * ent)
49813244Sgraichen{
499130045Sgad#define	REASON_MAX	80
500130165Sgad	int modtime;
501130165Sgad	fk_entry free_or_keep;
502120361Sgad	double diffsecs;
503111772Sgad	char temp_reason[REASON_MAX];
504233257Sglebius	int oversized;
50559003Shm
506130165Sgad	free_or_keep = FREE_ENT;
507218127Smm	if (verbose)
508218127Smm		printf("%s <%d%s>: ", ent->log, ent->numlogs,
509218127Smm		    compress_type[ent->compress].flag);
510130165Sgad	ent->fsize = sizefile(ent->log);
511233257Sglebius	oversized = ((ent->trsize > 0) && (ent->fsize >= ent->trsize));
51259003Shm	modtime = age_old_log(ent->log);
513111772Sgad	ent->rotate = 0;
514114137Sgad	ent->firstcreate = 0;
515130165Sgad	if (ent->fsize < 0) {
516114137Sgad		/*
517114137Sgad		 * If either the C flag or the -C option was specified,
518114137Sgad		 * and if we won't be creating the file, then have the
519114137Sgad		 * verbose message include a hint as to why the file
520114137Sgad		 * will not be created.
521114137Sgad		 */
522114137Sgad		temp_reason[0] = '\0';
523114137Sgad		if (createlogs > 1)
524114137Sgad			ent->firstcreate = 1;
525114137Sgad		else if ((ent->flags & CE_CREATE) && createlogs)
526114137Sgad			ent->firstcreate = 1;
527114137Sgad		else if (ent->flags & CE_CREATE)
528159998Sgad			strlcpy(temp_reason, " (no -C option)", REASON_MAX);
529114137Sgad		else if (createlogs)
530159998Sgad			strlcpy(temp_reason, " (no C flag)", REASON_MAX);
531114137Sgad
532114137Sgad		if (ent->firstcreate) {
533114137Sgad			if (verbose)
534114137Sgad				printf("does not exist -> will create.\n");
535114137Sgad			createlog(ent);
536114137Sgad		} else if (verbose) {
537114137Sgad			printf("does not exist, skipped%s.\n", temp_reason);
538114137Sgad		}
53959003Shm	} else {
540233257Sglebius		if (ent->flags & CE_TRIMAT && !force && !rotatereq &&
541233257Sglebius		    !oversized) {
542120361Sgad			diffsecs = ptimeget_diff(timenow, ent->trim_at);
543120361Sgad			if (diffsecs < 0.0) {
544120361Sgad				/* trim_at is some time in the future. */
545120361Sgad				if (verbose) {
546120361Sgad					ptime_adjust4dst(ent->trim_at,
547120361Sgad					    timenow);
54843071Swollman					printf("--> will trim at %s",
549120361Sgad					    ptimeget_ctime(ent->trim_at));
550120361Sgad				}
551130165Sgad				return (free_or_keep);
552120361Sgad			} else if (diffsecs >= 3600.0) {
553120361Sgad				/*
554120361Sgad				 * trim_at is more than an hour in the past,
555120361Sgad				 * so find the next valid trim_at time, and
556120361Sgad				 * tell the user what that will be.
557120361Sgad				 */
558120361Sgad				if (verbose && dbg_at_times)
559120361Sgad					printf("\n\t--> prev trim at %s\t",
560120361Sgad					    ptimeget_ctime(ent->trim_at));
561120361Sgad				if (verbose) {
562120361Sgad					ptimeset_nxtime(ent->trim_at);
563120361Sgad					printf("--> will trim at %s",
564120361Sgad					    ptimeget_ctime(ent->trim_at));
565120361Sgad				}
566130165Sgad				return (free_or_keep);
567120361Sgad			} else if (verbose && noaction && dbg_at_times) {
568120361Sgad				/*
569120361Sgad				 * If we are just debugging at-times, then
570120361Sgad				 * a detailed message is helpful.  Also
571120361Sgad				 * skip "doing" any commands, since they
572120361Sgad				 * would all be turned off by no-action.
573120361Sgad				 */
574120361Sgad				printf("\n\t--> timematch at %s",
575120361Sgad				    ptimeget_ctime(ent->trim_at));
576130165Sgad				return (free_or_keep);
57743071Swollman			} else if (verbose && ent->hours <= 0) {
57843071Swollman				printf("--> time is up\n");
57943071Swollman			}
58043071Swollman		}
581130165Sgad		if (verbose && (ent->trsize > 0))
582130165Sgad			printf("size (Kb): %d [%d] ", ent->fsize, ent->trsize);
58359003Shm		if (verbose && (ent->hours > 0))
58459003Shm			printf(" age (hr): %d [%d] ", modtime, ent->hours);
585111772Sgad
586111772Sgad		/*
587111772Sgad		 * Figure out if this logfile needs to be rotated.
588111772Sgad		 */
589111772Sgad		temp_reason[0] = '\0';
590111772Sgad		if (rotatereq) {
591111772Sgad			ent->rotate = 1;
592111772Sgad			snprintf(temp_reason, REASON_MAX, " due to -R from %s",
593111772Sgad			    requestor);
594111772Sgad		} else if (force) {
595111772Sgad			ent->rotate = 1;
596111772Sgad			snprintf(temp_reason, REASON_MAX, " due to -F request");
597233257Sglebius		} else if (oversized) {
598111772Sgad			ent->rotate = 1;
599111772Sgad			snprintf(temp_reason, REASON_MAX, " due to size>%dK",
600130165Sgad			    ent->trsize);
601111772Sgad		} else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) {
602111772Sgad			ent->rotate = 1;
603111772Sgad		} else if ((ent->hours > 0) && ((modtime >= ent->hours) ||
604111772Sgad		    (modtime < 0))) {
605111772Sgad			ent->rotate = 1;
606111772Sgad		}
607111772Sgad
608111772Sgad		/*
609111772Sgad		 * If the file needs to be rotated, then rotate it.
610111772Sgad		 */
611143106Sbrooks		if (ent->rotate && !norotate) {
612111772Sgad			if (temp_reason[0] != '\0')
613111772Sgad				ent->r_reason = strdup(temp_reason);
61459003Shm			if (verbose)
61559003Shm				printf("--> trimming log....\n");
616218127Smm			if (noaction && !verbose)
617218127Smm				printf("%s <%d%s>: trimming\n", ent->log,
618218127Smm				    ent->numlogs,
619218127Smm				    compress_type[ent->compress].flag);
620130165Sgad			free_or_keep = do_rotate(ent);
62159003Shm		} else {
62259003Shm			if (verbose)
62359003Shm				printf("--> skipping\n");
62459003Shm		}
62559003Shm	}
626130165Sgad	return (free_or_keep);
627111772Sgad#undef REASON_MAX
62813244Sgraichen}
62913244Sgraichen
63059004Shmstatic void
631111781Sgadparse_args(int argc, char **argv)
63213244Sgraichen{
633111781Sgad	int ch;
63459003Shm	char *p;
63513244Sgraichen
636120361Sgad	timenow = ptime_init(NULL);
637120361Sgad	ptimeset_time(timenow, time(NULL));
638159998Sgad	strlcpy(daytime, ptimeget_ctime(timenow) + 4, DAYTIME_LEN);
639321263Sngie	ptimeget_ctime_rfc5424(timenow, daytime_rfc5424, DAYTIME_RFC5424_LEN);
64013244Sgraichen
64159003Shm	/* Let's get our hostname */
642111781Sgad	(void)gethostname(hostname, sizeof(hostname));
64313244Sgraichen
64413244Sgraichen	/* Truncate domain */
645111781Sgad	if ((p = strchr(hostname, '.')) != NULL)
64613244Sgraichen		*p = '\0';
647111768Sgad
648111768Sgad	/* Parse command line options. */
649216832Sbrian	while ((ch = getopt(argc, argv, "a:d:f:nrst:vCD:FNPR:S:")) != -1)
650111781Sgad		switch (ch) {
65159004Shm		case 'a':
65259004Shm			archtodir++;
65359004Shm			archdirname = optarg;
65459004Shm			break;
655136127Sbrooks		case 'd':
656136127Sbrooks			destdir = optarg;
657136127Sbrooks			break;
658111768Sgad		case 'f':
659111768Sgad			conf = optarg;
660111768Sgad			break;
661111768Sgad		case 'n':
662111768Sgad			noaction++;
663244996Smarkj			/* FALLTHROUGH */
66459003Shm		case 'r':
66559003Shm			needroot = 0;
66659003Shm			break;
667111768Sgad		case 's':
668111768Sgad			nosignal = 1;
669111768Sgad			break;
670210372Ssimon		case 't':
671210372Ssimon			if (optarg[0] == '\0' ||
672210372Ssimon			    strcmp(optarg, "DEFAULT") == 0)
673210372Ssimon				timefnamefmt = strdup(DEFAULT_TIMEFNAME_FMT);
674210372Ssimon			else
675210372Ssimon				timefnamefmt = strdup(optarg);
676210372Ssimon			break;
67759003Shm		case 'v':
67859003Shm			verbose++;
67959003Shm			break;
680114137Sgad		case 'C':
681114137Sgad			/* Useful for things like rc.diskless... */
682114137Sgad			createlogs++;
683114137Sgad			break;
684119904Sgad		case 'D':
685119904Sgad			/*
686119904Sgad			 * Set some debugging option.  The specific option
687119904Sgad			 * depends on the value of optarg.  These options
688119904Sgad			 * may come and go without notice or documentation.
689119904Sgad			 */
690119904Sgad			if (parse_doption(optarg))
691119904Sgad				break;
692119904Sgad			usage();
693119904Sgad			/* NOTREACHED */
69434584Spst		case 'F':
69534584Spst			force++;
69634584Spst			break;
697143106Sbrooks		case 'N':
698143106Sbrooks			norotate++;
699143106Sbrooks			break;
700202668Sdelphij		case 'P':
701202668Sdelphij			enforcepid++;
702202668Sdelphij			break;
703111772Sgad		case 'R':
704111772Sgad			rotatereq++;
705111772Sgad			requestor = strdup(optarg);
706111772Sgad			break;
707210407Sbrian		case 'S':
708210407Sbrian			path_syslogpid = optarg;
709210407Sbrian			break;
710111781Sgad		case 'm':	/* Used by OpenBSD for "monitor mode" */
71159003Shm		default:
71259003Shm			usage();
713111768Sgad			/* NOTREACHED */
71459003Shm		}
715111772Sgad
716143106Sbrooks	if (force && norotate) {
717143106Sbrooks		warnx("Only one of -F and -N may be specified.");
718143106Sbrooks		usage();
719143106Sbrooks		/* NOTREACHED */
720143106Sbrooks	}
721143106Sbrooks
722111772Sgad	if (rotatereq) {
723111772Sgad		if (optind == argc) {
724111772Sgad			warnx("At least one filename must be given when -R is specified.");
725111772Sgad			usage();
726111772Sgad			/* NOTREACHED */
727111772Sgad		}
728111772Sgad		/* Make sure "requestor" value is safe for a syslog message. */
729111772Sgad		for (p = requestor; *p != '\0'; p++) {
730111772Sgad			if (!isprintch(*p) && (*p != '\t'))
731111772Sgad				*p = '.';
732111772Sgad		}
733111772Sgad	}
734119904Sgad
735119904Sgad	if (dbg_timenow) {
736119904Sgad		/*
737119904Sgad		 * Note that the 'daytime' variable is not changed.
738119904Sgad		 * That is only used in messages that track when a
739119904Sgad		 * logfile is rotated, and if a file *is* rotated,
740119904Sgad		 * then it will still rotated at the "real now" time.
741119904Sgad		 */
742120361Sgad		ptime_free(timenow);
743119904Sgad		timenow = dbg_timenow;
744119904Sgad		fprintf(stderr, "Debug: Running as if TimeNow is %s",
745120361Sgad		    ptimeget_ctime(dbg_timenow));
746119904Sgad	}
747119904Sgad
74843071Swollman}
74913244Sgraichen
750120361Sgad/*
751120361Sgad * These debugging options are mainly meant for developer use, such
752120361Sgad * as writing regression-tests.  They would not be needed by users
753120361Sgad * during normal operation of newsyslog...
754120361Sgad */
755119904Sgadstatic int
756119904Sgadparse_doption(const char *doption)
757119904Sgad{
758119904Sgad	const char TN[] = "TN=";
759120361Sgad	int res;
760119904Sgad
761119904Sgad	if (strncmp(doption, TN, sizeof(TN) - 1) == 0) {
762119904Sgad		/*
763120361Sgad		 * The "TimeNow" debugging option.  This might be off
764120361Sgad		 * by an hour when crossing a timezone change.
765119904Sgad		 */
766120361Sgad		dbg_timenow = ptime_init(NULL);
767120361Sgad		res = ptime_relparse(dbg_timenow, PTM_PARSE_ISO8601,
768120361Sgad		    time(NULL), doption + sizeof(TN) - 1);
769120361Sgad		if (res == -2) {
770120361Sgad			warnx("Non-existent time specified on -D %s", doption);
771120361Sgad			return (0);			/* failure */
772120361Sgad		} else if (res < 0) {
773119904Sgad			warnx("Malformed time given on -D %s", doption);
774119904Sgad			return (0);			/* failure */
775119904Sgad		}
776119904Sgad		return (1);			/* successfully parsed */
777119904Sgad
778119904Sgad	}
779119904Sgad
780120361Sgad	if (strcmp(doption, "ats") == 0) {
781120361Sgad		dbg_at_times++;
782120361Sgad		return (1);			/* successfully parsed */
783120361Sgad	}
784120361Sgad
785159968Sgad	/* XXX - This check could probably be dropped. */
786159968Sgad	if ((strcmp(doption, "neworder") == 0) || (strcmp(doption, "oldorder")
787159968Sgad	    == 0)) {
788159968Sgad		warnx("NOTE: newsyslog always uses 'neworder'.");
789130167Sgad		return (1);			/* successfully parsed */
790130167Sgad	}
791130167Sgad
792130165Sgad	warnx("Unknown -D (debug) option: '%s'", doption);
793119904Sgad	return (0);				/* failure */
794119904Sgad}
795119904Sgad
79659004Shmstatic void
79759004Shmusage(void)
79813244Sgraichen{
79980646Sobrien
80080646Sobrien	fprintf(stderr,
801219434Sru	    "usage: newsyslog [-CFNPnrsv] [-a directory] [-d directory] [-f config_file]\n"
802219434Sru	    "                 [-S pidfile] [-t timefmt] [[-R tagname] file ...]\n");
80359003Shm	exit(1);
80413244Sgraichen}
80513244Sgraichen
80659004Shm/*
807111773Sgad * Parse a configuration file and return a linked list of all the logs
808111773Sgad * which should be processed.
80913244Sgraichen */
810208648Sgordonstatic struct cflist *
811111773Sgadget_worklist(char **files)
81213244Sgraichen{
81359003Shm	FILE *f;
814111773Sgad	char **given;
815208649Sgordon	struct cflist *cmdlist, *filelist, *globlist;
816208648Sgordon	struct conf_entry *defconf, *dupent, *ent;
817208649Sgordon	struct ilist inclist;
818208649Sgordon	struct include_entry *inc;
819112020Sgad	int gmatch, fnres;
820111773Sgad
821208648Sgordon	defconf = NULL;
822208649Sgordon	STAILQ_INIT(&inclist);
823111773Sgad
824208648Sgordon	filelist = malloc(sizeof(struct cflist));
825208648Sgordon	if (filelist == NULL)
826208648Sgordon		err(1, "malloc of filelist");
827208648Sgordon	STAILQ_INIT(filelist);
828208648Sgordon	globlist = malloc(sizeof(struct cflist));
829208648Sgordon	if (globlist == NULL)
830208648Sgordon		err(1, "malloc of globlist");
831208648Sgordon	STAILQ_INIT(globlist);
832208648Sgordon
833208649Sgordon	inc = malloc(sizeof(struct include_entry));
834208649Sgordon	if (inc == NULL)
835208649Sgordon		err(1, "malloc of inc");
836208649Sgordon	inc->file = conf;
837208649Sgordon	if (inc->file == NULL)
838208649Sgordon		inc->file = _PATH_CONF;
839208649Sgordon	STAILQ_INSERT_TAIL(&inclist, inc, inc_nextp);
840111773Sgad
841208649Sgordon	STAILQ_FOREACH(inc, &inclist, inc_nextp) {
842208649Sgordon		if (strcmp(inc->file, "-") != 0)
843208649Sgordon			f = fopen(inc->file, "r");
844208649Sgordon		else {
845208649Sgordon			f = stdin;
846208649Sgordon			inc->file = "<stdin>";
847208649Sgordon		}
848208649Sgordon		if (!f)
849208649Sgordon			err(1, "%s", inc->file);
850208649Sgordon
851208649Sgordon		if (verbose)
852208649Sgordon			printf("Processing %s\n", inc->file);
853344882Sdab		parse_file(f, filelist, globlist, &defconf, &inclist);
854208649Sgordon		(void) fclose(f);
855111773Sgad	}
856111773Sgad
857111773Sgad	/*
858111773Sgad	 * All config-file information has been read in and turned into
859208648Sgordon	 * a filelist and a globlist.  If there were no specific files
860112020Sgad	 * given on the run command, then the only thing left to do is to
861112020Sgad	 * call a routine which finds all files matched by the globlist
862208648Sgordon	 * and adds them to the filelist.  Then return the worklist.
863111773Sgad	 */
864111773Sgad	if (*files == NULL) {
865208648Sgordon		expand_globs(filelist, globlist);
866208648Sgordon		free_clist(globlist);
867111773Sgad		if (defconf != NULL)
868111773Sgad			free_entry(defconf);
869208648Sgordon		return (filelist);
870111773Sgad	}
871111773Sgad
872111773Sgad	/*
873111773Sgad	 * If newsyslog was given a specific list of files to process,
874111773Sgad	 * it may be that some of those files were not listed in any
875111773Sgad	 * config file.  Those unlisted files should get the default
876111773Sgad	 * rotation action.  First, create the default-rotation action
877111773Sgad	 * if none was found in a system config file.
878111773Sgad	 */
879111773Sgad	if (defconf == NULL) {
880111773Sgad		defconf = init_entry(DEFAULT_MARKER, NULL);
881111773Sgad		defconf->numlogs = 3;
882130165Sgad		defconf->trsize = 50;
883111773Sgad		defconf->permissions = S_IRUSR|S_IWUSR;
884111773Sgad	}
885111773Sgad
886111773Sgad	/*
887111773Sgad	 * If newsyslog was run with a list of specific filenames,
888111773Sgad	 * then create a new worklist which has only those files in
889111773Sgad	 * it, picking up the rotation-rules for those files from
890208648Sgordon	 * the original filelist.
891111773Sgad	 *
892111773Sgad	 * XXX - Note that this will copy multiple rules for a single
893111773Sgad	 *	logfile, if multiple entries are an exact match for
894111773Sgad	 *	that file.  That matches the historic behavior, but do
895111773Sgad	 *	we want to continue to allow it?  If so, it should
896111773Sgad	 *	probably be handled more intelligently.
897111773Sgad	 */
898208648Sgordon	cmdlist = malloc(sizeof(struct cflist));
899208648Sgordon	if (cmdlist == NULL)
900208648Sgordon		err(1, "malloc of cmdlist");
901208648Sgordon	STAILQ_INIT(cmdlist);
902208648Sgordon
903111773Sgad	for (given = files; *given; ++given) {
904111773Sgad		/*
905111773Sgad		 * First try to find exact-matches for this given file.
906111773Sgad		 */
907112020Sgad		gmatch = 0;
908208648Sgordon		STAILQ_FOREACH(ent, filelist, cf_nextp) {
909111773Sgad			if (strcmp(ent->log, *given) == 0) {
910111773Sgad				gmatch++;
911111773Sgad				dupent = init_entry(*given, ent);
912208648Sgordon				STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
913111773Sgad			}
914111773Sgad		}
915111773Sgad		if (gmatch) {
916111773Sgad			if (verbose > 2)
917111773Sgad				printf("\t+ Matched entry %s\n", *given);
918111773Sgad			continue;
919111773Sgad		}
920111773Sgad
921111773Sgad		/*
922111773Sgad		 * There was no exact-match for this given file, so look
923111773Sgad		 * for a "glob" entry which does match.
924111773Sgad		 */
925112020Sgad		gmatch = 0;
926344882Sdab		if (verbose > 2)
927112020Sgad			printf("\t+ Checking globs for %s\n", *given);
928208648Sgordon		STAILQ_FOREACH(ent, globlist, cf_nextp) {
929112020Sgad			fnres = fnmatch(ent->log, *given, FNM_PATHNAME);
930112020Sgad			if (verbose > 2)
931112020Sgad				printf("\t+    = %d for pattern %s\n", fnres,
932112020Sgad				    ent->log);
933112020Sgad			if (fnres == 0) {
934111773Sgad				gmatch++;
935111773Sgad				dupent = init_entry(*given, ent);
936112020Sgad				/* This new entry is not a glob! */
937111773Sgad				dupent->flags &= ~CE_GLOB;
938208648Sgordon				STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
939111773Sgad				/* Only allow a match to one glob-entry */
940111773Sgad				break;
941111773Sgad			}
942111773Sgad		}
943111773Sgad		if (gmatch) {
944111773Sgad			if (verbose > 2)
945111773Sgad				printf("\t+ Matched %s via %s\n", *given,
946111773Sgad				    ent->log);
947111773Sgad			continue;
948111773Sgad		}
949111773Sgad
950111773Sgad		/*
951111773Sgad		 * This given file was not found in any config file, so
952111773Sgad		 * add a worklist item based on the default entry.
953111773Sgad		 */
954111773Sgad		if (verbose > 2)
955111773Sgad			printf("\t+ No entry matched %s  (will use %s)\n",
956111773Sgad			    *given, DEFAULT_MARKER);
957111773Sgad		dupent = init_entry(*given, defconf);
958111773Sgad		/* Mark that it was *not* found in a config file */
959111773Sgad		dupent->def_cfg = 1;
960208648Sgordon		STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
961111773Sgad	}
962111773Sgad
963111773Sgad	/*
964112020Sgad	 * Free all the entries in the original work list, the list of
965112020Sgad	 * glob entries, and the default entry.
966111773Sgad	 */
967208648Sgordon	free_clist(filelist);
968208648Sgordon	free_clist(globlist);
969112020Sgad	free_entry(defconf);
970111773Sgad
971112020Sgad	/* And finally, return a worklist which matches the given files. */
972208648Sgordon	return (cmdlist);
973111773Sgad}
974111773Sgad
975111773Sgad/*
976112020Sgad * Expand the list of entries with filename patterns, and add all files
977112020Sgad * which match those glob-entries onto the worklist.
978112020Sgad */
979112020Sgadstatic void
980208648Sgordonexpand_globs(struct cflist *work_p, struct cflist *glob_p)
981112020Sgad{
982161412Sdelphij	int gmatch, gres;
983161412Sdelphij	size_t i;
984112020Sgad	char *mfname;
985208648Sgordon	struct conf_entry *dupent, *ent, *globent;
986112020Sgad	glob_t pglob;
987112020Sgad	struct stat st_fm;
988112020Sgad
989112020Sgad	/*
990112020Sgad	 * The worklist contains all fully-specified (non-GLOB) names.
991112020Sgad	 *
992112020Sgad	 * Now expand the list of filename-pattern (GLOB) entries into
993112020Sgad	 * a second list, which (by definition) will only match files
994112020Sgad	 * that already exist.  Do not add a glob-related entry for any
995112020Sgad	 * file which already exists in the fully-specified list.
996112020Sgad	 */
997208648Sgordon	STAILQ_FOREACH(globent, glob_p, cf_nextp) {
998112020Sgad		gres = glob(globent->log, GLOB_NOCHECK, NULL, &pglob);
999112020Sgad		if (gres != 0) {
1000112020Sgad			warn("cannot expand pattern (%d): %s", gres,
1001112020Sgad			    globent->log);
1002112020Sgad			continue;
1003112020Sgad		}
1004112020Sgad
1005112020Sgad		if (verbose > 2)
1006112020Sgad			printf("\t+ Expanding pattern %s\n", globent->log);
1007112020Sgad		for (i = 0; i < pglob.gl_matchc; i++) {
1008112020Sgad			mfname = pglob.gl_pathv[i];
1009112020Sgad
1010112020Sgad			/* See if this file already has a specific entry. */
1011112020Sgad			gmatch = 0;
1012208648Sgordon			STAILQ_FOREACH(ent, work_p, cf_nextp) {
1013112020Sgad				if (strcmp(mfname, ent->log) == 0) {
1014112020Sgad					gmatch++;
1015112020Sgad					break;
1016112020Sgad				}
1017112020Sgad			}
1018112020Sgad			if (gmatch)
1019112020Sgad				continue;
1020112020Sgad
1021112020Sgad			/* Make sure the named matched is a file. */
1022112020Sgad			gres = lstat(mfname, &st_fm);
1023112020Sgad			if (gres != 0) {
1024112020Sgad				/* Error on a file that glob() matched?!? */
1025112020Sgad				warn("Skipping %s - lstat() error", mfname);
1026112020Sgad				continue;
1027112020Sgad			}
1028112020Sgad			if (!S_ISREG(st_fm.st_mode)) {
1029112020Sgad				/* We only rotate files! */
1030112020Sgad				if (verbose > 2)
1031112020Sgad					printf("\t+  . skipping %s (!file)\n",
1032112020Sgad					    mfname);
1033112020Sgad				continue;
1034112020Sgad			}
1035112020Sgad
1036112020Sgad			if (verbose > 2)
1037112020Sgad				printf("\t+  . add file %s\n", mfname);
1038112020Sgad			dupent = init_entry(mfname, globent);
1039112020Sgad			/* This new entry is not a glob! */
1040112020Sgad			dupent->flags &= ~CE_GLOB;
1041208648Sgordon
1042208648Sgordon			/* Add to the worklist. */
1043208648Sgordon			STAILQ_INSERT_TAIL(work_p, dupent, cf_nextp);
1044112020Sgad		}
1045112020Sgad		globfree(&pglob);
1046112020Sgad		if (verbose > 2)
1047112020Sgad			printf("\t+ Done with pattern %s\n", globent->log);
1048112020Sgad	}
1049112020Sgad}
1050112020Sgad
1051112020Sgad/*
1052111773Sgad * Parse a configuration file and update a linked list of all the logs to
1053111773Sgad * process.
1054111773Sgad */
1055111773Sgadstatic void
1056208648Sgordonparse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
1057344882Sdab    struct conf_entry **defconf_p, struct ilist *inclist)
1058111773Sgad{
105959003Shm	char line[BUFSIZ], *parse, *q;
1060107737Ssobomax	char *cp, *errline, *group;
1061208648Sgordon	struct conf_entry *working;
1062111781Sgad	struct passwd *pwd;
106359003Shm	struct group *grp;
1064208649Sgordon	glob_t pglob;
1065120361Sgad	int eol, ptm_opts, res, special;
1066208649Sgordon	size_t i;
106713244Sgraichen
1068130165Sgad	errline = NULL;
1069111773Sgad	while (fgets(line, BUFSIZ, cf)) {
1070107737Ssobomax		if ((line[0] == '\n') || (line[0] == '#') ||
1071107737Ssobomax		    (strlen(line) == 0))
107259003Shm			continue;
1073130165Sgad		if (errline != NULL)
1074130165Sgad			free(errline);
107559003Shm		errline = strdup(line);
1076107737Ssobomax		for (cp = line + 1; *cp != '\0'; cp++) {
1077107737Ssobomax			if (*cp != '#')
1078107737Ssobomax				continue;
1079107737Ssobomax			if (*(cp - 1) == '\\') {
1080107737Ssobomax				strcpy(cp - 1, cp);
1081107737Ssobomax				cp--;
1082107737Ssobomax				continue;
1083107737Ssobomax			}
1084107737Ssobomax			*cp = '\0';
1085107737Ssobomax			break;
1086107737Ssobomax		}
108760373Sdes
108860373Sdes		q = parse = missing_field(sob(line), errline);
108960373Sdes		parse = son(line);
109060373Sdes		if (!*parse)
109180646Sobrien			errx(1, "malformed line (missing fields):\n%s",
109280646Sobrien			    errline);
109360373Sdes		*parse = '\0';
109460373Sdes
1095130165Sgad		/*
1096130165Sgad		 * Allow people to set debug options via the config file.
1097208648Sgordon		 * (NOTE: debug options are undocumented, and may disappear
1098130165Sgad		 * at any time, etc).
1099130165Sgad		 */
1100130165Sgad		if (strcasecmp(DEBUG_MARKER, q) == 0) {
1101252378Skientzle			q = parse = missing_field(sob(parse + 1), errline);
1102130165Sgad			parse = son(parse);
1103130165Sgad			if (!*parse)
1104130165Sgad				warnx("debug line specifies no option:\n%s",
1105130165Sgad				    errline);
1106130165Sgad			else {
1107130165Sgad				*parse = '\0';
1108130165Sgad				parse_doption(q);
1109130165Sgad			}
1110130165Sgad			continue;
1111208649Sgordon		} else if (strcasecmp(INCLUDE_MARKER, q) == 0) {
1112208649Sgordon			if (verbose)
1113208649Sgordon				printf("Found: %s", errline);
1114252378Skientzle			q = parse = missing_field(sob(parse + 1), errline);
1115208649Sgordon			parse = son(parse);
1116208649Sgordon			if (!*parse) {
1117208649Sgordon				warnx("include line missing argument:\n%s",
1118208649Sgordon				    errline);
1119208649Sgordon				continue;
1120208649Sgordon			}
1121208649Sgordon
1122208649Sgordon			*parse = '\0';
1123208649Sgordon
1124208649Sgordon			if (isglobstr(q)) {
1125208649Sgordon				res = glob(q, GLOB_NOCHECK, NULL, &pglob);
1126208649Sgordon				if (res != 0) {
1127208649Sgordon					warn("cannot expand pattern (%d): %s",
1128208649Sgordon					    res, q);
1129208649Sgordon					continue;
1130208649Sgordon				}
1131208649Sgordon
1132208649Sgordon				if (verbose > 2)
1133208649Sgordon					printf("\t+ Expanding pattern %s\n", q);
1134208649Sgordon
1135208649Sgordon				for (i = 0; i < pglob.gl_matchc; i++)
1136208649Sgordon					add_to_queue(pglob.gl_pathv[i],
1137208649Sgordon					    inclist);
1138208649Sgordon				globfree(&pglob);
1139208649Sgordon			} else
1140208649Sgordon				add_to_queue(q, inclist);
1141208649Sgordon			continue;
1142130165Sgad		}
1143130165Sgad
1144112020Sgad		special = 0;
1145111388Sgad		working = init_entry(q, NULL);
1146111388Sgad		if (strcasecmp(DEFAULT_MARKER, q) == 0) {
1147112020Sgad			special = 1;
1148344882Sdab			if (*defconf_p != NULL) {
1149111388Sgad				warnx("Ignoring duplicate entry for %s!", q);
1150111388Sgad				free_entry(working);
1151111388Sgad				continue;
1152111388Sgad			}
1153344882Sdab			*defconf_p = working;
115459003Shm		}
115513244Sgraichen
1156252378Skientzle		q = parse = missing_field(sob(parse + 1), errline);
115759003Shm		parse = son(parse);
115825518Sbrian		if (!*parse)
115980646Sobrien			errx(1, "malformed line (missing fields):\n%s",
116080646Sobrien			    errline);
116159003Shm		*parse = '\0';
116259003Shm		if ((group = strchr(q, ':')) != NULL ||
116359003Shm		    (group = strrchr(q, '.')) != NULL) {
116459003Shm			*group++ = '\0';
116559003Shm			if (*q) {
1166119102Sgad				if (!(isnumberstr(q))) {
1167111781Sgad					if ((pwd = getpwnam(q)) == NULL)
116859003Shm						errx(1,
116980646Sobrien				     "error in config file; unknown user:\n%s",
117059003Shm						    errline);
1171111781Sgad					working->uid = pwd->pw_uid;
117259003Shm				} else
117359003Shm					working->uid = atoi(q);
117459003Shm			} else
1175111779Sgad				working->uid = (uid_t)-1;
117613244Sgraichen
117759003Shm			q = group;
117859003Shm			if (*q) {
1179119102Sgad				if (!(isnumberstr(q))) {
118059003Shm					if ((grp = getgrnam(q)) == NULL)
118159003Shm						errx(1,
118280646Sobrien				    "error in config file; unknown group:\n%s",
118359003Shm						    errline);
118459003Shm					working->gid = grp->gr_gid;
118559003Shm				} else
118659003Shm					working->gid = atoi(q);
118759003Shm			} else
1188111779Sgad				working->gid = (gid_t)-1;
118913244Sgraichen
1190252378Skientzle			q = parse = missing_field(sob(parse + 1), errline);
119159003Shm			parse = son(parse);
119259003Shm			if (!*parse)
119380646Sobrien				errx(1, "malformed line (missing fields):\n%s",
119480646Sobrien				    errline);
119559003Shm			*parse = '\0';
1196111779Sgad		} else {
1197111779Sgad			working->uid = (uid_t)-1;
1198111779Sgad			working->gid = (gid_t)-1;
1199111779Sgad		}
120059003Shm
120159003Shm		if (!sscanf(q, "%o", &working->permissions))
120259003Shm			errx(1, "error in config file; bad permissions:\n%s",
120359003Shm			    errline);
120459003Shm
1205252378Skientzle		q = parse = missing_field(sob(parse + 1), errline);
120659003Shm		parse = son(parse);
120725518Sbrian		if (!*parse)
120880646Sobrien			errx(1, "malformed line (missing fields):\n%s",
120980646Sobrien			    errline);
121059003Shm		*parse = '\0';
1211111400Sgad		if (!sscanf(q, "%d", &working->numlogs) || working->numlogs < 0)
1212111400Sgad			errx(1, "error in config file; bad value for count of logs to save:\n%s",
121359003Shm			    errline);
121413244Sgraichen
1215252378Skientzle		q = parse = missing_field(sob(parse + 1), errline);
121659003Shm		parse = son(parse);
121725518Sbrian		if (!*parse)
121880646Sobrien			errx(1, "malformed line (missing fields):\n%s",
121980646Sobrien			    errline);
122059003Shm		*parse = '\0';
1221114762Sgad		if (isdigitch(*q))
1222130165Sgad			working->trsize = atoi(q);
1223130165Sgad		else if (strcmp(q, "*") == 0)
1224130165Sgad			working->trsize = -1;
1225114762Sgad		else {
1226114762Sgad			warnx("Invalid value of '%s' for 'size' in line:\n%s",
1227114762Sgad			    q, errline);
1228130165Sgad			working->trsize = -1;
1229114762Sgad		}
123059003Shm
123159003Shm		working->flags = 0;
1232218127Smm		working->compress = COMPRESS_NONE;
1233252378Skientzle		q = parse = missing_field(sob(parse + 1), errline);
123459003Shm		parse = son(parse);
123525518Sbrian		eol = !*parse;
123659003Shm		*parse = '\0';
123743071Swollman		{
123859003Shm			char *ep;
123959003Shm			u_long ul;
124013244Sgraichen
124143071Swollman			ul = strtoul(q, &ep, 10);
124243071Swollman			if (ep == q)
124343071Swollman				working->hours = 0;
124443071Swollman			else if (*ep == '*')
124543071Swollman				working->hours = -1;
124643071Swollman			else if (ul > INT_MAX)
124743071Swollman				errx(1, "interval is too large:\n%s", errline);
124843071Swollman			else
124943071Swollman				working->hours = ul;
125043071Swollman
1251120361Sgad			if (*ep == '\0' || strcmp(ep, "*") == 0)
1252120361Sgad				goto no_trimat;
1253120361Sgad			if (*ep != '@' && *ep != '$')
125443071Swollman				errx(1, "malformed interval/at:\n%s", errline);
1255120361Sgad
1256120361Sgad			working->flags |= CE_TRIMAT;
1257120361Sgad			working->trim_at = ptime_init(NULL);
1258120361Sgad			ptm_opts = PTM_PARSE_ISO8601;
1259120361Sgad			if (*ep == '$')
1260120361Sgad				ptm_opts = PTM_PARSE_DWM;
1261120361Sgad			ptm_opts |= PTM_PARSE_MATCHDOM;
1262120361Sgad			res = ptime_relparse(working->trim_at, ptm_opts,
1263120361Sgad			    ptimeget_secs(timenow), ep + 1);
1264120361Sgad			if (res == -2)
1265120361Sgad				errx(1, "nonexistent time for 'at' value:\n%s",
1266120361Sgad				    errline);
1267120361Sgad			else if (res < 0)
1268120361Sgad				errx(1, "malformed 'at' value:\n%s", errline);
126943071Swollman		}
1270120361Sgadno_trimat:
127143071Swollman
127225518Sbrian		if (eol)
127359003Shm			q = NULL;
127425518Sbrian		else {
1275252378Skientzle			q = parse = sob(parse + 1);	/* Optional field */
127659003Shm			parse = son(parse);
127759003Shm			if (!*parse)
127859003Shm				eol = 1;
127959003Shm			*parse = '\0';
128025518Sbrian		}
128125443Sache
1282111768Sgad		for (; q && *q && !isspacech(*q); q++) {
1283111768Sgad			switch (tolowerch(*q)) {
1284111768Sgad			case 'b':
128559003Shm				working->flags |= CE_BINARY;
1286111768Sgad				break;
1287114137Sgad			case 'c':
1288111768Sgad				/*
1289114137Sgad				 * XXX - 	Ick! Ugly! Remove ASAP!
1290114137Sgad				 * We want `c' and `C' for "create".  But we
1291114137Sgad				 * will temporarily treat `c' as `g', because
1292114137Sgad				 * FreeBSD releases <= 4.8 have a typo of
1293114137Sgad				 * checking  ('G' || 'c')  for CE_GLOB.
1294111768Sgad				 */
1295114137Sgad				if (*q == 'c') {
1296114137Sgad					warnx("Assuming 'g' for 'c' in flags for line:\n%s",
1297114137Sgad					    errline);
1298114137Sgad					warnx("The 'c' flag will eventually mean 'CREATE'");
1299114137Sgad					working->flags |= CE_GLOB;
1300114137Sgad					break;
1301114137Sgad				}
1302114137Sgad				working->flags |= CE_CREATE;
1303114137Sgad				break;
1304130043Sgad			case 'd':
1305130043Sgad				working->flags |= CE_NODUMP;
1306130043Sgad				break;
1307111768Sgad			case 'g':
1308106905Ssobomax				working->flags |= CE_GLOB;
1309111768Sgad				break;
1310111768Sgad			case 'j':
1311218127Smm				working->compress = COMPRESS_BZIP2;
1312111768Sgad				break;
1313111768Sgad			case 'n':
1314111768Sgad				working->flags |= CE_NOSIGNAL;
1315111768Sgad				break;
1316221873Ssobomax			case 'r':
1317221873Ssobomax				working->flags |= CE_PID2CMD;
1318221873Ssobomax				break;
1319321263Sngie			case 't':
1320321263Sngie				working->flags |= CE_RFC5424;
1321321263Sngie				break;
1322112003Sgad			case 'u':
1323112003Sgad				working->flags |= CE_SIGNALGROUP;
1324112003Sgad				break;
1325111768Sgad			case 'w':
1326321263Sngie				/* Deprecated flag - keep for compatibility purposes */
1327111768Sgad				break;
1328218127Smm			case 'x':
1329218127Smm				working->compress = COMPRESS_XZ;
1330218127Smm				break;
1331111768Sgad			case 'z':
1332218127Smm				working->compress = COMPRESS_GZIP;
1333111768Sgad				break;
1334111768Sgad			case '-':
1335111768Sgad				break;
1336111781Sgad			case 'f':	/* Used by OpenBSD for "CE_FOLLOW" */
1337111781Sgad			case 'm':	/* Used by OpenBSD for "CE_MONITOR" */
1338111781Sgad			case 'p':	/* Used by NetBSD  for "CE_PLAIN0" */
1339111768Sgad			default:
134080646Sobrien				errx(1, "illegal flag in config file -- %c",
134180646Sobrien				    *q);
1342111768Sgad			}
134359003Shm		}
134459003Shm
134525518Sbrian		if (eol)
134659003Shm			q = NULL;
134725518Sbrian		else {
1348252378Skientzle			q = parse = sob(parse + 1);	/* Optional field */
134959003Shm			parse = son(parse);
135059003Shm			if (!*parse)
135159003Shm				eol = 1;
135259003Shm			*parse = '\0';
135325518Sbrian		}
135425443Sache
1355221873Ssobomax		working->pid_cmd_file = NULL;
135625443Sache		if (q && *q) {
135725443Sache			if (*q == '/')
1358221873Ssobomax				working->pid_cmd_file = strdup(q);
1359290225Sbapt			else if (isalnum(*q))
136036817Sache				goto got_sig;
1361290225Sbapt			else {
136280646Sobrien				errx(1,
1363290225Sbapt			"illegal pid file or signal in config file:\n%s",
136480646Sobrien				    errline);
1365290225Sbapt			}
136625443Sache		}
136736817Sache		if (eol)
136859003Shm			q = NULL;
136936817Sache		else {
1370252378Skientzle			q = parse = sob(parse + 1);	/* Optional field */
1371344882Sdab			parse = son(parse);
1372344882Sdab			*parse = '\0';
137336817Sache		}
137436817Sache
137536817Sache		working->sig = SIGHUP;
137636817Sache		if (q && *q) {
1377290225Sbaptgot_sig:
1378290225Sbapt			working->sig = parse_signal(q);
1379290225Sbapt			if (working->sig < 1 || working->sig >= sys_nsig) {
138080646Sobrien				errx(1,
1381290225Sbapt				    "illegal signal in config file:\n%s",
138280646Sobrien				    errline);
138336817Sache			}
138436817Sache		}
1385111768Sgad
1386111768Sgad		/*
1387111768Sgad		 * Finish figuring out what pid-file to use (if any) in
1388111768Sgad		 * later processing if this logfile needs to be rotated.
1389111768Sgad		 */
1390111768Sgad		if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) {
1391111768Sgad			/*
1392111768Sgad			 * This config-entry specified 'n' for nosignal,
1393221873Ssobomax			 * see if it also specified an explicit pid_cmd_file.
1394111768Sgad			 * This would be a pretty pointless combination.
1395111768Sgad			 */
1396221873Ssobomax			if (working->pid_cmd_file != NULL) {
1397111768Sgad				warnx("Ignoring '%s' because flag 'n' was specified in line:\n%s",
1398221873Ssobomax				    working->pid_cmd_file, errline);
1399221873Ssobomax				free(working->pid_cmd_file);
1400221873Ssobomax				working->pid_cmd_file = NULL;
1401111768Sgad			}
1402221873Ssobomax		} else if (working->pid_cmd_file == NULL) {
1403111768Sgad			/*
1404111768Sgad			 * This entry did not specify the 'n' flag, which
1405111768Sgad			 * means it should signal syslogd unless it had
1406112003Sgad			 * specified some other pid-file (and obviously the
1407112003Sgad			 * syslog pid-file will not be for a process-group).
1408112003Sgad			 * Also, we should only try to notify syslog if we
1409112003Sgad			 * are root.
1410111768Sgad			 */
1411112003Sgad			if (working->flags & CE_SIGNALGROUP) {
1412112003Sgad				warnx("Ignoring flag 'U' in line:\n%s",
1413112003Sgad				    errline);
1414112003Sgad				working->flags &= ~CE_SIGNALGROUP;
1415112003Sgad			}
1416111768Sgad			if (needroot)
1417221873Ssobomax				working->pid_cmd_file = strdup(path_syslogpid);
1418111768Sgad		}
1419111768Sgad
1420112020Sgad		/*
1421112020Sgad		 * Add this entry to the appropriate list of entries, unless
1422112020Sgad		 * it was some kind of special entry (eg: <default>).
1423112020Sgad		 */
1424112020Sgad		if (special) {
1425112020Sgad			;			/* Do not add to any list */
1426112020Sgad		} else if (working->flags & CE_GLOB) {
1427208648Sgordon			STAILQ_INSERT_TAIL(glob_p, working, cf_nextp);
1428112020Sgad		} else {
1429208648Sgordon			STAILQ_INSERT_TAIL(work_p, working, cf_nextp);
1430112020Sgad		}
1431130165Sgad	}
1432130165Sgad	if (errline != NULL)
143359003Shm		free(errline);
143413244Sgraichen}
143513244Sgraichen
143659003Shmstatic char *
143759004Shmmissing_field(char *p, char *errline)
143813244Sgraichen{
143980646Sobrien
144059003Shm	if (!p || !*p)
144159003Shm		errx(1, "missing field in config file:\n%s", errline);
144259003Shm	return (p);
144313244Sgraichen}
144413244Sgraichen
1445208649Sgordon/*
1446210372Ssimon * In our sort we return it in the reverse of what qsort normally
1447210372Ssimon * would do, as we want the newest files first.  If we have two
1448210372Ssimon * entries with the same time we don't really care about order.
1449210372Ssimon *
1450210372Ssimon * Support function for qsort() in delete_oldest_timelog().
1451210372Ssimon */
1452210372Ssimonstatic int
1453210372Ssimonoldlog_entry_compare(const void *a, const void *b)
1454210372Ssimon{
1455210372Ssimon	const struct oldlog_entry *ola = a, *olb = b;
1456210372Ssimon
1457210372Ssimon	if (ola->t > olb->t)
1458210372Ssimon		return (-1);
1459210372Ssimon	else if (ola->t < olb->t)
1460210372Ssimon		return (1);
1461210372Ssimon	else
1462210372Ssimon		return (0);
1463210372Ssimon}
1464210372Ssimon
1465210372Ssimon/*
1466248776Smarkj * Check whether the file corresponding to dp is an archive of the logfile
1467248776Smarkj * logfname, based on the timefnamefmt format string. Return true and fill out
1468248776Smarkj * tm if this is the case; otherwise return false.
1469248776Smarkj */
1470248776Smarkjstatic int
1471250545Smarkjvalidate_old_timelog(int fd, const struct dirent *dp, const char *logfname,
1472250545Smarkj    struct tm *tm)
1473248776Smarkj{
1474250545Smarkj	struct stat sb;
1475248776Smarkj	size_t logfname_len;
1476248776Smarkj	char *s;
1477248776Smarkj	int c;
1478248776Smarkj
1479248776Smarkj	logfname_len = strlen(logfname);
1480248776Smarkj
1481250545Smarkj	if (dp->d_type != DT_REG) {
1482250545Smarkj		/*
1483250545Smarkj		 * Some filesystems (e.g. NFS) don't fill out the d_type field
1484250545Smarkj		 * and leave it set to DT_UNKNOWN; in this case we must obtain
1485250545Smarkj		 * the file type ourselves.
1486250545Smarkj		 */
1487250545Smarkj		if (dp->d_type != DT_UNKNOWN ||
1488250545Smarkj		    fstatat(fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) != 0 ||
1489250545Smarkj		    !S_ISREG(sb.st_mode))
1490250545Smarkj			return (0);
1491250545Smarkj	}
1492248776Smarkj	/* Ignore everything but files with our logfile prefix. */
1493248776Smarkj	if (strncmp(dp->d_name, logfname, logfname_len) != 0)
1494248776Smarkj		return (0);
1495248776Smarkj	/* Ignore the actual non-rotated logfile. */
1496248776Smarkj	if (dp->d_namlen == logfname_len)
1497248776Smarkj		return (0);
1498248776Smarkj
1499248776Smarkj	/*
1500248776Smarkj	 * Make sure we created have found a logfile, so the
1501248776Smarkj	 * postfix is valid, IE format is: '.<time>(.[bgx]z)?'.
1502248776Smarkj	 */
1503248776Smarkj	if (dp->d_name[logfname_len] != '.') {
1504248776Smarkj		if (verbose)
1505248776Smarkj			printf("Ignoring %s which has unexpected "
1506248776Smarkj			    "extension '%s'\n", dp->d_name,
1507248776Smarkj			    &dp->d_name[logfname_len]);
1508248776Smarkj		return (0);
1509248776Smarkj	}
1510261820Smarkj	memset(tm, 0, sizeof(*tm));
1511248776Smarkj	if ((s = strptime(&dp->d_name[logfname_len + 1],
1512248776Smarkj	    timefnamefmt, tm)) == NULL) {
1513248776Smarkj		/*
1514248776Smarkj		 * We could special case "old" sequentially named logfiles here,
1515248776Smarkj		 * but we do not as that would require special handling to
1516248776Smarkj		 * decide which one was the oldest compared to "new" time based
1517248776Smarkj		 * logfiles.
1518248776Smarkj		 */
1519248776Smarkj		if (verbose)
1520248776Smarkj			printf("Ignoring %s which does not "
1521248776Smarkj			    "match time format\n", dp->d_name);
1522248776Smarkj		return (0);
1523248776Smarkj	}
1524248776Smarkj
1525248776Smarkj	for (c = 0; c < COMPRESS_TYPES; c++)
1526248776Smarkj		if (strcmp(s, compress_type[c].suffix) == 0)
1527248776Smarkj			/* We're done. */
1528248776Smarkj			return (1);
1529248776Smarkj
1530248776Smarkj	if (verbose)
1531248776Smarkj		printf("Ignoring %s which has unexpected extension '%s'\n",
1532248776Smarkj		    dp->d_name, s);
1533248776Smarkj
1534248776Smarkj	return (0);
1535248776Smarkj}
1536248776Smarkj
1537248776Smarkj/*
1538210372Ssimon * Delete the oldest logfiles, when using time based filenames.
1539210372Ssimon */
1540210372Ssimonstatic void
1541210372Ssimondelete_oldest_timelog(const struct conf_entry *ent, const char *archive_dir)
1542210372Ssimon{
1543210372Ssimon	char *logfname, *s, *dir, errbuf[80];
1544248776Smarkj	int dir_fd, i, logcnt, max_logcnt;
1545210372Ssimon	struct oldlog_entry *oldlogs;
1546210372Ssimon	struct dirent *dp;
1547210372Ssimon	const char *cdir;
1548210372Ssimon	struct tm tm;
1549210372Ssimon	DIR *dirp;
1550210372Ssimon
1551210372Ssimon	oldlogs = malloc(MAX_OLDLOGS * sizeof(struct oldlog_entry));
1552210372Ssimon	max_logcnt = MAX_OLDLOGS;
1553210372Ssimon	logcnt = 0;
1554210372Ssimon
1555210372Ssimon	if (archive_dir != NULL && archive_dir[0] != '\0')
1556210372Ssimon		cdir = archive_dir;
1557210372Ssimon	else
1558210372Ssimon		if ((cdir = dirname(ent->log)) == NULL)
1559210372Ssimon			err(1, "dirname()");
1560210372Ssimon	if ((dir = strdup(cdir)) == NULL)
1561210372Ssimon		err(1, "strdup()");
1562210372Ssimon
1563210372Ssimon	if ((s = basename(ent->log)) == NULL)
1564210372Ssimon		err(1, "basename()");
1565210372Ssimon	if ((logfname = strdup(s)) == NULL)
1566210372Ssimon		err(1, "strdup()");
1567210372Ssimon	if (strcmp(logfname, "/") == 0)
1568210372Ssimon		errx(1, "Invalid log filename - became '/'");
1569210372Ssimon
1570210372Ssimon	if (verbose > 2)
1571210372Ssimon		printf("Searching for old logs in %s\n", dir);
1572210372Ssimon
1573210372Ssimon	/* First we create a 'list' of all archived logfiles */
1574210372Ssimon	if ((dirp = opendir(dir)) == NULL)
1575210372Ssimon		err(1, "Cannot open log directory '%s'", dir);
1576235647Sgleb	dir_fd = dirfd(dirp);
1577210372Ssimon	while ((dp = readdir(dirp)) != NULL) {
1578250545Smarkj		if (validate_old_timelog(dir_fd, dp, logfname, &tm) == 0)
1579210372Ssimon			continue;
1580210372Ssimon
1581210372Ssimon		/*
1582210372Ssimon		 * We should now have old an old rotated logfile, so
1583210372Ssimon		 * add it to the 'list'.
1584210372Ssimon		 */
1585210372Ssimon		if ((oldlogs[logcnt].t = timegm(&tm)) == -1)
1586210372Ssimon			err(1, "Could not convert time string to time value");
1587210372Ssimon		if ((oldlogs[logcnt].fname = strdup(dp->d_name)) == NULL)
1588210372Ssimon			err(1, "strdup()");
1589210372Ssimon		logcnt++;
1590210372Ssimon
1591210372Ssimon		/*
1592210372Ssimon		 * It is very unlikely we ever run out of space in the
1593210372Ssimon		 * logfile array from the default size, but lets
1594210372Ssimon		 * handle it anyway...
1595210372Ssimon		 */
1596210372Ssimon		if (logcnt >= max_logcnt) {
1597210372Ssimon			max_logcnt *= 4;
1598210372Ssimon			/* Detect integer overflow */
1599210372Ssimon			if (max_logcnt < logcnt)
1600210372Ssimon				errx(1, "Too many old logfiles found");
1601210372Ssimon			oldlogs = realloc(oldlogs,
1602210372Ssimon			    max_logcnt * sizeof(struct oldlog_entry));
1603210372Ssimon			if (oldlogs == NULL)
1604210372Ssimon				err(1, "realloc()");
1605210372Ssimon		}
1606210372Ssimon	}
1607210372Ssimon
1608210372Ssimon	/* Second, if needed we delete oldest archived logfiles */
1609210372Ssimon	if (logcnt > 0 && logcnt >= ent->numlogs && ent->numlogs > 1) {
1610210372Ssimon		oldlogs = realloc(oldlogs, logcnt *
1611210372Ssimon		    sizeof(struct oldlog_entry));
1612210372Ssimon		if (oldlogs == NULL)
1613210372Ssimon			err(1, "realloc()");
1614210372Ssimon
1615210372Ssimon		/*
1616210372Ssimon		 * We now sort the logs in the order of newest to
1617210372Ssimon		 * oldest.  That way we can simply skip over the
1618210372Ssimon		 * number of records we want to keep.
1619210372Ssimon		 */
1620210372Ssimon		qsort(oldlogs, logcnt, sizeof(struct oldlog_entry),
1621210372Ssimon		    oldlog_entry_compare);
1622210372Ssimon		for (i = ent->numlogs - 1; i < logcnt; i++) {
1623210372Ssimon			if (noaction)
1624210372Ssimon				printf("\trm -f %s/%s\n", dir,
1625210372Ssimon				    oldlogs[i].fname);
1626235647Sgleb			else if (unlinkat(dir_fd, oldlogs[i].fname, 0) != 0) {
1627210372Ssimon				snprintf(errbuf, sizeof(errbuf),
1628244995Smarkj				    "Could not delete old logfile '%s'",
1629210372Ssimon				    oldlogs[i].fname);
1630210372Ssimon				perror(errbuf);
1631210372Ssimon			}
1632210372Ssimon		}
1633210372Ssimon	} else if (verbose > 1)
1634210372Ssimon		printf("No old logs to delete for logfile %s\n", ent->log);
1635210372Ssimon
1636210372Ssimon	/* Third, cleanup */
1637210372Ssimon	closedir(dirp);
1638210372Ssimon	for (i = 0; i < logcnt; i++) {
1639210372Ssimon		assert(oldlogs[i].fname != NULL);
1640210372Ssimon		free(oldlogs[i].fname);
1641210372Ssimon	}
1642210372Ssimon	free(oldlogs);
1643210372Ssimon	free(logfname);
1644210372Ssimon	free(dir);
1645210372Ssimon}
1646210372Ssimon
1647210372Ssimon/*
1648228990Suqs * Generate a log filename, when using classic filenames.
1649220926Ssimon */
1650220926Ssimonstatic void
1651229654Suqsgen_classiclog_fname(char *fname, size_t fname_sz, const char *archive_dir,
1652220926Ssimon    const char *namepart, int numlogs_c)
1653220926Ssimon{
1654220926Ssimon
1655220926Ssimon	if (archive_dir[0] != '\0')
1656220926Ssimon		(void) snprintf(fname, fname_sz, "%s/%s.%d", archive_dir,
1657220926Ssimon		    namepart, numlogs_c);
1658220926Ssimon	else
1659220926Ssimon		(void) snprintf(fname, fname_sz, "%s.%d", namepart, numlogs_c);
1660220926Ssimon}
1661220926Ssimon
1662220926Ssimon/*
1663229654Suqs * Delete a rotated logfile, when using classic filenames.
1664220926Ssimon */
1665220926Ssimonstatic void
1666229654Suqsdelete_classiclog(const char *archive_dir, const char *namepart, int numlog_c)
1667220926Ssimon{
1668220926Ssimon	char file1[MAXPATHLEN], zfile1[MAXPATHLEN];
1669220926Ssimon	int c;
1670220926Ssimon
1671229654Suqs	gen_classiclog_fname(file1, sizeof(file1), archive_dir, namepart,
1672220926Ssimon	    numlog_c);
1673220926Ssimon
1674220926Ssimon	for (c = 0; c < COMPRESS_TYPES; c++) {
1675220926Ssimon		(void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1676220926Ssimon		    compress_type[c].suffix);
1677220926Ssimon		if (noaction)
1678220926Ssimon			printf("\trm -f %s\n", zfile1);
1679220926Ssimon		else
1680220926Ssimon			(void) unlink(zfile1);
1681220926Ssimon	}
1682220926Ssimon}
1683220926Ssimon
1684220926Ssimon/*
1685208649Sgordon * Only add to the queue if the file hasn't already been added. This is
1686208649Sgordon * done to prevent circular include loops.
1687208649Sgordon */
1688208649Sgordonstatic void
1689208649Sgordonadd_to_queue(const char *fname, struct ilist *inclist)
1690208649Sgordon{
1691208649Sgordon	struct include_entry *inc;
1692208649Sgordon
1693208649Sgordon	STAILQ_FOREACH(inc, inclist, inc_nextp) {
1694208649Sgordon		if (strcmp(fname, inc->file) == 0) {
1695208649Sgordon			warnx("duplicate include detected: %s", fname);
1696208649Sgordon			return;
1697208649Sgordon		}
1698208649Sgordon	}
1699208649Sgordon
1700208649Sgordon	inc = malloc(sizeof(struct include_entry));
1701208649Sgordon	if (inc == NULL)
1702208649Sgordon		err(1, "malloc of inc");
1703208649Sgordon	inc->file = strdup(fname);
1704208649Sgordon
1705208649Sgordon	if (verbose > 2)
1706208649Sgordon		printf("\t+ Adding %s to the processing queue.\n", fname);
1707208649Sgordon
1708208649Sgordon	STAILQ_INSERT_TAIL(inclist, inc, inc_nextp);
1709208649Sgordon}
1710208649Sgordon
1711218127Smm/*
1712218127Smm * Search for logfile and return its compression suffix (if supported)
1713218127Smm * The suffix detection is first-match in the order of compress_types
1714218127Smm *
1715218127Smm * Note: if logfile without suffix exists (uncompressed, COMPRESS_NONE)
1716218127Smm * a zero-length string is returned
1717218127Smm */
1718218127Smmstatic const char *
1719218127Smmget_logfile_suffix(const char *logfile)
1720218127Smm{
1721218127Smm	struct stat st;
1722218127Smm	char zfile[MAXPATHLEN];
1723218944Ssobomax	int c;
1724218127Smm
1725218944Ssobomax	for (c = 0; c < COMPRESS_TYPES; c++) {
1726218127Smm		(void) strlcpy(zfile, logfile, MAXPATHLEN);
1727218127Smm		(void) strlcat(zfile, compress_type[c].suffix, MAXPATHLEN);
1728218127Smm		if (lstat(zfile, &st) == 0)
1729218127Smm			return (compress_type[c].suffix);
1730218127Smm	}
1731218127Smm	return (NULL);
1732218127Smm}
1733218127Smm
1734130165Sgadstatic fk_entry
1735130165Sgaddo_rotate(const struct conf_entry *ent)
173613244Sgraichen{
173771299Sjedgar	char dirpart[MAXPATHLEN], namepart[MAXPATHLEN];
173871299Sjedgar	char file1[MAXPATHLEN], file2[MAXPATHLEN];
173971299Sjedgar	char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN];
1740218127Smm	const char *logfile_suffix;
1741210372Ssimon	char datetimestr[30];
1742159968Sgad	int flags, numlogs_c;
1743130165Sgad	fk_entry free_or_keep;
1744159968Sgad	struct sigwork_entry *swork;
174559003Shm	struct stat st;
1746210372Ssimon	struct tm tm;
1747210372Ssimon	time_t now;
174813244Sgraichen
1749119927Sgad	flags = ent->flags;
1750130165Sgad	free_or_keep = FREE_ENT;
1751119927Sgad
175259004Shm	if (archtodir) {
175359004Shm		char *p;
175413244Sgraichen
175559004Shm		/* build complete name of archive directory into dirpart */
175659004Shm		if (*archdirname == '/') {	/* absolute */
175771299Sjedgar			strlcpy(dirpart, archdirname, sizeof(dirpart));
175859004Shm		} else {	/* relative */
175959004Shm			/* get directory part of logfile */
1760119927Sgad			strlcpy(dirpart, ent->log, sizeof(dirpart));
1761229403Sed			if ((p = strrchr(dirpart, '/')) == NULL)
176259004Shm				dirpart[0] = '\0';
176359004Shm			else
176459004Shm				*(p + 1) = '\0';
176571299Sjedgar			strlcat(dirpart, archdirname, sizeof(dirpart));
176659004Shm		}
176759004Shm
176859004Shm		/* check if archive directory exists, if not, create it */
176959004Shm		if (lstat(dirpart, &st))
1770114137Sgad			createdir(ent, dirpart);
177159004Shm
177259004Shm		/* get filename part of logfile */
1773229403Sed		if ((p = strrchr(ent->log, '/')) == NULL)
1774119927Sgad			strlcpy(namepart, ent->log, sizeof(namepart));
177559004Shm		else
177671299Sjedgar			strlcpy(namepart, p + 1, sizeof(namepart));
177759004Shm	} else {
1778210372Ssimon		/*
1779220926Ssimon		 * Tell utility functions we are not using an archive
1780220926Ssimon		 * dir.
1781210372Ssimon		 */
1782210372Ssimon		dirpart[0] = '\0';
1783220926Ssimon		strlcpy(namepart, ent->log, sizeof(namepart));
1784210372Ssimon	}
1785210372Ssimon
1786210372Ssimon	/* Delete old logs */
1787210372Ssimon	if (timefnamefmt != NULL)
1788210372Ssimon		delete_oldest_timelog(ent, dirpart);
1789210372Ssimon	else {
1790220926Ssimon		/*
1791220926Ssimon		 * Handle cleaning up after legacy newsyslog where we
1792220926Ssimon		 * kept ent->numlogs + 1 files.  This code can go away
1793220926Ssimon		 * at some point in the future.
1794220926Ssimon		 */
1795229654Suqs		delete_classiclog(dirpart, namepart, ent->numlogs);
1796220926Ssimon
1797220926Ssimon		if (ent->numlogs > 0)
1798229654Suqs			delete_classiclog(dirpart, namepart, ent->numlogs - 1);
1799220926Ssimon
180059003Shm	}
180113244Sgraichen
1802210372Ssimon	if (timefnamefmt != NULL) {
1803210372Ssimon		/* If time functions fails we can't really do any sensible */
1804210372Ssimon		if (time(&now) == (time_t)-1 ||
1805210372Ssimon		    localtime_r(&now, &tm) == NULL)
1806210372Ssimon			bzero(&tm, sizeof(tm));
1807210372Ssimon
1808210372Ssimon		strftime(datetimestr, sizeof(datetimestr), timefnamefmt, &tm);
1809210372Ssimon		if (archtodir)
1810210372Ssimon			(void) snprintf(file1, sizeof(file1), "%s/%s.%s",
1811210372Ssimon			    dirpart, namepart, datetimestr);
1812210372Ssimon		else
1813210372Ssimon			(void) snprintf(file1, sizeof(file1), "%s.%s",
1814210372Ssimon			    ent->log, datetimestr);
1815210372Ssimon
1816210372Ssimon		/* Don't run the code to move down logs */
1817220926Ssimon		numlogs_c = -1;
1818220926Ssimon	} else {
1819229654Suqs		gen_classiclog_fname(file1, sizeof(file1), dirpart, namepart,
1820220926Ssimon		    ent->numlogs - 1);
1821220926Ssimon		numlogs_c = ent->numlogs - 2;		/* copy for countdown */
1822220926Ssimon	}
1823210372Ssimon
182459003Shm	/* Move down log files */
1825220926Ssimon	for (; numlogs_c >= 0; numlogs_c--) {
182671299Sjedgar		(void) strlcpy(file2, file1, sizeof(file2));
182759004Shm
1828229654Suqs		gen_classiclog_fname(file1, sizeof(file1), dirpart, namepart,
1829220926Ssimon		    numlogs_c);
183059004Shm
1831218127Smm		logfile_suffix = get_logfile_suffix(file1);
1832218127Smm		if (logfile_suffix == NULL)
1833218127Smm			continue;
1834218127Smm		(void) strlcpy(zfile1, file1, MAXPATHLEN);
1835218127Smm		(void) strlcpy(zfile2, file2, MAXPATHLEN);
1836218127Smm		(void) strlcat(zfile1, logfile_suffix, MAXPATHLEN);
1837218127Smm		(void) strlcat(zfile2, logfile_suffix, MAXPATHLEN);
1838218127Smm
1839130165Sgad		if (noaction)
1840111967Sgad			printf("\tmv %s %s\n", zfile1, zfile2);
1841130165Sgad		else {
1842130165Sgad			/* XXX - Ought to be checking for failure! */
1843130165Sgad			(void)rename(zfile1, zfile2);
184459003Shm		}
1845130165Sgad		change_attrs(zfile2, ent);
184659003Shm	}
184713244Sgraichen
1848130038Sgad	if (ent->numlogs > 0) {
1849129974Sgad		if (noaction) {
1850130038Sgad			/*
1851130038Sgad			 * Note that savelog() may succeed with using link()
1852130038Sgad			 * for the archtodir case, but there is no good way
1853130038Sgad			 * of knowing if it will when doing "noaction", so
1854130038Sgad			 * here we claim that it will have to do a copy...
1855130038Sgad			 */
1856130038Sgad			if (archtodir)
1857130038Sgad				printf("\tcp %s %s\n", ent->log, file1);
1858130038Sgad			else
1859130038Sgad				printf("\tln %s %s\n", ent->log, file1);
1860244997Smarkj			printf("\ttouch %s\t\t"
1861244997Smarkj			    "# Update mtime for 'when'-interval processing\n",
1862244997Smarkj			    file1);
1863130165Sgad		} else {
1864130038Sgad			if (!(flags & CE_BINARY)) {
1865130038Sgad				/* Report the trimming to the old log */
1866130038Sgad				log_trim(ent->log, ent);
1867130038Sgad			}
1868130038Sgad			savelog(ent->log, file1);
1869244997Smarkj			/*
1870244997Smarkj			 * Interval-based rotations are done using the mtime of
1871244997Smarkj			 * the most recently archived log, so make sure it gets
1872244997Smarkj			 * updated during a rotation.
1873244997Smarkj			 */
1874244997Smarkj			utimes(file1, NULL);
187559004Shm		}
1876130165Sgad		change_attrs(file1, ent);
187718075Sjkh	}
187818075Sjkh
1879130038Sgad	/* Create the new log file and move it into place */
1880130038Sgad	if (noaction)
1881111781Sgad		printf("Start new log...\n");
1882130038Sgad	createlog(ent);
188325443Sache
1884111966Sgad	/*
1885130167Sgad	 * Save all signalling and file-compression to be done after log
1886130167Sgad	 * files from all entries have been rotated.  This way any one
1887130167Sgad	 * process will not be sent the same signal multiple times when
1888130167Sgad	 * multiple log files had to be rotated.
1889130167Sgad	 */
1890159968Sgad	swork = NULL;
1891221873Ssobomax	if (ent->pid_cmd_file != NULL)
1892159968Sgad		swork = save_sigwork(ent);
1893218127Smm	if (ent->numlogs > 0 && ent->compress > COMPRESS_NONE) {
1894159968Sgad		/*
1895159968Sgad		 * The zipwork_entry will include a pointer to this
1896159968Sgad		 * conf_entry, so the conf_entry should not be freed.
1897159968Sgad		 */
1898159968Sgad		free_or_keep = KEEP_ENT;
1899159968Sgad		save_zipwork(ent, swork, ent->fsize, file1);
1900130167Sgad	}
1901130167Sgad
1902130165Sgad	return (free_or_keep);
190313244Sgraichen}
190413244Sgraichen
1905130167Sgadstatic void
1906130167Sgaddo_sigwork(struct sigwork_entry *swork)
1907130167Sgad{
1908130204Sgad	struct sigwork_entry *nextsig;
1909130204Sgad	int kres, secs;
1910221873Ssobomax	char *tmp;
1911130167Sgad
1912245963Smarkj	if (swork->sw_runcmd == 0 && (!(swork->sw_pidok) || swork->sw_pid == 0))
1913130167Sgad		return;			/* no work to do... */
1914130167Sgad
1915130167Sgad	/*
1916130167Sgad	 * If nosignal (-s) was specified, then do not signal any process.
1917130167Sgad	 * Note that a nosignal request triggers a warning message if the
1918130167Sgad	 * rotated logfile needs to be compressed, *unless* -R was also
1919130167Sgad	 * specified.  We assume that an `-sR' request came from a process
1920130167Sgad	 * which writes to the logfile, and as such, we assume that process
1921130167Sgad	 * has already made sure the logfile is not presently in use.  This
1922130167Sgad	 * just sets swork->sw_pidok to a special value, and do_zipwork
1923130167Sgad	 * will print any necessary warning(s).
1924130167Sgad	 */
1925130167Sgad	if (nosignal) {
1926130167Sgad		if (!rotatereq)
1927130167Sgad			swork->sw_pidok = -1;
1928130167Sgad		return;
1929130167Sgad	}
1930130167Sgad
1931130204Sgad	/*
1932130204Sgad	 * Compute the pause between consecutive signals.  Use a longer
1933130204Sgad	 * sleep time if we will be sending two signals to the same
1934293290Sbdrewery	 * daemon or process-group.
1935130204Sgad	 */
1936130204Sgad	secs = 0;
1937130204Sgad	nextsig = SLIST_NEXT(swork, sw_nextp);
1938130204Sgad	if (nextsig != NULL) {
1939130204Sgad		if (swork->sw_pid == nextsig->sw_pid)
1940130204Sgad			secs = 10;
1941130204Sgad		else
1942130204Sgad			secs = 1;
1943130204Sgad	}
1944130204Sgad
1945130167Sgad	if (noaction) {
1946245963Smarkj		if (swork->sw_runcmd)
1947245962Smarkj			printf("\tsh -c '%s %d'\n", swork->sw_fname,
1948245962Smarkj			    swork->sw_signum);
1949245962Smarkj		else {
1950245962Smarkj			printf("\tkill -%d %d \t\t# %s\n", swork->sw_signum,
1951245962Smarkj			    (int)swork->sw_pid, swork->sw_fname);
1952245962Smarkj			if (secs > 0)
1953245962Smarkj				printf("\tsleep %d\n", secs);
1954245962Smarkj		}
1955130167Sgad		return;
1956130167Sgad	}
1957130167Sgad
1958245963Smarkj	if (swork->sw_runcmd) {
1959221873Ssobomax		asprintf(&tmp, "%s %d", swork->sw_fname, swork->sw_signum);
1960221873Ssobomax		if (tmp == NULL) {
1961221873Ssobomax			warn("can't allocate memory to run %s",
1962221873Ssobomax			    swork->sw_fname);
1963221873Ssobomax			return;
1964221873Ssobomax		}
1965221873Ssobomax		if (verbose)
1966221873Ssobomax			printf("Run command: %s\n", tmp);
1967221873Ssobomax		kres = system(tmp);
1968221873Ssobomax		if (kres) {
1969221873Ssobomax			warnx("%s: returned non-zero exit code: %d",
1970221873Ssobomax			    tmp, kres);
1971221873Ssobomax		}
1972221873Ssobomax		free(tmp);
1973221873Ssobomax		return;
1974221873Ssobomax	}
1975221873Ssobomax
1976130167Sgad	kres = kill(swork->sw_pid, swork->sw_signum);
1977130167Sgad	if (kres != 0) {
1978130167Sgad		/*
1979130167Sgad		 * Assume that "no such process" (ESRCH) is something
1980130167Sgad		 * to warn about, but is not an error.  Presumably the
1981130167Sgad		 * process which writes to the rotated log file(s) is
1982130167Sgad		 * gone, in which case we should have no problem with
1983130167Sgad		 * compressing the rotated log file(s).
1984130167Sgad		 */
1985130167Sgad		if (errno != ESRCH)
1986130167Sgad			swork->sw_pidok = 0;
1987273554Smarkj		warn("can't notify %s, pid %d = %s", swork->sw_pidtype,
1988273554Smarkj		    (int)swork->sw_pid, swork->sw_fname);
1989130167Sgad	} else {
1990130204Sgad		if (verbose)
1991130204Sgad			printf("Notified %s pid %d = %s\n", swork->sw_pidtype,
1992130204Sgad			    (int)swork->sw_pid, swork->sw_fname);
1993130204Sgad		if (secs > 0) {
1994130204Sgad			if (verbose)
1995130204Sgad				printf("Pause %d second(s) between signals\n",
1996130204Sgad				    secs);
1997130204Sgad			sleep(secs);
1998130167Sgad		}
1999130167Sgad	}
2000130167Sgad}
2001130167Sgad
2002130167Sgadstatic void
2003130167Sgaddo_zipwork(struct zipwork_entry *zwork)
2004130167Sgad{
2005130167Sgad	const char *pgm_name, *pgm_path;
2006154566Sgad	int errsav, fcount, zstatus;
2007130167Sgad	pid_t pidzip, wpid;
2008130167Sgad	char zresult[MAXPATHLEN];
2009218944Ssobomax	int c;
2010130167Sgad
2011228790Seadler	assert(zwork != NULL);
2012130167Sgad	pgm_path = NULL;
2013130167Sgad	strlcpy(zresult, zwork->zw_fname, sizeof(zresult));
2014228790Seadler	if (zwork->zw_conf != NULL &&
2015218127Smm	    zwork->zw_conf->compress > COMPRESS_NONE)
2016218944Ssobomax		for (c = 1; c < COMPRESS_TYPES; c++) {
2017218127Smm			if (zwork->zw_conf->compress == c) {
2018218127Smm				pgm_path = compress_type[c].path;
2019218127Smm				(void) strlcat(zresult,
2020218127Smm				    compress_type[c].suffix, sizeof(zresult));
2021218127Smm				break;
2022218127Smm			}
2023130167Sgad		}
2024130167Sgad	if (pgm_path == NULL) {
2025130167Sgad		warnx("invalid entry for %s in do_zipwork", zwork->zw_fname);
2026130167Sgad		return;
2027130167Sgad	}
2028154566Sgad	pgm_name = strrchr(pgm_path, '/');
2029154566Sgad	if (pgm_name == NULL)
2030154566Sgad		pgm_name = pgm_path;
2031154566Sgad	else
2032154566Sgad		pgm_name++;
2033130167Sgad
2034245963Smarkj	if (zwork->zw_swork != NULL && zwork->zw_swork->sw_runcmd == 0 &&
2035238281Sae	    zwork->zw_swork->sw_pidok <= 0) {
2036130167Sgad		warnx(
2037130167Sgad		    "log %s not compressed because daemon(s) not notified",
2038130167Sgad		    zwork->zw_fname);
2039130167Sgad		change_attrs(zwork->zw_fname, zwork->zw_conf);
2040130167Sgad		return;
2041130167Sgad	}
2042130167Sgad
2043130167Sgad	if (noaction) {
2044130167Sgad		printf("\t%s %s\n", pgm_name, zwork->zw_fname);
2045130167Sgad		change_attrs(zresult, zwork->zw_conf);
2046130167Sgad		return;
2047130167Sgad	}
2048130167Sgad
2049154566Sgad	fcount = 1;
2050130167Sgad	pidzip = fork();
2051154566Sgad	while (pidzip < 0) {
2052154566Sgad		/*
2053154566Sgad		 * The fork failed.  If the failure was due to a temporary
2054154566Sgad		 * problem, then wait a short time and try it again.
2055154566Sgad		 */
2056154566Sgad		errsav = errno;
2057154566Sgad		warn("fork() for `%s %s'", pgm_name, zwork->zw_fname);
2058154566Sgad		if (errsav != EAGAIN || fcount > 5)
2059154566Sgad			errx(1, "Exiting...");
2060154566Sgad		sleep(fcount * 12);
2061154566Sgad		fcount++;
2062154566Sgad		pidzip = fork();
2063154566Sgad	}
2064154566Sgad	if (!pidzip) {
2065130167Sgad		/* The child process executes the compression command */
2066130167Sgad		execl(pgm_path, pgm_path, "-f", zwork->zw_fname, (char *)0);
2067154566Sgad		err(1, "execl(`%s -f %s')", pgm_path, zwork->zw_fname);
2068130167Sgad	}
2069130167Sgad
2070130167Sgad	wpid = waitpid(pidzip, &zstatus, 0);
2071130167Sgad	if (wpid == -1) {
2072154566Sgad		/* XXX - should this be a fatal error? */
2073130167Sgad		warn("%s: waitpid(%d)", pgm_path, pidzip);
2074130167Sgad		return;
2075130167Sgad	}
2076130167Sgad	if (!WIFEXITED(zstatus)) {
2077154566Sgad		warnx("`%s -f %s' did not terminate normally", pgm_name,
2078154566Sgad		    zwork->zw_fname);
2079130167Sgad		return;
2080130167Sgad	}
2081130167Sgad	if (WEXITSTATUS(zstatus)) {
2082154566Sgad		warnx("`%s -f %s' terminated with a non-zero status (%d)",
2083154566Sgad		    pgm_name, zwork->zw_fname, WEXITSTATUS(zstatus));
2084130167Sgad		return;
2085130167Sgad	}
2086130167Sgad
2087130167Sgad	/* Compression was successful, set file attributes on the result. */
2088130167Sgad	change_attrs(zresult, zwork->zw_conf);
2089130167Sgad}
2090130167Sgad
2091130167Sgad/*
2092130167Sgad * Save information on any process we need to signal.  Any single
2093130167Sgad * process may need to be sent different signal-values for different
2094130167Sgad * log files, but usually a single signal-value will cause the process
2095130167Sgad * to close and re-open all of it's log files.
2096130167Sgad */
2097130167Sgadstatic struct sigwork_entry *
2098130167Sgadsave_sigwork(const struct conf_entry *ent)
2099130167Sgad{
2100130167Sgad	struct sigwork_entry *sprev, *stmp;
2101130167Sgad	int ndiff;
2102130167Sgad	size_t tmpsiz;
2103130167Sgad
2104130167Sgad	sprev = NULL;
2105130167Sgad	ndiff = 1;
2106130167Sgad	SLIST_FOREACH(stmp, &swhead, sw_nextp) {
2107221873Ssobomax		ndiff = strcmp(ent->pid_cmd_file, stmp->sw_fname);
2108130167Sgad		if (ndiff > 0)
2109130167Sgad			break;
2110130167Sgad		if (ndiff == 0) {
2111130167Sgad			if (ent->sig == stmp->sw_signum)
2112130167Sgad				break;
2113130167Sgad			if (ent->sig > stmp->sw_signum) {
2114130167Sgad				ndiff = 1;
2115130167Sgad				break;
2116130167Sgad			}
2117130167Sgad		}
2118130167Sgad		sprev = stmp;
2119130167Sgad	}
2120130167Sgad	if (stmp != NULL && ndiff == 0)
2121130167Sgad		return (stmp);
2122130167Sgad
2123221873Ssobomax	tmpsiz = sizeof(struct sigwork_entry) + strlen(ent->pid_cmd_file) + 1;
2124130167Sgad	stmp = malloc(tmpsiz);
2125321263Sngie
2126245963Smarkj	stmp->sw_runcmd = 0;
2127221873Ssobomax	/* If this is a command to run we just set the flag and run command */
2128221873Ssobomax	if (ent->flags & CE_PID2CMD) {
2129245961Smarkj		stmp->sw_pid = -1;
2130245961Smarkj		stmp->sw_pidok = 0;
2131245963Smarkj		stmp->sw_runcmd = 1;
2132221873Ssobomax	} else {
2133221873Ssobomax		set_swpid(stmp, ent);
2134221873Ssobomax	}
2135130167Sgad	stmp->sw_signum = ent->sig;
2136221873Ssobomax	strcpy(stmp->sw_fname, ent->pid_cmd_file);
2137130167Sgad	if (sprev == NULL)
2138130167Sgad		SLIST_INSERT_HEAD(&swhead, stmp, sw_nextp);
2139130167Sgad	else
2140130167Sgad		SLIST_INSERT_AFTER(sprev, stmp, sw_nextp);
2141130167Sgad	return (stmp);
2142130167Sgad}
2143130167Sgad
2144130167Sgad/*
2145130167Sgad * Save information on any file we need to compress.  We may see the same
2146130167Sgad * file multiple times, so check the full list to avoid duplicates.  The
2147130167Sgad * list itself is sorted smallest-to-largest, because that's the order we
2148130167Sgad * want to compress the files.  If the partition is very low on disk space,
2149130167Sgad * then the smallest files are the most likely to compress, and compressing
2150130167Sgad * them first will free up more space for the larger files.
2151130167Sgad */
2152130167Sgadstatic struct zipwork_entry *
2153130167Sgadsave_zipwork(const struct conf_entry *ent, const struct sigwork_entry *swork,
2154130167Sgad    int zsize, const char *zipfname)
2155130167Sgad{
2156130167Sgad	struct zipwork_entry *zprev, *ztmp;
2157130167Sgad	int ndiff;
2158130167Sgad	size_t tmpsiz;
2159130167Sgad
2160130167Sgad	/* Compute the size if the caller did not know it. */
2161130167Sgad	if (zsize < 0)
2162130167Sgad		zsize = sizefile(zipfname);
2163130167Sgad
2164130167Sgad	zprev = NULL;
2165130167Sgad	ndiff = 1;
2166130167Sgad	SLIST_FOREACH(ztmp, &zwhead, zw_nextp) {
2167130707Sgad		ndiff = strcmp(zipfname, ztmp->zw_fname);
2168130167Sgad		if (ndiff == 0)
2169130167Sgad			break;
2170130167Sgad		if (zsize > ztmp->zw_fsize)
2171130167Sgad			zprev = ztmp;
2172130167Sgad	}
2173130167Sgad	if (ztmp != NULL && ndiff == 0)
2174130167Sgad		return (ztmp);
2175130167Sgad
2176130167Sgad	tmpsiz = sizeof(struct zipwork_entry) + strlen(zipfname) + 1;
2177130167Sgad	ztmp = malloc(tmpsiz);
2178130167Sgad	ztmp->zw_conf = ent;
2179130167Sgad	ztmp->zw_swork = swork;
2180130167Sgad	ztmp->zw_fsize = zsize;
2181130167Sgad	strcpy(ztmp->zw_fname, zipfname);
2182130167Sgad	if (zprev == NULL)
2183130167Sgad		SLIST_INSERT_HEAD(&zwhead, ztmp, zw_nextp);
2184130167Sgad	else
2185130167Sgad		SLIST_INSERT_AFTER(zprev, ztmp, zw_nextp);
2186130167Sgad	return (ztmp);
2187130167Sgad}
2188130167Sgad
2189130167Sgad/* Send a signal to the pid specified by pidfile */
2190130167Sgadstatic void
2191130167Sgadset_swpid(struct sigwork_entry *swork, const struct conf_entry *ent)
2192130167Sgad{
2193130167Sgad	FILE *f;
2194130167Sgad	long minok, maxok, rval;
2195130167Sgad	char *endp, *linep, line[BUFSIZ];
2196130167Sgad
2197130167Sgad	minok = MIN_PID;
2198130167Sgad	maxok = MAX_PID;
2199130167Sgad	swork->sw_pidok = 0;
2200130167Sgad	swork->sw_pid = 0;
2201130167Sgad	swork->sw_pidtype = "daemon";
2202130167Sgad	if (ent->flags & CE_SIGNALGROUP) {
2203130167Sgad		/*
2204130167Sgad		 * If we are expected to signal a process-group when
2205130167Sgad		 * rotating this logfile, then the value read in should
2206130167Sgad		 * be the negative of a valid process ID.
2207130167Sgad		 */
2208130167Sgad		minok = -MAX_PID;
2209130167Sgad		maxok = -MIN_PID;
2210130167Sgad		swork->sw_pidtype = "process-group";
2211130167Sgad	}
2212130167Sgad
2213221873Ssobomax	f = fopen(ent->pid_cmd_file, "r");
2214130167Sgad	if (f == NULL) {
2215202668Sdelphij		if (errno == ENOENT && enforcepid == 0) {
2216200806Sdelphij			/*
2217200806Sdelphij			 * Warn if the PID file doesn't exist, but do
2218200806Sdelphij			 * not consider it an error.  Most likely it
2219200806Sdelphij			 * means the process has been terminated,
2220200806Sdelphij			 * so it should be safe to rotate any log
2221200806Sdelphij			 * files that the process would have been using.
2222200806Sdelphij			 */
2223200806Sdelphij			swork->sw_pidok = 1;
2224221873Ssobomax			warnx("pid file doesn't exist: %s", ent->pid_cmd_file);
2225200806Sdelphij		} else
2226221873Ssobomax			warn("can't open pid file: %s", ent->pid_cmd_file);
2227130167Sgad		return;
2228130167Sgad	}
2229130167Sgad
2230130167Sgad	if (fgets(line, BUFSIZ, f) == NULL) {
2231130167Sgad		/*
2232130167Sgad		 * Warn if the PID file is empty, but do not consider
2233130167Sgad		 * it an error.  Most likely it means the process has
2234130167Sgad		 * has terminated, so it should be safe to rotate any
2235130167Sgad		 * log files that the process would have been using.
2236130167Sgad		 */
2237202668Sdelphij		if (feof(f) && enforcepid == 0) {
2238130167Sgad			swork->sw_pidok = 1;
2239221873Ssobomax			warnx("pid/cmd file is empty: %s", ent->pid_cmd_file);
2240130167Sgad		} else
2241221873Ssobomax			warn("can't read from pid file: %s", ent->pid_cmd_file);
2242130167Sgad		(void)fclose(f);
2243130167Sgad		return;
2244130167Sgad	}
2245130167Sgad	(void)fclose(f);
2246130167Sgad
2247130167Sgad	errno = 0;
2248130167Sgad	linep = line;
2249130167Sgad	while (*linep == ' ')
2250130167Sgad		linep++;
2251130167Sgad	rval = strtol(linep, &endp, 10);
2252130167Sgad	if (*endp != '\0' && !isspacech(*endp)) {
2253130167Sgad		warnx("pid file does not start with a valid number: %s",
2254221873Ssobomax		    ent->pid_cmd_file);
2255130167Sgad	} else if (rval < minok || rval > maxok) {
2256130167Sgad		warnx("bad value '%ld' for process number in %s",
2257221873Ssobomax		    rval, ent->pid_cmd_file);
2258130167Sgad		if (verbose)
2259130167Sgad			warnx("\t(expecting value between %ld and %ld)",
2260130167Sgad			    minok, maxok);
2261130167Sgad	} else {
2262130167Sgad		swork->sw_pidok = 1;
2263130167Sgad		swork->sw_pid = rval;
2264130167Sgad	}
2265130167Sgad
2266130167Sgad	return;
2267130167Sgad}
2268130167Sgad
226913244Sgraichen/* Log the fact that the logs were turned over */
227059004Shmstatic int
2271119926Sgadlog_trim(const char *logname, const struct conf_entry *log_ent)
227213244Sgraichen{
227359003Shm	FILE *f;
2274111388Sgad	const char *xtra;
227559003Shm
2276119926Sgad	if ((f = fopen(logname, "a")) == NULL)
227759003Shm		return (-1);
2278111388Sgad	xtra = "";
2279111768Sgad	if (log_ent->def_cfg)
2280111388Sgad		xtra = " using <default> rule";
2281321263Sngie	if (log_ent->flags & CE_RFC5424) {
2282321263Sngie		if (log_ent->firstcreate) {
2283321263Sngie			fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s\n",
2284321263Sngie			    LOG_MAKEPRI(LOG_USER, LOG_INFO),
2285321263Sngie			    daytime_rfc5424, hostname, getpid(),
2286321263Sngie			    "logfile first created", xtra);
2287321263Sngie		} else if (log_ent->r_reason != NULL) {
2288321263Sngie			fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s%s\n",
2289321263Sngie			    LOG_MAKEPRI(LOG_USER, LOG_INFO),
2290321263Sngie			    daytime_rfc5424, hostname, getpid(),
2291321263Sngie			    "logfile turned over", log_ent->r_reason, xtra);
2292321263Sngie		} else {
2293321263Sngie			fprintf(f, "<%d>1 %s %s newsyslog %d - - %s%s\n",
2294321263Sngie			    LOG_MAKEPRI(LOG_USER, LOG_INFO),
2295321263Sngie			    daytime_rfc5424, hostname, getpid(),
2296321263Sngie			    "logfile turned over", xtra);
2297321263Sngie		}
2298321263Sngie	} else {
2299321263Sngie		if (log_ent->firstcreate)
2300321263Sngie			fprintf(f, "%s %s newsyslog[%d]: logfile first created%s\n",
2301321263Sngie			    daytime, hostname, getpid(), xtra);
2302321263Sngie		else if (log_ent->r_reason != NULL)
2303321263Sngie			fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s%s\n",
2304321263Sngie			    daytime, hostname, getpid(), log_ent->r_reason, xtra);
2305321263Sngie		else
2306321263Sngie			fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s\n",
2307321263Sngie			    daytime, hostname, getpid(), xtra);
2308321263Sngie	}
230959003Shm	if (fclose(f) == EOF)
2310127858Scharnier		err(1, "log_trim: fclose");
231159003Shm	return (0);
231213244Sgraichen}
231313244Sgraichen
231413244Sgraichen/* Return size in kilobytes of a file */
231559004Shmstatic int
2316130165Sgadsizefile(const char *file)
231713244Sgraichen{
231859003Shm	struct stat sb;
231913244Sgraichen
232059003Shm	if (stat(file, &sb) < 0)
232159003Shm		return (-1);
2322262075Sbdrewery	return (kbytes(sb.st_size));
232313244Sgraichen}
232413244Sgraichen
2325248776Smarkj/*
2326248776Smarkj * Return the mtime of the most recent archive of the logfile, using timestamp
2327248776Smarkj * based filenames.
2328248776Smarkj */
2329248776Smarkjstatic time_t
2330248776Smarkjmtime_old_timelog(const char *file)
2331248776Smarkj{
2332248776Smarkj	struct stat sb;
2333248776Smarkj	struct tm tm;
2334248776Smarkj	int dir_fd;
2335248776Smarkj	time_t t;
2336248776Smarkj	struct dirent *dp;
2337248776Smarkj	DIR *dirp;
2338248776Smarkj	char *s, *logfname, *dir;
2339248776Smarkj
2340248776Smarkj	t = -1;
2341248776Smarkj
2342248776Smarkj	if ((dir = dirname(file)) == NULL) {
2343248776Smarkj		warn("dirname() of '%s'", file);
2344248776Smarkj		return (t);
2345248776Smarkj	}
2346248776Smarkj	if ((s = basename(file)) == NULL) {
2347248776Smarkj		warn("basename() of '%s'", file);
2348248776Smarkj		return (t);
2349248776Smarkj	} else if (s[0] == '/') {
2350248776Smarkj		warnx("Invalid log filename '%s'", s);
2351248776Smarkj		return (t);
2352248776Smarkj	} else if ((logfname = strdup(s)) == NULL)
2353248776Smarkj		err(1, "strdup()");
2354248776Smarkj
2355248776Smarkj	if ((dirp = opendir(dir)) == NULL) {
2356248776Smarkj		warn("Cannot open log directory '%s'", dir);
2357248776Smarkj		return (t);
2358248776Smarkj	}
2359248776Smarkj	dir_fd = dirfd(dirp);
2360248776Smarkj	/* Open the archive dir and find the most recent archive of logfname. */
2361248776Smarkj	while ((dp = readdir(dirp)) != NULL) {
2362250545Smarkj		if (validate_old_timelog(dir_fd, dp, logfname, &tm) == 0)
2363248776Smarkj			continue;
2364248776Smarkj
2365251240Smarkj		if (fstatat(dir_fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
2366248776Smarkj			warn("Cannot stat '%s'", file);
2367248776Smarkj			continue;
2368248776Smarkj		}
2369248776Smarkj		if (t < sb.st_mtime)
2370248776Smarkj			t = sb.st_mtime;
2371248776Smarkj	}
2372248776Smarkj	closedir(dirp);
2373248776Smarkj
2374248776Smarkj	return (t);
2375248776Smarkj}
2376248776Smarkj
2377248776Smarkj/* Return the age in hours of the most recent archive of the logfile. */
237859004Shmstatic int
2379248776Smarkjage_old_log(const char *file)
238013244Sgraichen{
238159003Shm	struct stat sb;
2382218127Smm	const char *logfile_suffix;
2383218127Smm	char tmp[MAXPATHLEN + sizeof(".0") + COMPRESS_SUFFIX_MAXLEN + 1];
2384248776Smarkj	time_t mtime;
238513244Sgraichen
238659004Shm	if (archtodir) {
238759004Shm		char *p;
238859004Shm
238959004Shm		/* build name of archive directory into tmp */
239059004Shm		if (*archdirname == '/') {	/* absolute */
239171299Sjedgar			strlcpy(tmp, archdirname, sizeof(tmp));
239259004Shm		} else {	/* relative */
239359004Shm			/* get directory part of logfile */
239471299Sjedgar			strlcpy(tmp, file, sizeof(tmp));
2395229403Sed			if ((p = strrchr(tmp, '/')) == NULL)
239659004Shm				tmp[0] = '\0';
239759004Shm			else
239859004Shm				*(p + 1) = '\0';
239971299Sjedgar			strlcat(tmp, archdirname, sizeof(tmp));
240059004Shm		}
240159004Shm
240271299Sjedgar		strlcat(tmp, "/", sizeof(tmp));
240359004Shm
240459004Shm		/* get filename part of logfile */
2405229403Sed		if ((p = strrchr(file, '/')) == NULL)
240671299Sjedgar			strlcat(tmp, file, sizeof(tmp));
240759004Shm		else
240871299Sjedgar			strlcat(tmp, p + 1, sizeof(tmp));
240959004Shm	} else {
241071299Sjedgar		(void) strlcpy(tmp, file, sizeof(tmp));
241159004Shm	}
241259004Shm
2413248776Smarkj	if (timefnamefmt != NULL) {
2414248776Smarkj		mtime = mtime_old_timelog(tmp);
2415248776Smarkj		if (mtime == -1)
2416248776Smarkj			return (-1);
2417248776Smarkj	} else {
2418248776Smarkj		strlcat(tmp, ".0", sizeof(tmp));
2419248776Smarkj		logfile_suffix = get_logfile_suffix(tmp);
2420248776Smarkj		if (logfile_suffix == NULL)
2421248776Smarkj			return (-1);
2422248776Smarkj		(void) strlcat(tmp, logfile_suffix, sizeof(tmp));
2423248776Smarkj		if (stat(tmp, &sb) < 0)
2424248776Smarkj			return (-1);
2425248776Smarkj		mtime = sb.st_mtime;
2426248776Smarkj	}
2427248776Smarkj
2428248776Smarkj	return ((int)(ptimeget_secs(timenow) - mtime + 1800) / 3600);
242913244Sgraichen}
243013244Sgraichen
243113244Sgraichen/* Skip Over Blanks */
2432111820Sgadstatic char *
243359004Shmsob(char *p)
243413244Sgraichen{
243559003Shm	while (p && *p && isspace(*p))
243659003Shm		p++;
243759003Shm	return (p);
243813244Sgraichen}
243913244Sgraichen
244013244Sgraichen/* Skip Over Non-Blanks */
2441111820Sgadstatic char *
244259004Shmson(char *p)
244313244Sgraichen{
244459003Shm	while (p && *p && !isspace(*p))
244559003Shm		p++;
244659003Shm	return (p);
244713244Sgraichen}
244843071Swollman
2449119102Sgad/* Check if string is actually a number */
2450119102Sgadstatic int
2451119102Sgadisnumberstr(const char *string)
2452119102Sgad{
2453119102Sgad	while (*string) {
2454119102Sgad		if (!isdigitch(*string++))
2455119102Sgad			return (0);
2456119102Sgad	}
2457119102Sgad	return (1);
2458119102Sgad}
2459119102Sgad
2460208649Sgordon/* Check if string contains a glob */
2461208649Sgordonstatic int
2462208649Sgordonisglobstr(const char *string)
2463208649Sgordon{
2464208649Sgordon	char chr;
2465208649Sgordon
2466208649Sgordon	while ((chr = *string++)) {
2467208649Sgordon		if (chr == '*' || chr == '?' || chr == '[')
2468208649Sgordon			return (1);
2469208649Sgordon	}
2470208649Sgordon	return (0);
2471208649Sgordon}
2472208649Sgordon
2473130038Sgad/*
2474130038Sgad * Save the active log file under a new name.  A link to the new name
2475130038Sgad * is the quick-and-easy way to do this.  If that fails (which it will
2476130038Sgad * if the destination is on another partition), then make a copy of
2477130038Sgad * the file to the new location.
2478130038Sgad */
247959004Shmstatic void
2480130038Sgadsavelog(char *from, char *to)
248159004Shm{
248259004Shm	FILE *src, *dst;
2483130038Sgad	int c, res;
248459004Shm
2485130038Sgad	res = link(from, to);
2486130038Sgad	if (res == 0)
2487130038Sgad		return;
2488130038Sgad
248959004Shm	if ((src = fopen(from, "r")) == NULL)
249059004Shm		err(1, "can't fopen %s for reading", from);
249159004Shm	if ((dst = fopen(to, "w")) == NULL)
249259004Shm		err(1, "can't fopen %s for writing", to);
249359004Shm
249459004Shm	while ((c = getc(src)) != EOF) {
249559004Shm		if ((putc(c, dst)) == EOF)
249659004Shm			err(1, "error writing to %s", to);
249759004Shm	}
249859004Shm
249959004Shm	if (ferror(src))
250059004Shm		err(1, "error reading from %s", from);
250159004Shm	if ((fclose(src)) != 0)
250259004Shm		err(1, "can't fclose %s", to);
250359004Shm	if ((fclose(dst)) != 0)
250459004Shm		err(1, "can't fclose %s", from);
250559004Shm}
250659004Shm
250759004Shm/* create one or more directory components of a path */
250859004Shmstatic void
2509114137Sgadcreatedir(const struct conf_entry *ent, char *dirpart)
251059004Shm{
2511111398Sgad	int res;
251259004Shm	char *s, *d;
251371299Sjedgar	char mkdirpath[MAXPATHLEN];
251459004Shm	struct stat st;
251559004Shm
251659004Shm	s = dirpart;
251759004Shm	d = mkdirpath;
251859004Shm
251959004Shm	for (;;) {
252059004Shm		*d++ = *s++;
2521111398Sgad		if (*s != '/' && *s != '\0')
2522111398Sgad			continue;
2523111398Sgad		*d = '\0';
2524111398Sgad		res = lstat(mkdirpath, &st);
2525111398Sgad		if (res != 0) {
2526111398Sgad			if (noaction) {
2527111967Sgad				printf("\tmkdir %s\n", mkdirpath);
2528111398Sgad			} else {
2529111398Sgad				res = mkdir(mkdirpath, 0755);
2530111398Sgad				if (res != 0)
2531111398Sgad					err(1, "Error on mkdir(\"%s\") for -a",
2532111398Sgad					    mkdirpath);
2533111398Sgad			}
253459004Shm		}
253559004Shm		if (*s == '\0')
253659004Shm			break;
253759004Shm	}
2538114137Sgad	if (verbose) {
2539114137Sgad		if (ent->firstcreate)
2540114137Sgad			printf("Created directory '%s' for new %s\n",
2541114137Sgad			    dirpart, ent->log);
2542114137Sgad		else
2543114137Sgad			printf("Created directory '%s' for -a\n", dirpart);
2544114137Sgad	}
254559004Shm}
254659004Shm
2547114137Sgad/*
2548114137Sgad * Create a new log file, destroying any currently-existing version
2549114137Sgad * of the log file in the process.  If the caller wants a backup copy
2550114137Sgad * of the file to exist, they should call 'link(logfile,logbackup)'
2551114137Sgad * before calling this routine.
2552114137Sgad */
2553114137Sgadvoid
2554114137Sgadcreatelog(const struct conf_entry *ent)
2555114137Sgad{
2556114137Sgad	int fd, failed;
2557114137Sgad	struct stat st;
2558114137Sgad	char *realfile, *slash, tempfile[MAXPATHLEN];
2559114137Sgad
2560114137Sgad	fd = -1;
2561114137Sgad	realfile = ent->log;
2562114137Sgad
2563114137Sgad	/*
2564114137Sgad	 * If this log file is being created for the first time (-C option),
2565114137Sgad	 * then it may also be true that the parent directory does not exist
2566114137Sgad	 * yet.  Check, and create that directory if it is missing.
2567114137Sgad	 */
2568114137Sgad	if (ent->firstcreate) {
2569114137Sgad		strlcpy(tempfile, realfile, sizeof(tempfile));
2570114137Sgad		slash = strrchr(tempfile, '/');
2571114137Sgad		if (slash != NULL) {
2572114137Sgad			*slash = '\0';
2573131581Ssobomax			failed = stat(tempfile, &st);
2574114137Sgad			if (failed && errno != ENOENT)
2575131581Ssobomax				err(1, "Error on stat(%s)", tempfile);
2576114137Sgad			if (failed)
2577114137Sgad				createdir(ent, tempfile);
2578114137Sgad			else if (!S_ISDIR(st.st_mode))
2579114137Sgad				errx(1, "%s exists but is not a directory",
2580114137Sgad				    tempfile);
2581114137Sgad		}
2582114137Sgad	}
2583114137Sgad
2584114137Sgad	/*
2585114137Sgad	 * First create an unused filename, so it can be chown'ed and
2586114137Sgad	 * chmod'ed before it is moved into the real location.  mkstemp
2587114137Sgad	 * will create the file mode=600 & owned by us.  Note that all
2588114137Sgad	 * temp files will have a suffix of '.z<something>'.
2589114137Sgad	 */
2590114137Sgad	strlcpy(tempfile, realfile, sizeof(tempfile));
2591114137Sgad	strlcat(tempfile, ".zXXXXXX", sizeof(tempfile));
2592114137Sgad	if (noaction)
2593114137Sgad		printf("\tmktemp %s\n", tempfile);
2594114137Sgad	else {
2595114137Sgad		fd = mkstemp(tempfile);
2596114137Sgad		if (fd < 0)
2597114137Sgad			err(1, "can't mkstemp logfile %s", tempfile);
2598114137Sgad
2599114137Sgad		/*
2600114137Sgad		 * Add status message to what will become the new log file.
2601114137Sgad		 */
2602114137Sgad		if (!(ent->flags & CE_BINARY)) {
2603114137Sgad			if (log_trim(tempfile, ent))
2604114137Sgad				err(1, "can't add status message to log");
2605114137Sgad		}
2606114137Sgad	}
2607114137Sgad
2608114137Sgad	/* Change the owner/group, if we are supposed to */
2609114137Sgad	if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2610114137Sgad		if (noaction)
2611114137Sgad			printf("\tchown %u:%u %s\n", ent->uid, ent->gid,
2612114137Sgad			    tempfile);
2613114137Sgad		else {
2614114137Sgad			failed = fchown(fd, ent->uid, ent->gid);
2615114137Sgad			if (failed)
2616114137Sgad				err(1, "can't fchown temp file %s", tempfile);
2617114137Sgad		}
2618114137Sgad	}
2619114137Sgad
2620130043Sgad	/* Turn on NODUMP if it was requested in the config-file. */
2621130043Sgad	if (ent->flags & CE_NODUMP) {
2622130043Sgad		if (noaction)
2623130043Sgad			printf("\tchflags nodump %s\n", tempfile);
2624130043Sgad		else {
2625130043Sgad			failed = fchflags(fd, UF_NODUMP);
2626130043Sgad			if (failed) {
2627130043Sgad				warn("log_trim: fchflags(NODUMP)");
2628130043Sgad			}
2629130043Sgad		}
2630130043Sgad	}
2631130043Sgad
2632114137Sgad	/*
2633114137Sgad	 * Note that if the real logfile still exists, and if the call
2634114137Sgad	 * to rename() fails, then "neither the old file nor the new
2635114137Sgad	 * file shall be changed or created" (to quote the standard).
2636114137Sgad	 * If the call succeeds, then the file will be replaced without
2637114137Sgad	 * any window where some other process might find that the file
2638114137Sgad	 * did not exist.
2639114137Sgad	 * XXX - ? It may be that for some error conditions, we could
2640114137Sgad	 *	retry by first removing the realfile and then renaming.
2641114137Sgad	 */
2642114137Sgad	if (noaction) {
2643114137Sgad		printf("\tchmod %o %s\n", ent->permissions, tempfile);
2644114137Sgad		printf("\tmv %s %s\n", tempfile, realfile);
2645114137Sgad	} else {
2646114137Sgad		failed = fchmod(fd, ent->permissions);
2647114137Sgad		if (failed)
2648114137Sgad			err(1, "can't fchmod temp file '%s'", tempfile);
2649114137Sgad		failed = rename(tempfile, realfile);
2650114137Sgad		if (failed)
2651114137Sgad			err(1, "can't mv %s to %s", tempfile, realfile);
2652114137Sgad	}
2653114137Sgad
2654114137Sgad	if (fd >= 0)
2655114137Sgad		close(fd);
2656114137Sgad}
2657130165Sgad
2658154566Sgad/*
2659154566Sgad * Change the attributes of a given filename to what was specified in
2660154566Sgad * the newsyslog.conf entry.  This routine is only called for files
2661154566Sgad * that newsyslog expects that it has created, and thus it is a fatal
2662154566Sgad * error if this routine finds that the file does not exist.
2663154566Sgad */
2664130165Sgadstatic void
2665130165Sgadchange_attrs(const char *fname, const struct conf_entry *ent)
2666130165Sgad{
2667130165Sgad	int failed;
2668130165Sgad
2669130165Sgad	if (noaction) {
2670130165Sgad		printf("\tchmod %o %s\n", ent->permissions, fname);
2671130165Sgad
2672130165Sgad		if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
2673130165Sgad			printf("\tchown %u:%u %s\n",
2674130165Sgad			    ent->uid, ent->gid, fname);
2675130165Sgad
2676130165Sgad		if (ent->flags & CE_NODUMP)
2677130165Sgad			printf("\tchflags nodump %s\n", fname);
2678130165Sgad		return;
2679130165Sgad	}
2680130165Sgad
2681130165Sgad	failed = chmod(fname, ent->permissions);
2682154566Sgad	if (failed) {
2683154566Sgad		if (errno != EPERM)
2684154566Sgad			err(1, "chmod(%s) in change_attrs", fname);
2685154566Sgad		warn("change_attrs couldn't chmod(%s)", fname);
2686154566Sgad	}
2687130165Sgad
2688130165Sgad	if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2689130165Sgad		failed = chown(fname, ent->uid, ent->gid);
2690130165Sgad		if (failed)
2691130165Sgad			warn("can't chown %s", fname);
2692130165Sgad	}
2693130165Sgad
2694130165Sgad	if (ent->flags & CE_NODUMP) {
2695130165Sgad		failed = chflags(fname, UF_NODUMP);
2696130165Sgad		if (failed)
2697130165Sgad			warn("can't chflags %s NODUMP", fname);
2698130165Sgad	}
2699130165Sgad}
2700290225Sbapt
2701290225Sbapt/*
2702290225Sbapt * Parse a signal number or signal name. Returns the signal number parsed or -1
2703290225Sbapt * on failure.
2704290225Sbapt */
2705290225Sbaptstatic int
2706290225Sbaptparse_signal(const char *str)
2707290225Sbapt{
2708290225Sbapt	int sig, i;
2709290225Sbapt	const char *errstr;
2710290225Sbapt
2711290225Sbapt	sig = strtonum(str, 1, sys_nsig - 1, &errstr);
2712290225Sbapt
2713290225Sbapt	if (errstr == NULL)
2714290225Sbapt		return (sig);
2715290225Sbapt	if (strncasecmp(str, "SIG", 3) == 0)
2716290225Sbapt		str += 3;
2717290225Sbapt
2718290225Sbapt	for (i = 1; i < sys_nsig; i++) {
2719290225Sbapt		if (strcasecmp(str, sys_signame[i]) == 0)
2720290225Sbapt			return (i);
2721290225Sbapt	}
2722290225Sbapt
2723290225Sbapt	return (-1);
2724290225Sbapt}
2725