newsyslog.c revision 246918
1231990Smp/*-
259243Sobrien * ------+---------+---------+-------- + --------+---------+---------+---------*
359243Sobrien * This file includes significant modifications done by:
459243Sobrien * Copyright (c) 2003, 2004  - Garance Alistair Drosehn <gad@FreeBSD.org>.
559243Sobrien * All rights reserved.
659243Sobrien *
759243Sobrien * Redistribution and use in source and binary forms, with or without
859243Sobrien * modification, are permitted provided that the following conditions
959243Sobrien * are met:
1059243Sobrien *   1. Redistributions of source code must retain the above copyright
1159243Sobrien *      notice, this list of conditions and the following disclaimer.
1259243Sobrien *   2. Redistributions in binary form must reproduce the above copyright
1359243Sobrien *      notice, this list of conditions and the following disclaimer in the
1459243Sobrien *      documentation and/or other materials provided with the distribution.
1559243Sobrien *
1659243Sobrien * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17100616Smp * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1859243Sobrien * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1959243Sobrien * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
2059243Sobrien * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2159243Sobrien * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2259243Sobrien * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2359243Sobrien * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2459243Sobrien * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2559243Sobrien * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2659243Sobrien * SUCH DAMAGE.
2759243Sobrien *
2859243Sobrien * ------+---------+---------+-------- + --------+---------+---------+---------*
2959243Sobrien */
3059243Sobrien
3159243Sobrien/*
3259243Sobrien * This file contains changes from the Open Software Foundation.
3359243Sobrien */
3469408Sache
3559243Sobrien/*
36231990Smp * Copyright 1988, 1989 by the Massachusetts Institute of Technology
37231990Smp *
3859243Sobrien * Permission to use, copy, modify, and distribute this software and its
3959243Sobrien * documentation for any purpose and without fee is hereby granted, provided
4059243Sobrien * that the above copyright notice appear in all copies and that both that
4159243Sobrien * copyright notice and this permission notice appear in supporting
4259243Sobrien * documentation, and that the names of M.I.T. and the M.I.T. S.I.P.B. not be
4359243Sobrien * used in advertising or publicity pertaining to distribution of the
4459243Sobrien * software without specific, written prior permission. M.I.T. and the M.I.T.
4559243Sobrien * S.I.P.B. make no representations about the suitability of this software
4659243Sobrien * for any purpose.  It is provided "as is" without express or implied
4759243Sobrien * warranty.
4859243Sobrien *
4959243Sobrien */
5059243Sobrien
5159243Sobrien/*
5259243Sobrien * newsyslog - roll over selected logs at the appropriate time, keeping the a
5359243Sobrien * specified number of backup files around.
5459243Sobrien */
5559243Sobrien
5659243Sobrien#include <sys/cdefs.h>
5759243Sobrien__FBSDID("$FreeBSD: stable/9/usr.sbin/newsyslog/newsyslog.c 246918 2013-02-17 19:49:18Z markj $");
5859243Sobrien
5959243Sobrien#define	OSF
6059243Sobrien
6159243Sobrien#include <sys/param.h>
6259243Sobrien#include <sys/queue.h>
6359243Sobrien#include <sys/stat.h>
6459243Sobrien#include <sys/wait.h>
6559243Sobrien
6659243Sobrien#include <assert.h>
6759243Sobrien#include <ctype.h>
6859243Sobrien#include <err.h>
6959243Sobrien#include <errno.h>
7059243Sobrien#include <dirent.h>
7159243Sobrien#include <fcntl.h>
7259243Sobrien#include <fnmatch.h>
7359243Sobrien#include <glob.h>
7459243Sobrien#include <grp.h>
7559243Sobrien#include <paths.h>
7659243Sobrien#include <pwd.h>
7759243Sobrien#include <signal.h>
7859243Sobrien#include <stdio.h>
7959243Sobrien#include <libgen.h>
8059243Sobrien#include <stdlib.h>
8159243Sobrien#include <string.h>
8259243Sobrien#include <time.h>
8359243Sobrien#include <unistd.h>
8459243Sobrien
8559243Sobrien#include "pathnames.h"
8659243Sobrien#include "extern.h"
87167465Smp
88145479Smp/*
8959243Sobrien * Compression suffixes
9059243Sobrien */
9159243Sobrien#ifndef	COMPRESS_SUFFIX_GZ
9259243Sobrien#define	COMPRESS_SUFFIX_GZ	".gz"
9359243Sobrien#endif
9459243Sobrien
9559243Sobrien#ifndef	COMPRESS_SUFFIX_BZ2
9659243Sobrien#define	COMPRESS_SUFFIX_BZ2	".bz2"
9759243Sobrien#endif
9859243Sobrien
9959243Sobrien#ifndef	COMPRESS_SUFFIX_XZ
10059243Sobrien#define	COMPRESS_SUFFIX_XZ	".xz"
10159243Sobrien#endif
10259243Sobrien
10359243Sobrien#define	COMPRESS_SUFFIX_MAXLEN	MAX(MAX(sizeof(COMPRESS_SUFFIX_GZ),sizeof(COMPRESS_SUFFIX_BZ2)),sizeof(COMPRESS_SUFFIX_XZ))
10459243Sobrien
10559243Sobrien/*
10659243Sobrien * Compression types
10759243Sobrien */
10859243Sobrien#define	COMPRESS_TYPES  4	/* Number of supported compression types */
10959243Sobrien
11059243Sobrien#define	COMPRESS_NONE	0
11159243Sobrien#define	COMPRESS_GZIP	1
11259243Sobrien#define	COMPRESS_BZIP2	2
11359243Sobrien#define	COMPRESS_XZ	3
11459243Sobrien
11559243Sobrien/*
11659243Sobrien * Bit-values for the 'flags' parsed from a config-file entry.
11759243Sobrien */
11859243Sobrien#define	CE_BINARY	0x0008	/* Logfile is in binary, do not add status */
11959243Sobrien				/*    messages to logfile(s) when rotating. */
12059243Sobrien#define	CE_NOSIGNAL	0x0010	/* There is no process to signal when */
12159243Sobrien				/*    trimming this file. */
12259243Sobrien#define	CE_TRIMAT	0x0020	/* trim file at a specific time. */
12359243Sobrien#define	CE_GLOB		0x0040	/* name of the log is file name pattern. */
12459243Sobrien#define	CE_SIGNALGROUP	0x0080	/* Signal a process-group instead of a single */
12559243Sobrien				/*    process when trimming this file. */
12659243Sobrien#define	CE_CREATE	0x0100	/* Create the log file if it does not exist. */
12759243Sobrien#define	CE_NODUMP	0x0200	/* Set 'nodump' on newly created log file. */
12859243Sobrien#define	CE_PID2CMD	0x0400	/* Replace PID file with a shell command.*/
12959243Sobrien
13059243Sobrien#define	MIN_PID         5	/* Don't touch pids lower than this */
13159243Sobrien#define	MAX_PID		99999	/* was lower, see /usr/include/sys/proc.h */
13259243Sobrien
13359243Sobrien#define	kbytes(size)  (((size) + 1023) >> 10)
13459243Sobrien
13559243Sobrien#define	DEFAULT_MARKER	"<default>"
13659243Sobrien#define	DEBUG_MARKER	"<debug>"
13759243Sobrien#define	INCLUDE_MARKER	"<include>"
13859243Sobrien#define	DEFAULT_TIMEFNAME_FMT	"%Y%m%dT%H%M%S"
13959243Sobrien
14059243Sobrien#define	MAX_OLDLOGS 65536	/* Default maximum number of old logfiles */
14159243Sobrien
14259243Sobrienstruct compress_types {
14359243Sobrien	const char *flag;	/* Flag in configuration file */
14459243Sobrien	const char *suffix;	/* Compression suffix */
14559243Sobrien	const char *path;	/* Path to compression program */
14659243Sobrien};
14759243Sobrien
14859243Sobrienconst struct compress_types compress_type[COMPRESS_TYPES] = {
14959243Sobrien	{ "", "", "" },					/* no compression */
15059243Sobrien	{ "Z", COMPRESS_SUFFIX_GZ, _PATH_GZIP },	/* gzip compression */
15159243Sobrien	{ "J", COMPRESS_SUFFIX_BZ2, _PATH_BZIP2 },	/* bzip2 compression */
15259243Sobrien	{ "X", COMPRESS_SUFFIX_XZ, _PATH_XZ }		/* xz compression */
15359243Sobrien};
15459243Sobrien
15559243Sobrienstruct conf_entry {
15659243Sobrien	STAILQ_ENTRY(conf_entry) cf_nextp;
15759243Sobrien	char *log;		/* Name of the log */
15859243Sobrien	char *pid_cmd_file;		/* PID or command file */
15959243Sobrien	char *r_reason;		/* The reason this file is being rotated */
16059243Sobrien	int firstcreate;	/* Creating log for the first time (-C). */
16159243Sobrien	int rotate;		/* Non-zero if this file should be rotated */
16259243Sobrien	int fsize;		/* size found for the log file */
16359243Sobrien	uid_t uid;		/* Owner of log */
16459243Sobrien	gid_t gid;		/* Group of log */
16559243Sobrien	int numlogs;		/* Number of logs to keep */
16659243Sobrien	int trsize;		/* Size cutoff to trigger trimming the log */
16759243Sobrien	int hours;		/* Hours between log trimming */
16859243Sobrien	struct ptime_data *trim_at;	/* Specific time to do trimming */
16959243Sobrien	unsigned int permissions;	/* File permissions on the log */
17059243Sobrien	int flags;		/* CE_BINARY */
17159243Sobrien	int compress;		/* Compression */
17259243Sobrien	int sig;		/* Signal to send */
17359243Sobrien	int def_cfg;		/* Using the <default> rule for this file */
17459243Sobrien};
17559243Sobrien
17659243Sobrienstruct sigwork_entry {
17759243Sobrien	SLIST_ENTRY(sigwork_entry) sw_nextp;
17859243Sobrien	int	 sw_signum;		/* the signal to send */
17959243Sobrien	int	 sw_pidok;		/* true if pid value is valid */
18059243Sobrien	pid_t	 sw_pid;		/* the process id from the PID file */
18159243Sobrien	const char *sw_pidtype;		/* "daemon" or "process group" */
18259243Sobrien	int	 sw_runcmd;		/* run command or send PID to signal */
18359243Sobrien	char	 sw_fname[1];		/* file the PID was read from or shell cmd */
18459243Sobrien};
18559243Sobrien
18659243Sobrienstruct zipwork_entry {
18759243Sobrien	SLIST_ENTRY(zipwork_entry) zw_nextp;
18859243Sobrien	const struct conf_entry *zw_conf;	/* for chown/perm/flag info */
18959243Sobrien	const struct sigwork_entry *zw_swork;	/* to know success of signal */
19059243Sobrien	int	 zw_fsize;		/* size of the file to compress */
19159243Sobrien	char	 zw_fname[1];		/* the file to compress */
19259243Sobrien};
19359243Sobrien
19459243Sobrienstruct include_entry {
19559243Sobrien	STAILQ_ENTRY(include_entry) inc_nextp;
19659243Sobrien	const char *file;	/* Name of file to process */
19759243Sobrien};
19859243Sobrien
19959243Sobrienstruct oldlog_entry {
20059243Sobrien	char *fname;		/* Filename of the log file */
20159243Sobrien	time_t t;		/* Parsed timestamp of the logfile */
20259243Sobrien};
20359243Sobrien
20459243Sobrientypedef enum {
20559243Sobrien	FREE_ENT, KEEP_ENT
20659243Sobrien}	fk_entry;
20759243Sobrien
20859243SobrienSTAILQ_HEAD(cflist, conf_entry);
20959243SobrienSLIST_HEAD(swlisthead, sigwork_entry) swhead = SLIST_HEAD_INITIALIZER(swhead);
21059243SobrienSLIST_HEAD(zwlisthead, zipwork_entry) zwhead = SLIST_HEAD_INITIALIZER(zwhead);
21159243SobrienSTAILQ_HEAD(ilist, include_entry);
21259243Sobrien
21359243Sobrienint dbg_at_times;		/* -D Show details of 'trim_at' code */
21459243Sobrien
21559243Sobrienint archtodir = 0;		/* Archive old logfiles to other directory */
21659243Sobrienint createlogs;			/* Create (non-GLOB) logfiles which do not */
21759243Sobrien				/*    already exist.  1=='for entries with */
21859243Sobrien				/*    C flag', 2=='for all entries'. */
21959243Sobrienint verbose = 0;		/* Print out what's going on */
22059243Sobrienint needroot = 1;		/* Root privs are necessary */
22159243Sobrienint noaction = 0;		/* Don't do anything, just show it */
22259243Sobrienint norotate = 0;		/* Don't rotate */
22359243Sobrienint nosignal;			/* Do not send any signals */
22459243Sobrienint enforcepid = 0;		/* If PID file does not exist or empty, do nothing */
22559243Sobrienint force = 0;			/* Force the trim no matter what */
22659243Sobrienint rotatereq = 0;		/* -R = Always rotate the file(s) as given */
22759243Sobrien				/*    on the command (this also requires   */
22859243Sobrien				/*    that a list of files *are* given on  */
22959243Sobrien				/*    the run command). */
23059243Sobrienchar *requestor;		/* The name given on a -R request */
23159243Sobrienchar *timefnamefmt = NULL;	/* Use time based filenames instead of .0 etc */
23259243Sobrienchar *archdirname;		/* Directory path to old logfiles archive */
23359243Sobrienchar *destdir = NULL;		/* Directory to treat at root for logs */
23459243Sobrienconst char *conf;		/* Configuration file to use */
23559243Sobrien
23659243Sobrienstruct ptime_data *dbg_timenow;	/* A "timenow" value set via -D option */
23759243Sobrienstruct ptime_data *timenow;	/* The time to use for checking at-fields */
23859243Sobrien
23959243Sobrien#define	DAYTIME_LEN	16
24059243Sobrienchar daytime[DAYTIME_LEN];	/* The current time in human readable form,
24159243Sobrien				 * used for rotation-tracking messages. */
24259243Sobrienchar hostname[MAXHOSTNAMELEN];	/* hostname */
24359243Sobrien
24459243Sobrienconst char *path_syslogpid = _PATH_SYSLOGPID;
24559243Sobrien
24659243Sobrienstatic struct cflist *get_worklist(char **files);
24759243Sobrienstatic void parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
24859243Sobrien		    struct conf_entry *defconf_p, struct ilist *inclist);
24959243Sobrienstatic void add_to_queue(const char *fname, struct ilist *inclist);
25059243Sobrienstatic char *sob(char *p);
25159243Sobrienstatic char *son(char *p);
25259243Sobrienstatic int isnumberstr(const char *);
25359243Sobrienstatic int isglobstr(const char *);
25459243Sobrienstatic char *missing_field(char *p, char *errline);
25559243Sobrienstatic void	 change_attrs(const char *, const struct conf_entry *);
25659243Sobrienstatic const char *get_logfile_suffix(const char *logfile);
25759243Sobrienstatic fk_entry	 do_entry(struct conf_entry *);
25859243Sobrienstatic fk_entry	 do_rotate(const struct conf_entry *);
25959243Sobrienstatic void	 do_sigwork(struct sigwork_entry *);
26059243Sobrienstatic void	 do_zipwork(struct zipwork_entry *);
26159243Sobrienstatic struct sigwork_entry *
26259243Sobrien		 save_sigwork(const struct conf_entry *);
26359243Sobrienstatic struct zipwork_entry *
26459243Sobrien		 save_zipwork(const struct conf_entry *, const struct
26559243Sobrien		    sigwork_entry *, int, const char *);
26659243Sobrienstatic void	 set_swpid(struct sigwork_entry *, const struct conf_entry *);
26759243Sobrienstatic int	 sizefile(const char *);
26859243Sobrienstatic void expand_globs(struct cflist *work_p, struct cflist *glob_p);
26959243Sobrienstatic void free_clist(struct cflist *list);
27059243Sobrienstatic void free_entry(struct conf_entry *ent);
27159243Sobrienstatic struct conf_entry *init_entry(const char *fname,
27259243Sobrien		struct conf_entry *src_entry);
27359243Sobrienstatic void parse_args(int argc, char **argv);
27459243Sobrienstatic int parse_doption(const char *doption);
27559243Sobrienstatic void usage(void);
27659243Sobrienstatic int log_trim(const char *logname, const struct conf_entry *log_ent);
27759243Sobrienstatic int age_old_log(char *file);
27859243Sobrienstatic void savelog(char *from, char *to);
27959243Sobrienstatic void createdir(const struct conf_entry *ent, char *dirpart);
28059243Sobrienstatic void createlog(const struct conf_entry *ent);
28159243Sobrien
28259243Sobrien/*
28359243Sobrien * All the following take a parameter of 'int', but expect values in the
28459243Sobrien * range of unsigned char.  Define wrappers which take values of type 'char',
28559243Sobrien * whether signed or unsigned, and ensure they end up in the right range.
28659243Sobrien */
28759243Sobrien#define	isdigitch(Anychar) isdigit((u_char)(Anychar))
28859243Sobrien#define	isprintch(Anychar) isprint((u_char)(Anychar))
28959243Sobrien#define	isspacech(Anychar) isspace((u_char)(Anychar))
29059243Sobrien#define	tolowerch(Anychar) tolower((u_char)(Anychar))
29159243Sobrien
29259243Sobrienint
29359243Sobrienmain(int argc, char **argv)
29459243Sobrien{
29559243Sobrien	struct cflist *worklist;
29659243Sobrien	struct conf_entry *p;
29759243Sobrien	struct sigwork_entry *stmp;
29859243Sobrien	struct zipwork_entry *ztmp;
29959243Sobrien
30059243Sobrien	SLIST_INIT(&swhead);
30159243Sobrien	SLIST_INIT(&zwhead);
30259243Sobrien
30359243Sobrien	parse_args(argc, argv);
30459243Sobrien	argc -= optind;
30559243Sobrien	argv += optind;
30659243Sobrien
30759243Sobrien	if (needroot && getuid() && geteuid())
30859243Sobrien		errx(1, "must have root privs");
30959243Sobrien	worklist = get_worklist(argv);
31059243Sobrien
31159243Sobrien	/*
31259243Sobrien	 * Rotate all the files which need to be rotated.  Note that
31359243Sobrien	 * some users have *hundreds* of entries in newsyslog.conf!
31459243Sobrien	 */
31559243Sobrien	while (!STAILQ_EMPTY(worklist)) {
31659243Sobrien		p = STAILQ_FIRST(worklist);
31759243Sobrien		STAILQ_REMOVE_HEAD(worklist, cf_nextp);
31859243Sobrien		if (do_entry(p) == FREE_ENT)
31959243Sobrien			free_entry(p);
32059243Sobrien	}
32159243Sobrien
32259243Sobrien	/*
32359243Sobrien	 * Send signals to any processes which need a signal to tell
32459243Sobrien	 * them to close and re-open the log file(s) we have rotated.
32559243Sobrien	 * Note that zipwork_entries include pointers to these
32659243Sobrien	 * sigwork_entry's, so we can not free the entries here.
32759243Sobrien	 */
32859243Sobrien	if (!SLIST_EMPTY(&swhead)) {
32959243Sobrien		if (noaction || verbose)
33059243Sobrien			printf("Signal all daemon process(es)...\n");
33159243Sobrien		SLIST_FOREACH(stmp, &swhead, sw_nextp)
33259243Sobrien			do_sigwork(stmp);
33359243Sobrien		if (noaction)
33459243Sobrien			printf("\tsleep 10\n");
33559243Sobrien		else {
33659243Sobrien			if (verbose)
33759243Sobrien				printf("Pause 10 seconds to allow daemon(s)"
33859243Sobrien				    " to close log file(s)\n");
33959243Sobrien			sleep(10);
34059243Sobrien		}
34159243Sobrien	}
34259243Sobrien	/*
34359243Sobrien	 * Compress all files that we're expected to compress, now
34459243Sobrien	 * that all processes should have closed the files which
34559243Sobrien	 * have been rotated.
34659243Sobrien	 */
34759243Sobrien	if (!SLIST_EMPTY(&zwhead)) {
34859243Sobrien		if (noaction || verbose)
34959243Sobrien			printf("Compress all rotated log file(s)...\n");
35059243Sobrien		while (!SLIST_EMPTY(&zwhead)) {
35159243Sobrien			ztmp = SLIST_FIRST(&zwhead);
35259243Sobrien			do_zipwork(ztmp);
35359243Sobrien			SLIST_REMOVE_HEAD(&zwhead, zw_nextp);
35459243Sobrien			free(ztmp);
35559243Sobrien		}
35659243Sobrien	}
35759243Sobrien	/* Now free all the sigwork entries. */
35859243Sobrien	while (!SLIST_EMPTY(&swhead)) {
35959243Sobrien		stmp = SLIST_FIRST(&swhead);
36059243Sobrien		SLIST_REMOVE_HEAD(&swhead, sw_nextp);
36159243Sobrien		free(stmp);
36259243Sobrien	}
36359243Sobrien
36459243Sobrien	while (wait(NULL) > 0 || errno == EINTR)
36559243Sobrien		;
36659243Sobrien	return (0);
36759243Sobrien}
36859243Sobrien
36959243Sobrienstatic struct conf_entry *
37059243Sobrieninit_entry(const char *fname, struct conf_entry *src_entry)
37159243Sobrien{
37259243Sobrien	struct conf_entry *tempwork;
37359243Sobrien
37459243Sobrien	if (verbose > 4)
37559243Sobrien		printf("\t--> [creating entry for %s]\n", fname);
37659243Sobrien
37759243Sobrien	tempwork = malloc(sizeof(struct conf_entry));
37859243Sobrien	if (tempwork == NULL)
37959243Sobrien		err(1, "malloc of conf_entry for %s", fname);
38059243Sobrien
38159243Sobrien	if (destdir == NULL || fname[0] != '/')
38259243Sobrien		tempwork->log = strdup(fname);
38359243Sobrien	else
38459243Sobrien		asprintf(&tempwork->log, "%s%s", destdir, fname);
38559243Sobrien	if (tempwork->log == NULL)
38659243Sobrien		err(1, "strdup for %s", fname);
38759243Sobrien
38859243Sobrien	if (src_entry != NULL) {
38959243Sobrien		tempwork->pid_cmd_file = NULL;
39059243Sobrien		if (src_entry->pid_cmd_file)
39159243Sobrien			tempwork->pid_cmd_file = strdup(src_entry->pid_cmd_file);
39259243Sobrien		tempwork->r_reason = NULL;
39359243Sobrien		tempwork->firstcreate = 0;
39459243Sobrien		tempwork->rotate = 0;
39559243Sobrien		tempwork->fsize = -1;
39659243Sobrien		tempwork->uid = src_entry->uid;
39759243Sobrien		tempwork->gid = src_entry->gid;
39859243Sobrien		tempwork->numlogs = src_entry->numlogs;
39959243Sobrien		tempwork->trsize = src_entry->trsize;
40059243Sobrien		tempwork->hours = src_entry->hours;
40159243Sobrien		tempwork->trim_at = NULL;
40259243Sobrien		if (src_entry->trim_at != NULL)
40359243Sobrien			tempwork->trim_at = ptime_init(src_entry->trim_at);
40459243Sobrien		tempwork->permissions = src_entry->permissions;
40559243Sobrien		tempwork->flags = src_entry->flags;
40659243Sobrien		tempwork->compress = src_entry->compress;
40759243Sobrien		tempwork->sig = src_entry->sig;
40859243Sobrien		tempwork->def_cfg = src_entry->def_cfg;
40959243Sobrien	} else {
41059243Sobrien		/* Initialize as a "do-nothing" entry */
41159243Sobrien		tempwork->pid_cmd_file = NULL;
41259243Sobrien		tempwork->r_reason = NULL;
41359243Sobrien		tempwork->firstcreate = 0;
41459243Sobrien		tempwork->rotate = 0;
41559243Sobrien		tempwork->fsize = -1;
41659243Sobrien		tempwork->uid = (uid_t)-1;
41759243Sobrien		tempwork->gid = (gid_t)-1;
41859243Sobrien		tempwork->numlogs = 1;
41959243Sobrien		tempwork->trsize = -1;
42059243Sobrien		tempwork->hours = -1;
42159243Sobrien		tempwork->trim_at = NULL;
42259243Sobrien		tempwork->permissions = 0;
42359243Sobrien		tempwork->flags = 0;
42459243Sobrien		tempwork->compress = COMPRESS_NONE;
42559243Sobrien		tempwork->sig = SIGHUP;
42659243Sobrien		tempwork->def_cfg = 0;
42759243Sobrien	}
42859243Sobrien
42959243Sobrien	return (tempwork);
43059243Sobrien}
43159243Sobrien
43259243Sobrienstatic void
43359243Sobrienfree_entry(struct conf_entry *ent)
43459243Sobrien{
43559243Sobrien
43659243Sobrien	if (ent == NULL)
43759243Sobrien		return;
43859243Sobrien
43959243Sobrien	if (ent->log != NULL) {
44059243Sobrien		if (verbose > 4)
44159243Sobrien			printf("\t--> [freeing entry for %s]\n", ent->log);
44259243Sobrien		free(ent->log);
44359243Sobrien		ent->log = NULL;
44459243Sobrien	}
44559243Sobrien
44659243Sobrien	if (ent->pid_cmd_file != NULL) {
44759243Sobrien		free(ent->pid_cmd_file);
44859243Sobrien		ent->pid_cmd_file = NULL;
44959243Sobrien	}
45059243Sobrien
45159243Sobrien	if (ent->r_reason != NULL) {
45259243Sobrien		free(ent->r_reason);
45359243Sobrien		ent->r_reason = NULL;
45459243Sobrien	}
45559243Sobrien
45659243Sobrien	if (ent->trim_at != NULL) {
45759243Sobrien		ptime_free(ent->trim_at);
45859243Sobrien		ent->trim_at = NULL;
45959243Sobrien	}
46059243Sobrien
46159243Sobrien	free(ent);
46259243Sobrien}
46359243Sobrien
46459243Sobrienstatic void
46559243Sobrienfree_clist(struct cflist *list)
46659243Sobrien{
46759243Sobrien	struct conf_entry *ent;
46859243Sobrien
46959243Sobrien	while (!STAILQ_EMPTY(list)) {
47059243Sobrien		ent = STAILQ_FIRST(list);
47159243Sobrien		STAILQ_REMOVE_HEAD(list, cf_nextp);
47259243Sobrien		free_entry(ent);
47359243Sobrien	}
47459243Sobrien
47559243Sobrien	free(list);
47659243Sobrien	list = NULL;
47759243Sobrien}
47859243Sobrien
47959243Sobrienstatic fk_entry
48059243Sobriendo_entry(struct conf_entry * ent)
48159243Sobrien{
48259243Sobrien#define	REASON_MAX	80
48359243Sobrien	int modtime;
48459243Sobrien	fk_entry free_or_keep;
48559243Sobrien	double diffsecs;
48659243Sobrien	char temp_reason[REASON_MAX];
48759243Sobrien	int oversized;
48859243Sobrien
48959243Sobrien	free_or_keep = FREE_ENT;
49059243Sobrien	if (verbose)
49159243Sobrien		printf("%s <%d%s>: ", ent->log, ent->numlogs,
49259243Sobrien		    compress_type[ent->compress].flag);
49359243Sobrien	ent->fsize = sizefile(ent->log);
49459243Sobrien	oversized = ((ent->trsize > 0) && (ent->fsize >= ent->trsize));
49559243Sobrien	modtime = age_old_log(ent->log);
49659243Sobrien	ent->rotate = 0;
49759243Sobrien	ent->firstcreate = 0;
49859243Sobrien	if (ent->fsize < 0) {
49959243Sobrien		/*
50059243Sobrien		 * If either the C flag or the -C option was specified,
50159243Sobrien		 * and if we won't be creating the file, then have the
50259243Sobrien		 * verbose message include a hint as to why the file
50359243Sobrien		 * will not be created.
50459243Sobrien		 */
50559243Sobrien		temp_reason[0] = '\0';
50659243Sobrien		if (createlogs > 1)
50759243Sobrien			ent->firstcreate = 1;
50859243Sobrien		else if ((ent->flags & CE_CREATE) && createlogs)
50959243Sobrien			ent->firstcreate = 1;
51059243Sobrien		else if (ent->flags & CE_CREATE)
51159243Sobrien			strlcpy(temp_reason, " (no -C option)", REASON_MAX);
51259243Sobrien		else if (createlogs)
51359243Sobrien			strlcpy(temp_reason, " (no C flag)", REASON_MAX);
51459243Sobrien
51559243Sobrien		if (ent->firstcreate) {
51659243Sobrien			if (verbose)
51759243Sobrien				printf("does not exist -> will create.\n");
51859243Sobrien			createlog(ent);
51959243Sobrien		} else if (verbose) {
52059243Sobrien			printf("does not exist, skipped%s.\n", temp_reason);
52159243Sobrien		}
52259243Sobrien	} else {
52359243Sobrien		if (ent->flags & CE_TRIMAT && !force && !rotatereq &&
52459243Sobrien		    !oversized) {
52559243Sobrien			diffsecs = ptimeget_diff(timenow, ent->trim_at);
52659243Sobrien			if (diffsecs < 0.0) {
52759243Sobrien				/* trim_at is some time in the future. */
52859243Sobrien				if (verbose) {
52959243Sobrien					ptime_adjust4dst(ent->trim_at,
53059243Sobrien					    timenow);
53159243Sobrien					printf("--> will trim at %s",
53259243Sobrien					    ptimeget_ctime(ent->trim_at));
53359243Sobrien				}
53459243Sobrien				return (free_or_keep);
53559243Sobrien			} else if (diffsecs >= 3600.0) {
53659243Sobrien				/*
53759243Sobrien				 * trim_at is more than an hour in the past,
53859243Sobrien				 * so find the next valid trim_at time, and
53959243Sobrien				 * tell the user what that will be.
54059243Sobrien				 */
54159243Sobrien				if (verbose && dbg_at_times)
54259243Sobrien					printf("\n\t--> prev trim at %s\t",
54359243Sobrien					    ptimeget_ctime(ent->trim_at));
54459243Sobrien				if (verbose) {
54559243Sobrien					ptimeset_nxtime(ent->trim_at);
54659243Sobrien					printf("--> will trim at %s",
54759243Sobrien					    ptimeget_ctime(ent->trim_at));
54859243Sobrien				}
54959243Sobrien				return (free_or_keep);
55059243Sobrien			} else if (verbose && noaction && dbg_at_times) {
55159243Sobrien				/*
55259243Sobrien				 * If we are just debugging at-times, then
55359243Sobrien				 * a detailed message is helpful.  Also
55459243Sobrien				 * skip "doing" any commands, since they
55559243Sobrien				 * would all be turned off by no-action.
556131962Smp				 */
55759243Sobrien				printf("\n\t--> timematch at %s",
55859243Sobrien				    ptimeget_ctime(ent->trim_at));
55959243Sobrien				return (free_or_keep);
56059243Sobrien			} else if (verbose && ent->hours <= 0) {
56159243Sobrien				printf("--> time is up\n");
56259243Sobrien			}
56359243Sobrien		}
56483098Smp		if (verbose && (ent->trsize > 0))
56583098Smp			printf("size (Kb): %d [%d] ", ent->fsize, ent->trsize);
56683098Smp		if (verbose && (ent->hours > 0))
56783098Smp			printf(" age (hr): %d [%d] ", modtime, ent->hours);
56883098Smp
56983098Smp		/*
57059243Sobrien		 * Figure out if this logfile needs to be rotated.
571167465Smp		 */
572167465Smp		temp_reason[0] = '\0';
573167465Smp		if (rotatereq) {
574167465Smp			ent->rotate = 1;
575167465Smp			snprintf(temp_reason, REASON_MAX, " due to -R from %s",
576167465Smp			    requestor);
577167465Smp		} else if (force) {
578167465Smp			ent->rotate = 1;
579167465Smp			snprintf(temp_reason, REASON_MAX, " due to -F request");
580167465Smp		} else if (oversized) {
581167465Smp			ent->rotate = 1;
582167465Smp			snprintf(temp_reason, REASON_MAX, " due to size>%dK",
583167465Smp			    ent->trsize);
584167465Smp		} else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) {
58559243Sobrien			ent->rotate = 1;
58659243Sobrien		} else if ((ent->hours > 0) && ((modtime >= ent->hours) ||
58759243Sobrien		    (modtime < 0))) {
588167465Smp			ent->rotate = 1;
58959243Sobrien		}
590167465Smp
591167465Smp		/*
59259243Sobrien		 * If the file needs to be rotated, then rotate it.
59359243Sobrien		 */
59459243Sobrien		if (ent->rotate && !norotate) {
59559243Sobrien			if (temp_reason[0] != '\0')
59659243Sobrien				ent->r_reason = strdup(temp_reason);
597167465Smp			if (verbose)
598167465Smp				printf("--> trimming log....\n");
599167465Smp			if (noaction && !verbose)
60059243Sobrien				printf("%s <%d%s>: trimming\n", ent->log,
60159243Sobrien				    ent->numlogs,
60259243Sobrien				    compress_type[ent->compress].flag);
60359243Sobrien			free_or_keep = do_rotate(ent);
60459243Sobrien		} else {
60559243Sobrien			if (verbose)
60659243Sobrien				printf("--> skipping\n");
60759243Sobrien		}
60859243Sobrien	}
60959243Sobrien	return (free_or_keep);
61059243Sobrien#undef REASON_MAX
61159243Sobrien}
61259243Sobrien
61359243Sobrienstatic void
61459243Sobrienparse_args(int argc, char **argv)
61559243Sobrien{
61659243Sobrien	int ch;
61759243Sobrien	char *p;
61859243Sobrien
61959243Sobrien	timenow = ptime_init(NULL);
620167465Smp	ptimeset_time(timenow, time(NULL));
62159243Sobrien	strlcpy(daytime, ptimeget_ctime(timenow) + 4, DAYTIME_LEN);
62259243Sobrien
62359243Sobrien	/* Let's get our hostname */
62459243Sobrien	(void)gethostname(hostname, sizeof(hostname));
62559243Sobrien
62659243Sobrien	/* Truncate domain */
62759243Sobrien	if ((p = strchr(hostname, '.')) != NULL)
62859243Sobrien		*p = '\0';
62959243Sobrien
63059243Sobrien	/* Parse command line options. */
631167465Smp	while ((ch = getopt(argc, argv, "a:d:f:nrst:vCD:FNPR:S:")) != -1)
63259243Sobrien		switch (ch) {
63359243Sobrien		case 'a':
63459243Sobrien			archtodir++;
63559243Sobrien			archdirname = optarg;
636231990Smp			break;
63759243Sobrien		case 'd':
63859243Sobrien			destdir = optarg;
63959243Sobrien			break;
64059243Sobrien		case 'f':
64159243Sobrien			conf = optarg;
64259243Sobrien			break;
643167465Smp		case 'n':
64459243Sobrien			noaction++;
64559243Sobrien			/* FALLTHROUGH */
64659243Sobrien		case 'r':
64759243Sobrien			needroot = 0;
64859243Sobrien			break;
64959243Sobrien		case 's':
65059243Sobrien			nosignal = 1;
65159243Sobrien			break;
65259243Sobrien		case 't':
65359243Sobrien			if (optarg[0] == '\0' ||
65459243Sobrien			    strcmp(optarg, "DEFAULT") == 0)
65559243Sobrien				timefnamefmt = strdup(DEFAULT_TIMEFNAME_FMT);
656167465Smp			else
65759243Sobrien				timefnamefmt = strdup(optarg);
65859243Sobrien			break;
65959243Sobrien		case 'v':
66059243Sobrien			verbose++;
66159243Sobrien			break;
66259243Sobrien		case 'C':
66359243Sobrien			/* Useful for things like rc.diskless... */
66459243Sobrien			createlogs++;
66559243Sobrien			break;
66659243Sobrien		case 'D':
66759243Sobrien			/*
66859243Sobrien			 * Set some debugging option.  The specific option
66959243Sobrien			 * depends on the value of optarg.  These options
67059243Sobrien			 * may come and go without notice or documentation.
67159243Sobrien			 */
67259243Sobrien			if (parse_doption(optarg))
67359243Sobrien				break;
67459243Sobrien			usage();
67559243Sobrien			/* NOTREACHED */
67659243Sobrien		case 'F':
67759243Sobrien			force++;
67859243Sobrien			break;
67959243Sobrien		case 'N':
68059243Sobrien			norotate++;
68159243Sobrien			break;
68259243Sobrien		case 'P':
68359243Sobrien			enforcepid++;
68459243Sobrien			break;
68559243Sobrien		case 'R':
68659243Sobrien			rotatereq++;
68759243Sobrien			requestor = strdup(optarg);
68859243Sobrien			break;
68959243Sobrien		case 'S':
69059243Sobrien			path_syslogpid = optarg;
691167465Smp			break;
69259243Sobrien		case 'm':	/* Used by OpenBSD for "monitor mode" */
69359243Sobrien		default:
69459243Sobrien			usage();
695167465Smp			/* NOTREACHED */
69659243Sobrien		}
69759243Sobrien
69859243Sobrien	if (force && norotate) {
69959243Sobrien		warnx("Only one of -F and -N may be specified.");
70059243Sobrien		usage();
70159243Sobrien		/* NOTREACHED */
70259243Sobrien	}
70359243Sobrien
70459243Sobrien	if (rotatereq) {
70559243Sobrien		if (optind == argc) {
70659243Sobrien			warnx("At least one filename must be given when -R is specified.");
70759243Sobrien			usage();
70859243Sobrien			/* NOTREACHED */
70959243Sobrien		}
71059243Sobrien		/* Make sure "requestor" value is safe for a syslog message. */
71159243Sobrien		for (p = requestor; *p != '\0'; p++) {
71259243Sobrien			if (!isprintch(*p) && (*p != '\t'))
71359243Sobrien				*p = '.';
71459243Sobrien		}
71559243Sobrien	}
71659243Sobrien
71759243Sobrien	if (dbg_timenow) {
71859243Sobrien		/*
71959243Sobrien		 * Note that the 'daytime' variable is not changed.
72059243Sobrien		 * That is only used in messages that track when a
72159243Sobrien		 * logfile is rotated, and if a file *is* rotated,
72259243Sobrien		 * then it will still rotated at the "real now" time.
72359243Sobrien		 */
72459243Sobrien		ptime_free(timenow);
72559243Sobrien		timenow = dbg_timenow;
726167465Smp		fprintf(stderr, "Debug: Running as if TimeNow is %s",
72759243Sobrien		    ptimeget_ctime(dbg_timenow));
72859243Sobrien	}
729167465Smp
73059243Sobrien}
73159243Sobrien
73259243Sobrien/*
73359243Sobrien * These debugging options are mainly meant for developer use, such
73459243Sobrien * as writing regression-tests.  They would not be needed by users
73559243Sobrien * during normal operation of newsyslog...
73659243Sobrien */
73759243Sobrienstatic int
73859243Sobrienparse_doption(const char *doption)
73959243Sobrien{
74059243Sobrien	const char TN[] = "TN=";
74159243Sobrien	int res;
74259243Sobrien
74359243Sobrien	if (strncmp(doption, TN, sizeof(TN) - 1) == 0) {
74459243Sobrien		/*
74559243Sobrien		 * The "TimeNow" debugging option.  This might be off
74659243Sobrien		 * by an hour when crossing a timezone change.
74759243Sobrien		 */
74859243Sobrien		dbg_timenow = ptime_init(NULL);
74959243Sobrien		res = ptime_relparse(dbg_timenow, PTM_PARSE_ISO8601,
75059243Sobrien		    time(NULL), doption + sizeof(TN) - 1);
75159243Sobrien		if (res == -2) {
75259243Sobrien			warnx("Non-existent time specified on -D %s", doption);
75359243Sobrien			return (0);			/* failure */
75459243Sobrien		} else if (res < 0) {
75559243Sobrien			warnx("Malformed time given on -D %s", doption);
75659243Sobrien			return (0);			/* failure */
757167465Smp		}
75859243Sobrien		return (1);			/* successfully parsed */
75959243Sobrien
76059243Sobrien	}
76159243Sobrien
76259243Sobrien	if (strcmp(doption, "ats") == 0) {
76359243Sobrien		dbg_at_times++;
76459243Sobrien		return (1);			/* successfully parsed */
76559243Sobrien	}
76659243Sobrien
76759243Sobrien	/* XXX - This check could probably be dropped. */
76859243Sobrien	if ((strcmp(doption, "neworder") == 0) || (strcmp(doption, "oldorder")
76959243Sobrien	    == 0)) {
77059243Sobrien		warnx("NOTE: newsyslog always uses 'neworder'.");
77159243Sobrien		return (1);			/* successfully parsed */
77259243Sobrien	}
77359243Sobrien
77459243Sobrien	warnx("Unknown -D (debug) option: '%s'", doption);
77559243Sobrien	return (0);				/* failure */
77659243Sobrien}
77759243Sobrien
77859243Sobrienstatic void
77959243Sobrienusage(void)
78059243Sobrien{
78159243Sobrien
78259243Sobrien	fprintf(stderr,
78359243Sobrien	    "usage: newsyslog [-CFNPnrsv] [-a directory] [-d directory] [-f config_file]\n"
78459243Sobrien	    "                 [-S pidfile] [-t timefmt] [[-R tagname] file ...]\n");
78559243Sobrien	exit(1);
78659243Sobrien}
78759243Sobrien
78859243Sobrien/*
78959243Sobrien * Parse a configuration file and return a linked list of all the logs
79059243Sobrien * which should be processed.
79159243Sobrien */
79259243Sobrienstatic struct cflist *
79359243Sobrienget_worklist(char **files)
79459243Sobrien{
79559243Sobrien	FILE *f;
79659243Sobrien	char **given;
79759243Sobrien	struct cflist *cmdlist, *filelist, *globlist;
79859243Sobrien	struct conf_entry *defconf, *dupent, *ent;
79959243Sobrien	struct ilist inclist;
80059243Sobrien	struct include_entry *inc;
80159243Sobrien	int gmatch, fnres;
80259243Sobrien
80359243Sobrien	defconf = NULL;
80459243Sobrien	STAILQ_INIT(&inclist);
80559243Sobrien
80659243Sobrien	filelist = malloc(sizeof(struct cflist));
80759243Sobrien	if (filelist == NULL)
80859243Sobrien		err(1, "malloc of filelist");
80959243Sobrien	STAILQ_INIT(filelist);
81059243Sobrien	globlist = malloc(sizeof(struct cflist));
81159243Sobrien	if (globlist == NULL)
81259243Sobrien		err(1, "malloc of globlist");
81359243Sobrien	STAILQ_INIT(globlist);
81459243Sobrien
81559243Sobrien	inc = malloc(sizeof(struct include_entry));
81659243Sobrien	if (inc == NULL)
81759243Sobrien		err(1, "malloc of inc");
81859243Sobrien	inc->file = conf;
81959243Sobrien	if (inc->file == NULL)
82059243Sobrien		inc->file = _PATH_CONF;
82159243Sobrien	STAILQ_INSERT_TAIL(&inclist, inc, inc_nextp);
82259243Sobrien
82359243Sobrien	STAILQ_FOREACH(inc, &inclist, inc_nextp) {
82459243Sobrien		if (strcmp(inc->file, "-") != 0)
82559243Sobrien			f = fopen(inc->file, "r");
82659243Sobrien		else {
82759243Sobrien			f = stdin;
82859243Sobrien			inc->file = "<stdin>";
82959243Sobrien		}
83059243Sobrien		if (!f)
83159243Sobrien			err(1, "%s", inc->file);
83259243Sobrien
83359243Sobrien		if (verbose)
83459243Sobrien			printf("Processing %s\n", inc->file);
83559243Sobrien		parse_file(f, filelist, globlist, defconf, &inclist);
83659243Sobrien		(void) fclose(f);
83759243Sobrien	}
83859243Sobrien
83959243Sobrien	/*
84059243Sobrien	 * All config-file information has been read in and turned into
84159243Sobrien	 * a filelist and a globlist.  If there were no specific files
84259243Sobrien	 * given on the run command, then the only thing left to do is to
84359243Sobrien	 * call a routine which finds all files matched by the globlist
84459243Sobrien	 * and adds them to the filelist.  Then return the worklist.
84559243Sobrien	 */
84659243Sobrien	if (*files == NULL) {
84759243Sobrien		expand_globs(filelist, globlist);
84859243Sobrien		free_clist(globlist);
84959243Sobrien		if (defconf != NULL)
85059243Sobrien			free_entry(defconf);
85159243Sobrien		return (filelist);
85259243Sobrien		/* NOTREACHED */
85359243Sobrien	}
85459243Sobrien
85559243Sobrien	/*
85659243Sobrien	 * If newsyslog was given a specific list of files to process,
85759243Sobrien	 * it may be that some of those files were not listed in any
85859243Sobrien	 * config file.  Those unlisted files should get the default
85959243Sobrien	 * rotation action.  First, create the default-rotation action
86059243Sobrien	 * if none was found in a system config file.
86159243Sobrien	 */
86259243Sobrien	if (defconf == NULL) {
86359243Sobrien		defconf = init_entry(DEFAULT_MARKER, NULL);
86459243Sobrien		defconf->numlogs = 3;
86559243Sobrien		defconf->trsize = 50;
86659243Sobrien		defconf->permissions = S_IRUSR|S_IWUSR;
86759243Sobrien	}
86859243Sobrien
86959243Sobrien	/*
87059243Sobrien	 * If newsyslog was run with a list of specific filenames,
87159243Sobrien	 * then create a new worklist which has only those files in
87259243Sobrien	 * it, picking up the rotation-rules for those files from
87359243Sobrien	 * the original filelist.
87459243Sobrien	 *
87559243Sobrien	 * XXX - Note that this will copy multiple rules for a single
87659243Sobrien	 *	logfile, if multiple entries are an exact match for
87759243Sobrien	 *	that file.  That matches the historic behavior, but do
87859243Sobrien	 *	we want to continue to allow it?  If so, it should
87959243Sobrien	 *	probably be handled more intelligently.
88059243Sobrien	 */
88159243Sobrien	cmdlist = malloc(sizeof(struct cflist));
88259243Sobrien	if (cmdlist == NULL)
88359243Sobrien		err(1, "malloc of cmdlist");
88459243Sobrien	STAILQ_INIT(cmdlist);
88559243Sobrien
88659243Sobrien	for (given = files; *given; ++given) {
88759243Sobrien		/*
88859243Sobrien		 * First try to find exact-matches for this given file.
88959243Sobrien		 */
89059243Sobrien		gmatch = 0;
89159243Sobrien		STAILQ_FOREACH(ent, filelist, cf_nextp) {
89259243Sobrien			if (strcmp(ent->log, *given) == 0) {
893167465Smp				gmatch++;
89459243Sobrien				dupent = init_entry(*given, ent);
89559243Sobrien				STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
89659243Sobrien			}
89759243Sobrien		}
89859243Sobrien		if (gmatch) {
89959243Sobrien			if (verbose > 2)
90059243Sobrien				printf("\t+ Matched entry %s\n", *given);
90159243Sobrien			continue;
90259243Sobrien		}
90359243Sobrien
90459243Sobrien		/*
90559243Sobrien		 * There was no exact-match for this given file, so look
90659243Sobrien		 * for a "glob" entry which does match.
90759243Sobrien		 */
90859243Sobrien		gmatch = 0;
90959243Sobrien		if (verbose > 2 && globlist != NULL)
91059243Sobrien			printf("\t+ Checking globs for %s\n", *given);
91159243Sobrien		STAILQ_FOREACH(ent, globlist, cf_nextp) {
91259243Sobrien			fnres = fnmatch(ent->log, *given, FNM_PATHNAME);
91359243Sobrien			if (verbose > 2)
91459243Sobrien				printf("\t+    = %d for pattern %s\n", fnres,
91559243Sobrien				    ent->log);
91659243Sobrien			if (fnres == 0) {
91759243Sobrien				gmatch++;
91859243Sobrien				dupent = init_entry(*given, ent);
91959243Sobrien				/* This new entry is not a glob! */
92059243Sobrien				dupent->flags &= ~CE_GLOB;
92159243Sobrien				STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
92259243Sobrien				/* Only allow a match to one glob-entry */
92359243Sobrien				break;
92459243Sobrien			}
92559243Sobrien		}
92659243Sobrien		if (gmatch) {
92759243Sobrien			if (verbose > 2)
92859243Sobrien				printf("\t+ Matched %s via %s\n", *given,
92959243Sobrien				    ent->log);
93059243Sobrien			continue;
93159243Sobrien		}
93259243Sobrien
93359243Sobrien		/*
93459243Sobrien		 * This given file was not found in any config file, so
93559243Sobrien		 * add a worklist item based on the default entry.
93659243Sobrien		 */
93759243Sobrien		if (verbose > 2)
93859243Sobrien			printf("\t+ No entry matched %s  (will use %s)\n",
93959243Sobrien			    *given, DEFAULT_MARKER);
94059243Sobrien		dupent = init_entry(*given, defconf);
94159243Sobrien		/* Mark that it was *not* found in a config file */
94259243Sobrien		dupent->def_cfg = 1;
94359243Sobrien		STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
94459243Sobrien	}
94559243Sobrien
94659243Sobrien	/*
94759243Sobrien	 * Free all the entries in the original work list, the list of
94859243Sobrien	 * glob entries, and the default entry.
94959243Sobrien	 */
95059243Sobrien	free_clist(filelist);
95159243Sobrien	free_clist(globlist);
95259243Sobrien	free_entry(defconf);
95359243Sobrien
95459243Sobrien	/* And finally, return a worklist which matches the given files. */
95559243Sobrien	return (cmdlist);
95659243Sobrien}
95759243Sobrien
95859243Sobrien/*
95959243Sobrien * Expand the list of entries with filename patterns, and add all files
96059243Sobrien * which match those glob-entries onto the worklist.
96159243Sobrien */
96259243Sobrienstatic void
96359243Sobrienexpand_globs(struct cflist *work_p, struct cflist *glob_p)
96459243Sobrien{
96559243Sobrien	int gmatch, gres;
96659243Sobrien	size_t i;
96759243Sobrien	char *mfname;
96859243Sobrien	struct conf_entry *dupent, *ent, *globent;
96959243Sobrien	glob_t pglob;
97059243Sobrien	struct stat st_fm;
97159243Sobrien
97259243Sobrien	/*
97359243Sobrien	 * The worklist contains all fully-specified (non-GLOB) names.
97459243Sobrien	 *
97559243Sobrien	 * Now expand the list of filename-pattern (GLOB) entries into
97659243Sobrien	 * a second list, which (by definition) will only match files
97759243Sobrien	 * that already exist.  Do not add a glob-related entry for any
97859243Sobrien	 * file which already exists in the fully-specified list.
97959243Sobrien	 */
98059243Sobrien	STAILQ_FOREACH(globent, glob_p, cf_nextp) {
98159243Sobrien		gres = glob(globent->log, GLOB_NOCHECK, NULL, &pglob);
98259243Sobrien		if (gres != 0) {
98359243Sobrien			warn("cannot expand pattern (%d): %s", gres,
98459243Sobrien			    globent->log);
98559243Sobrien			continue;
98659243Sobrien		}
98759243Sobrien
98859243Sobrien		if (verbose > 2)
98959243Sobrien			printf("\t+ Expanding pattern %s\n", globent->log);
99059243Sobrien		for (i = 0; i < pglob.gl_matchc; i++) {
99159243Sobrien			mfname = pglob.gl_pathv[i];
99259243Sobrien
99359243Sobrien			/* See if this file already has a specific entry. */
99459243Sobrien			gmatch = 0;
99559243Sobrien			STAILQ_FOREACH(ent, work_p, cf_nextp) {
99659243Sobrien				if (strcmp(mfname, ent->log) == 0) {
99759243Sobrien					gmatch++;
99859243Sobrien					break;
99959243Sobrien				}
100059243Sobrien			}
100159243Sobrien			if (gmatch)
100259243Sobrien				continue;
100359243Sobrien
100459243Sobrien			/* Make sure the named matched is a file. */
100559243Sobrien			gres = lstat(mfname, &st_fm);
100659243Sobrien			if (gres != 0) {
100759243Sobrien				/* Error on a file that glob() matched?!? */
100859243Sobrien				warn("Skipping %s - lstat() error", mfname);
100959243Sobrien				continue;
101059243Sobrien			}
101159243Sobrien			if (!S_ISREG(st_fm.st_mode)) {
101259243Sobrien				/* We only rotate files! */
101359243Sobrien				if (verbose > 2)
101459243Sobrien					printf("\t+  . skipping %s (!file)\n",
101559243Sobrien					    mfname);
101659243Sobrien				continue;
101759243Sobrien			}
101859243Sobrien
101959243Sobrien			if (verbose > 2)
102059243Sobrien				printf("\t+  . add file %s\n", mfname);
102159243Sobrien			dupent = init_entry(mfname, globent);
102259243Sobrien			/* This new entry is not a glob! */
102359243Sobrien			dupent->flags &= ~CE_GLOB;
102459243Sobrien
102559243Sobrien			/* Add to the worklist. */
102659243Sobrien			STAILQ_INSERT_TAIL(work_p, dupent, cf_nextp);
102759243Sobrien		}
102859243Sobrien		globfree(&pglob);
102959243Sobrien		if (verbose > 2)
1030167465Smp			printf("\t+ Done with pattern %s\n", globent->log);
103159243Sobrien	}
103259243Sobrien}
103359243Sobrien
103459243Sobrien/*
103559243Sobrien * Parse a configuration file and update a linked list of all the logs to
103659243Sobrien * process.
103759243Sobrien */
103859243Sobrienstatic void
103959243Sobrienparse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
104059243Sobrien    struct conf_entry *defconf_p, struct ilist *inclist)
104159243Sobrien{
104259243Sobrien	char line[BUFSIZ], *parse, *q;
104359243Sobrien	char *cp, *errline, *group;
104459243Sobrien	struct conf_entry *working;
104559243Sobrien	struct passwd *pwd;
104659243Sobrien	struct group *grp;
104759243Sobrien	glob_t pglob;
104859243Sobrien	int eol, ptm_opts, res, special;
104959243Sobrien	size_t i;
105059243Sobrien
105159243Sobrien	errline = NULL;
105259243Sobrien	while (fgets(line, BUFSIZ, cf)) {
1053167465Smp		if ((line[0] == '\n') || (line[0] == '#') ||
105459243Sobrien		    (strlen(line) == 0))
105559243Sobrien			continue;
105659243Sobrien		if (errline != NULL)
105759243Sobrien			free(errline);
105859243Sobrien		errline = strdup(line);
105959243Sobrien		for (cp = line + 1; *cp != '\0'; cp++) {
106059243Sobrien			if (*cp != '#')
106159243Sobrien				continue;
106259243Sobrien			if (*(cp - 1) == '\\') {
1063167465Smp				strcpy(cp - 1, cp);
106459243Sobrien				cp--;
106559243Sobrien				continue;
106659243Sobrien			}
106759243Sobrien			*cp = '\0';
106859243Sobrien			break;
106959243Sobrien		}
107059243Sobrien
107159243Sobrien		q = parse = missing_field(sob(line), errline);
107259243Sobrien		parse = son(line);
1073167465Smp		if (!*parse)
107459243Sobrien			errx(1, "malformed line (missing fields):\n%s",
107559243Sobrien			    errline);
107659243Sobrien		*parse = '\0';
107759243Sobrien
107859243Sobrien		/*
107959243Sobrien		 * Allow people to set debug options via the config file.
108059243Sobrien		 * (NOTE: debug options are undocumented, and may disappear
108159243Sobrien		 * at any time, etc).
108259243Sobrien		 */
108359243Sobrien		if (strcasecmp(DEBUG_MARKER, q) == 0) {
1084167465Smp			q = parse = missing_field(sob(++parse), errline);
108559243Sobrien			parse = son(parse);
1086145479Smp			if (!*parse)
108759243Sobrien				warnx("debug line specifies no option:\n%s",
108859243Sobrien				    errline);
108959243Sobrien			else {
109059243Sobrien				*parse = '\0';
109159243Sobrien				parse_doption(q);
109259243Sobrien			}
109359243Sobrien			continue;
109459243Sobrien		} else if (strcasecmp(INCLUDE_MARKER, q) == 0) {
109559243Sobrien			if (verbose)
109659243Sobrien				printf("Found: %s", errline);
109759243Sobrien			q = parse = missing_field(sob(++parse), errline);
109859243Sobrien			parse = son(parse);
109959243Sobrien			if (!*parse) {
110059243Sobrien				warnx("include line missing argument:\n%s",
110159243Sobrien				    errline);
110259243Sobrien				continue;
110359243Sobrien			}
110459243Sobrien
110559243Sobrien			*parse = '\0';
110659243Sobrien
110759243Sobrien			if (isglobstr(q)) {
110859243Sobrien				res = glob(q, GLOB_NOCHECK, NULL, &pglob);
110959243Sobrien				if (res != 0) {
111059243Sobrien					warn("cannot expand pattern (%d): %s",
111159243Sobrien					    res, q);
111259243Sobrien					continue;
111359243Sobrien				}
111459243Sobrien
111559243Sobrien				if (verbose > 2)
111659243Sobrien					printf("\t+ Expanding pattern %s\n", q);
111759243Sobrien
1118167465Smp				for (i = 0; i < pglob.gl_matchc; i++)
111959243Sobrien					add_to_queue(pglob.gl_pathv[i],
112059243Sobrien					    inclist);
112159243Sobrien				globfree(&pglob);
112259243Sobrien			} else
112359243Sobrien				add_to_queue(q, inclist);
112459243Sobrien			continue;
112559243Sobrien		}
112659243Sobrien
112759243Sobrien		special = 0;
112859243Sobrien		working = init_entry(q, NULL);
112959243Sobrien		if (strcasecmp(DEFAULT_MARKER, q) == 0) {
113059243Sobrien			special = 1;
113159243Sobrien			if (defconf_p != NULL) {
113259243Sobrien				warnx("Ignoring duplicate entry for %s!", q);
113359243Sobrien				free_entry(working);
113459243Sobrien				continue;
113569408Sache			}
113659243Sobrien			defconf_p = working;
1137167465Smp		}
113859243Sobrien
113959243Sobrien		q = parse = missing_field(sob(++parse), errline);
114059243Sobrien		parse = son(parse);
114169408Sache		if (!*parse)
1142			errx(1, "malformed line (missing fields):\n%s",
1143			    errline);
1144		*parse = '\0';
1145		if ((group = strchr(q, ':')) != NULL ||
1146		    (group = strrchr(q, '.')) != NULL) {
1147			*group++ = '\0';
1148			if (*q) {
1149				if (!(isnumberstr(q))) {
1150					if ((pwd = getpwnam(q)) == NULL)
1151						errx(1,
1152				     "error in config file; unknown user:\n%s",
1153						    errline);
1154					working->uid = pwd->pw_uid;
1155				} else
1156					working->uid = atoi(q);
1157			} else
1158				working->uid = (uid_t)-1;
1159
1160			q = group;
1161			if (*q) {
1162				if (!(isnumberstr(q))) {
1163					if ((grp = getgrnam(q)) == NULL)
1164						errx(1,
1165				    "error in config file; unknown group:\n%s",
1166						    errline);
1167					working->gid = grp->gr_gid;
1168				} else
1169					working->gid = atoi(q);
1170			} else
1171				working->gid = (gid_t)-1;
1172
1173			q = parse = missing_field(sob(++parse), errline);
1174			parse = son(parse);
1175			if (!*parse)
1176				errx(1, "malformed line (missing fields):\n%s",
1177				    errline);
1178			*parse = '\0';
1179		} else {
1180			working->uid = (uid_t)-1;
1181			working->gid = (gid_t)-1;
1182		}
1183
1184		if (!sscanf(q, "%o", &working->permissions))
1185			errx(1, "error in config file; bad permissions:\n%s",
1186			    errline);
1187
1188		q = parse = missing_field(sob(++parse), errline);
1189		parse = son(parse);
1190		if (!*parse)
1191			errx(1, "malformed line (missing fields):\n%s",
1192			    errline);
1193		*parse = '\0';
1194		if (!sscanf(q, "%d", &working->numlogs) || working->numlogs < 0)
1195			errx(1, "error in config file; bad value for count of logs to save:\n%s",
1196			    errline);
1197
1198		q = parse = missing_field(sob(++parse), errline);
1199		parse = son(parse);
1200		if (!*parse)
1201			errx(1, "malformed line (missing fields):\n%s",
1202			    errline);
1203		*parse = '\0';
1204		if (isdigitch(*q))
1205			working->trsize = atoi(q);
1206		else if (strcmp(q, "*") == 0)
1207			working->trsize = -1;
1208		else {
1209			warnx("Invalid value of '%s' for 'size' in line:\n%s",
1210			    q, errline);
1211			working->trsize = -1;
1212		}
1213
1214		working->flags = 0;
1215		working->compress = COMPRESS_NONE;
1216		q = parse = missing_field(sob(++parse), errline);
1217		parse = son(parse);
1218		eol = !*parse;
1219		*parse = '\0';
1220		{
1221			char *ep;
1222			u_long ul;
1223
1224			ul = strtoul(q, &ep, 10);
1225			if (ep == q)
1226				working->hours = 0;
1227			else if (*ep == '*')
1228				working->hours = -1;
1229			else if (ul > INT_MAX)
1230				errx(1, "interval is too large:\n%s", errline);
1231			else
1232				working->hours = ul;
1233
1234			if (*ep == '\0' || strcmp(ep, "*") == 0)
1235				goto no_trimat;
1236			if (*ep != '@' && *ep != '$')
1237				errx(1, "malformed interval/at:\n%s", errline);
1238
1239			working->flags |= CE_TRIMAT;
1240			working->trim_at = ptime_init(NULL);
1241			ptm_opts = PTM_PARSE_ISO8601;
1242			if (*ep == '$')
1243				ptm_opts = PTM_PARSE_DWM;
1244			ptm_opts |= PTM_PARSE_MATCHDOM;
1245			res = ptime_relparse(working->trim_at, ptm_opts,
1246			    ptimeget_secs(timenow), ep + 1);
1247			if (res == -2)
1248				errx(1, "nonexistent time for 'at' value:\n%s",
1249				    errline);
1250			else if (res < 0)
1251				errx(1, "malformed 'at' value:\n%s", errline);
1252		}
1253no_trimat:
1254
1255		if (eol)
1256			q = NULL;
1257		else {
1258			q = parse = sob(++parse);	/* Optional field */
1259			parse = son(parse);
1260			if (!*parse)
1261				eol = 1;
1262			*parse = '\0';
1263		}
1264
1265		for (; q && *q && !isspacech(*q); q++) {
1266			switch (tolowerch(*q)) {
1267			case 'b':
1268				working->flags |= CE_BINARY;
1269				break;
1270			case 'c':
1271				/*
1272				 * XXX - 	Ick! Ugly! Remove ASAP!
1273				 * We want `c' and `C' for "create".  But we
1274				 * will temporarily treat `c' as `g', because
1275				 * FreeBSD releases <= 4.8 have a typo of
1276				 * checking  ('G' || 'c')  for CE_GLOB.
1277				 */
1278				if (*q == 'c') {
1279					warnx("Assuming 'g' for 'c' in flags for line:\n%s",
1280					    errline);
1281					warnx("The 'c' flag will eventually mean 'CREATE'");
1282					working->flags |= CE_GLOB;
1283					break;
1284				}
1285				working->flags |= CE_CREATE;
1286				break;
1287			case 'd':
1288				working->flags |= CE_NODUMP;
1289				break;
1290			case 'g':
1291				working->flags |= CE_GLOB;
1292				break;
1293			case 'j':
1294				working->compress = COMPRESS_BZIP2;
1295				break;
1296			case 'n':
1297				working->flags |= CE_NOSIGNAL;
1298				break;
1299			case 'r':
1300				working->flags |= CE_PID2CMD;
1301				break;
1302			case 'u':
1303				working->flags |= CE_SIGNALGROUP;
1304				break;
1305			case 'w':
1306				/* Depreciated flag - keep for compatibility purposes */
1307				break;
1308			case 'x':
1309				working->compress = COMPRESS_XZ;
1310				break;
1311			case 'z':
1312				working->compress = COMPRESS_GZIP;
1313				break;
1314			case '-':
1315				break;
1316			case 'f':	/* Used by OpenBSD for "CE_FOLLOW" */
1317			case 'm':	/* Used by OpenBSD for "CE_MONITOR" */
1318			case 'p':	/* Used by NetBSD  for "CE_PLAIN0" */
1319			default:
1320				errx(1, "illegal flag in config file -- %c",
1321				    *q);
1322			}
1323		}
1324
1325		if (eol)
1326			q = NULL;
1327		else {
1328			q = parse = sob(++parse);	/* Optional field */
1329			parse = son(parse);
1330			if (!*parse)
1331				eol = 1;
1332			*parse = '\0';
1333		}
1334
1335		working->pid_cmd_file = NULL;
1336		if (q && *q) {
1337			if (*q == '/')
1338				working->pid_cmd_file = strdup(q);
1339			else if (isdigit(*q))
1340				goto got_sig;
1341			else
1342				errx(1,
1343			"illegal pid file or signal number in config file:\n%s",
1344				    errline);
1345		}
1346		if (eol)
1347			q = NULL;
1348		else {
1349			q = parse = sob(++parse);	/* Optional field */
1350			*(parse = son(parse)) = '\0';
1351		}
1352
1353		working->sig = SIGHUP;
1354		if (q && *q) {
1355			if (isdigit(*q)) {
1356		got_sig:
1357				working->sig = atoi(q);
1358			} else {
1359		err_sig:
1360				errx(1,
1361				    "illegal signal number in config file:\n%s",
1362				    errline);
1363			}
1364			if (working->sig < 1 || working->sig >= NSIG)
1365				goto err_sig;
1366		}
1367
1368		/*
1369		 * Finish figuring out what pid-file to use (if any) in
1370		 * later processing if this logfile needs to be rotated.
1371		 */
1372		if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) {
1373			/*
1374			 * This config-entry specified 'n' for nosignal,
1375			 * see if it also specified an explicit pid_cmd_file.
1376			 * This would be a pretty pointless combination.
1377			 */
1378			if (working->pid_cmd_file != NULL) {
1379				warnx("Ignoring '%s' because flag 'n' was specified in line:\n%s",
1380				    working->pid_cmd_file, errline);
1381				free(working->pid_cmd_file);
1382				working->pid_cmd_file = NULL;
1383			}
1384		} else if (working->pid_cmd_file == NULL) {
1385			/*
1386			 * This entry did not specify the 'n' flag, which
1387			 * means it should signal syslogd unless it had
1388			 * specified some other pid-file (and obviously the
1389			 * syslog pid-file will not be for a process-group).
1390			 * Also, we should only try to notify syslog if we
1391			 * are root.
1392			 */
1393			if (working->flags & CE_SIGNALGROUP) {
1394				warnx("Ignoring flag 'U' in line:\n%s",
1395				    errline);
1396				working->flags &= ~CE_SIGNALGROUP;
1397			}
1398			if (needroot)
1399				working->pid_cmd_file = strdup(path_syslogpid);
1400		}
1401
1402		/*
1403		 * Add this entry to the appropriate list of entries, unless
1404		 * it was some kind of special entry (eg: <default>).
1405		 */
1406		if (special) {
1407			;			/* Do not add to any list */
1408		} else if (working->flags & CE_GLOB) {
1409			STAILQ_INSERT_TAIL(glob_p, working, cf_nextp);
1410		} else {
1411			STAILQ_INSERT_TAIL(work_p, working, cf_nextp);
1412		}
1413	}
1414	if (errline != NULL)
1415		free(errline);
1416}
1417
1418static char *
1419missing_field(char *p, char *errline)
1420{
1421
1422	if (!p || !*p)
1423		errx(1, "missing field in config file:\n%s", errline);
1424	return (p);
1425}
1426
1427/*
1428 * In our sort we return it in the reverse of what qsort normally
1429 * would do, as we want the newest files first.  If we have two
1430 * entries with the same time we don't really care about order.
1431 *
1432 * Support function for qsort() in delete_oldest_timelog().
1433 */
1434static int
1435oldlog_entry_compare(const void *a, const void *b)
1436{
1437	const struct oldlog_entry *ola = a, *olb = b;
1438
1439	if (ola->t > olb->t)
1440		return (-1);
1441	else if (ola->t < olb->t)
1442		return (1);
1443	else
1444		return (0);
1445}
1446
1447/*
1448 * Delete the oldest logfiles, when using time based filenames.
1449 */
1450static void
1451delete_oldest_timelog(const struct conf_entry *ent, const char *archive_dir)
1452{
1453	char *logfname, *s, *dir, errbuf[80];
1454	int dirfd, i, logcnt, max_logcnt, valid;
1455	struct oldlog_entry *oldlogs;
1456	size_t logfname_len;
1457	struct dirent *dp;
1458	const char *cdir;
1459	struct tm tm;
1460	DIR *dirp;
1461	int c;
1462
1463	oldlogs = malloc(MAX_OLDLOGS * sizeof(struct oldlog_entry));
1464	max_logcnt = MAX_OLDLOGS;
1465	logcnt = 0;
1466
1467	if (archive_dir != NULL && archive_dir[0] != '\0')
1468		cdir = archive_dir;
1469	else
1470		if ((cdir = dirname(ent->log)) == NULL)
1471			err(1, "dirname()");
1472	if ((dir = strdup(cdir)) == NULL)
1473		err(1, "strdup()");
1474
1475	if ((s = basename(ent->log)) == NULL)
1476		err(1, "basename()");
1477	if ((logfname = strdup(s)) == NULL)
1478		err(1, "strdup()");
1479	logfname_len = strlen(logfname);
1480	if (strcmp(logfname, "/") == 0)
1481		errx(1, "Invalid log filename - became '/'");
1482
1483	if (verbose > 2)
1484		printf("Searching for old logs in %s\n", dir);
1485
1486	/* First we create a 'list' of all archived logfiles */
1487	if ((dirp = opendir(dir)) == NULL)
1488		err(1, "Cannot open log directory '%s'", dir);
1489	dirfd = dirfd(dirp);
1490	while ((dp = readdir(dirp)) != NULL) {
1491		if (dp->d_type != DT_REG)
1492			continue;
1493
1494		/* Ignore everything but files with our logfile prefix */
1495		if (strncmp(dp->d_name, logfname, logfname_len) != 0)
1496			continue;
1497		/* Ignore the actual non-rotated logfile */
1498		if (dp->d_namlen == logfname_len)
1499			continue;
1500		/*
1501		 * Make sure we created have found a logfile, so the
1502		 * postfix is valid, IE format is: '.<time>(.[bg]z)?'.
1503		 */
1504		if (dp->d_name[logfname_len] != '.') {
1505			if (verbose)
1506				printf("Ignoring %s which has unexpected "
1507				    "extension '%s'\n", dp->d_name,
1508				    &dp->d_name[logfname_len]);
1509			continue;
1510		}
1511		if ((s = strptime(&dp->d_name[logfname_len + 1],
1512			    timefnamefmt, &tm)) == NULL) {
1513			/*
1514			 * We could special case "old" sequentially
1515			 * named logfiles here, but we do not as that
1516			 * would require special handling to decide
1517			 * which one was the oldest compared to "new"
1518			 * time based logfiles.
1519			 */
1520			if (verbose)
1521				printf("Ignoring %s which does not "
1522				    "match time format\n", dp->d_name);
1523			continue;
1524		}
1525
1526		for (c = 0; c < COMPRESS_TYPES; c++)
1527			if (strcmp(s, compress_type[c].suffix) == 0)
1528				valid = 1;
1529		if (valid != 1) {
1530			if (verbose)
1531				printf("Ignoring %s which has unexpected "
1532				    "extension '%s'\n", dp->d_name, s);
1533			continue;
1534		}
1535
1536		/*
1537		 * We should now have old an old rotated logfile, so
1538		 * add it to the 'list'.
1539		 */
1540		if ((oldlogs[logcnt].t = timegm(&tm)) == -1)
1541			err(1, "Could not convert time string to time value");
1542		if ((oldlogs[logcnt].fname = strdup(dp->d_name)) == NULL)
1543			err(1, "strdup()");
1544		logcnt++;
1545
1546		/*
1547		 * It is very unlikely we ever run out of space in the
1548		 * logfile array from the default size, but lets
1549		 * handle it anyway...
1550		 */
1551		if (logcnt >= max_logcnt) {
1552			max_logcnt *= 4;
1553			/* Detect integer overflow */
1554			if (max_logcnt < logcnt)
1555				errx(1, "Too many old logfiles found");
1556			oldlogs = realloc(oldlogs,
1557			    max_logcnt * sizeof(struct oldlog_entry));
1558			if (oldlogs == NULL)
1559				err(1, "realloc()");
1560		}
1561	}
1562
1563	/* Second, if needed we delete oldest archived logfiles */
1564	if (logcnt > 0 && logcnt >= ent->numlogs && ent->numlogs > 1) {
1565		oldlogs = realloc(oldlogs, logcnt *
1566		    sizeof(struct oldlog_entry));
1567		if (oldlogs == NULL)
1568			err(1, "realloc()");
1569
1570		/*
1571		 * We now sort the logs in the order of newest to
1572		 * oldest.  That way we can simply skip over the
1573		 * number of records we want to keep.
1574		 */
1575		qsort(oldlogs, logcnt, sizeof(struct oldlog_entry),
1576		    oldlog_entry_compare);
1577		for (i = ent->numlogs - 1; i < logcnt; i++) {
1578			if (noaction)
1579				printf("\trm -f %s/%s\n", dir,
1580				    oldlogs[i].fname);
1581			else if (unlinkat(dirfd, oldlogs[i].fname, 0) != 0) {
1582				snprintf(errbuf, sizeof(errbuf),
1583				    "Could not delete old logfile '%s'",
1584				    oldlogs[i].fname);
1585				perror(errbuf);
1586			}
1587		}
1588	} else if (verbose > 1)
1589		printf("No old logs to delete for logfile %s\n", ent->log);
1590
1591	/* Third, cleanup */
1592	closedir(dirp);
1593	for (i = 0; i < logcnt; i++) {
1594		assert(oldlogs[i].fname != NULL);
1595		free(oldlogs[i].fname);
1596	}
1597	free(oldlogs);
1598	free(logfname);
1599	free(dir);
1600}
1601
1602/*
1603 * Generate a log filename, when using clasic filenames.
1604 */
1605static void
1606gen_clasiclog_fname(char *fname, size_t fname_sz, const char *archive_dir,
1607    const char *namepart, int numlogs_c)
1608{
1609
1610	if (archive_dir[0] != '\0')
1611		(void) snprintf(fname, fname_sz, "%s/%s.%d", archive_dir,
1612		    namepart, numlogs_c);
1613	else
1614		(void) snprintf(fname, fname_sz, "%s.%d", namepart, numlogs_c);
1615}
1616
1617/*
1618 * Delete a rotated logfiles, when using clasic filenames.
1619 */
1620static void
1621delete_clasiclog(const char *archive_dir, const char *namepart, int numlog_c)
1622{
1623	char file1[MAXPATHLEN], zfile1[MAXPATHLEN];
1624	int c;
1625
1626	gen_clasiclog_fname(file1, sizeof(file1), archive_dir, namepart,
1627	    numlog_c);
1628
1629	for (c = 0; c < COMPRESS_TYPES; c++) {
1630		(void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1631		    compress_type[c].suffix);
1632		if (noaction)
1633			printf("\trm -f %s\n", zfile1);
1634		else
1635			(void) unlink(zfile1);
1636	}
1637}
1638
1639/*
1640 * Only add to the queue if the file hasn't already been added. This is
1641 * done to prevent circular include loops.
1642 */
1643static void
1644add_to_queue(const char *fname, struct ilist *inclist)
1645{
1646	struct include_entry *inc;
1647
1648	STAILQ_FOREACH(inc, inclist, inc_nextp) {
1649		if (strcmp(fname, inc->file) == 0) {
1650			warnx("duplicate include detected: %s", fname);
1651			return;
1652		}
1653	}
1654
1655	inc = malloc(sizeof(struct include_entry));
1656	if (inc == NULL)
1657		err(1, "malloc of inc");
1658	inc->file = strdup(fname);
1659
1660	if (verbose > 2)
1661		printf("\t+ Adding %s to the processing queue.\n", fname);
1662
1663	STAILQ_INSERT_TAIL(inclist, inc, inc_nextp);
1664}
1665
1666/*
1667 * Search for logfile and return its compression suffix (if supported)
1668 * The suffix detection is first-match in the order of compress_types
1669 *
1670 * Note: if logfile without suffix exists (uncompressed, COMPRESS_NONE)
1671 * a zero-length string is returned
1672 */
1673static const char *
1674get_logfile_suffix(const char *logfile)
1675{
1676	struct stat st;
1677	char zfile[MAXPATHLEN];
1678	int c;
1679
1680	for (c = 0; c < COMPRESS_TYPES; c++) {
1681		(void) strlcpy(zfile, logfile, MAXPATHLEN);
1682		(void) strlcat(zfile, compress_type[c].suffix, MAXPATHLEN);
1683		if (lstat(zfile, &st) == 0)
1684			return (compress_type[c].suffix);
1685	}
1686	return (NULL);
1687}
1688
1689static fk_entry
1690do_rotate(const struct conf_entry *ent)
1691{
1692	char dirpart[MAXPATHLEN], namepart[MAXPATHLEN];
1693	char file1[MAXPATHLEN], file2[MAXPATHLEN];
1694	char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN];
1695	const char *logfile_suffix;
1696	char datetimestr[30];
1697	int flags, numlogs_c;
1698	fk_entry free_or_keep;
1699	struct sigwork_entry *swork;
1700	struct stat st;
1701	struct tm tm;
1702	time_t now;
1703
1704	flags = ent->flags;
1705	free_or_keep = FREE_ENT;
1706
1707	if (archtodir) {
1708		char *p;
1709
1710		/* build complete name of archive directory into dirpart */
1711		if (*archdirname == '/') {	/* absolute */
1712			strlcpy(dirpart, archdirname, sizeof(dirpart));
1713		} else {	/* relative */
1714			/* get directory part of logfile */
1715			strlcpy(dirpart, ent->log, sizeof(dirpart));
1716			if ((p = rindex(dirpart, '/')) == NULL)
1717				dirpart[0] = '\0';
1718			else
1719				*(p + 1) = '\0';
1720			strlcat(dirpart, archdirname, sizeof(dirpart));
1721		}
1722
1723		/* check if archive directory exists, if not, create it */
1724		if (lstat(dirpart, &st))
1725			createdir(ent, dirpart);
1726
1727		/* get filename part of logfile */
1728		if ((p = rindex(ent->log, '/')) == NULL)
1729			strlcpy(namepart, ent->log, sizeof(namepart));
1730		else
1731			strlcpy(namepart, p + 1, sizeof(namepart));
1732	} else {
1733		/*
1734		 * Tell utility functions we are not using an archive
1735		 * dir.
1736		 */
1737		dirpart[0] = '\0';
1738		strlcpy(namepart, ent->log, sizeof(namepart));
1739	}
1740
1741	/* Delete old logs */
1742	if (timefnamefmt != NULL)
1743		delete_oldest_timelog(ent, dirpart);
1744	else {
1745		/*
1746		 * Handle cleaning up after legacy newsyslog where we
1747		 * kept ent->numlogs + 1 files.  This code can go away
1748		 * at some point in the future.
1749		 */
1750		delete_clasiclog(dirpart, namepart, ent->numlogs);
1751
1752		if (ent->numlogs > 0)
1753			delete_clasiclog(dirpart, namepart, ent->numlogs - 1);
1754
1755	}
1756
1757	if (timefnamefmt != NULL) {
1758		/* If time functions fails we can't really do any sensible */
1759		if (time(&now) == (time_t)-1 ||
1760		    localtime_r(&now, &tm) == NULL)
1761			bzero(&tm, sizeof(tm));
1762
1763		strftime(datetimestr, sizeof(datetimestr), timefnamefmt, &tm);
1764		if (archtodir)
1765			(void) snprintf(file1, sizeof(file1), "%s/%s.%s",
1766			    dirpart, namepart, datetimestr);
1767		else
1768			(void) snprintf(file1, sizeof(file1), "%s.%s",
1769			    ent->log, datetimestr);
1770
1771		/* Don't run the code to move down logs */
1772		numlogs_c = -1;
1773	} else {
1774		gen_clasiclog_fname(file1, sizeof(file1), dirpart, namepart,
1775		    ent->numlogs - 1);
1776		numlogs_c = ent->numlogs - 2;		/* copy for countdown */
1777	}
1778
1779	/* Move down log files */
1780	for (; numlogs_c >= 0; numlogs_c--) {
1781		(void) strlcpy(file2, file1, sizeof(file2));
1782
1783		gen_clasiclog_fname(file1, sizeof(file1), dirpart, namepart,
1784		    numlogs_c);
1785
1786		logfile_suffix = get_logfile_suffix(file1);
1787		if (logfile_suffix == NULL)
1788			continue;
1789		(void) strlcpy(zfile1, file1, MAXPATHLEN);
1790		(void) strlcpy(zfile2, file2, MAXPATHLEN);
1791		(void) strlcat(zfile1, logfile_suffix, MAXPATHLEN);
1792		(void) strlcat(zfile2, logfile_suffix, MAXPATHLEN);
1793
1794		if (noaction)
1795			printf("\tmv %s %s\n", zfile1, zfile2);
1796		else {
1797			/* XXX - Ought to be checking for failure! */
1798			(void)rename(zfile1, zfile2);
1799		}
1800		change_attrs(zfile2, ent);
1801	}
1802
1803	if (ent->numlogs > 0) {
1804		if (noaction) {
1805			/*
1806			 * Note that savelog() may succeed with using link()
1807			 * for the archtodir case, but there is no good way
1808			 * of knowing if it will when doing "noaction", so
1809			 * here we claim that it will have to do a copy...
1810			 */
1811			if (archtodir)
1812				printf("\tcp %s %s\n", ent->log, file1);
1813			else
1814				printf("\tln %s %s\n", ent->log, file1);
1815			printf("\ttouch %s\t\t"
1816			    "# Update mtime for 'when'-interval processing\n",
1817			    file1);
1818		} else {
1819			if (!(flags & CE_BINARY)) {
1820				/* Report the trimming to the old log */
1821				log_trim(ent->log, ent);
1822			}
1823			savelog(ent->log, file1);
1824			/*
1825			 * Interval-based rotations are done using the mtime of
1826			 * the most recently archived log, so make sure it gets
1827			 * updated during a rotation.
1828			 */
1829			utimes(file1, NULL);
1830		}
1831		change_attrs(file1, ent);
1832	}
1833
1834	/* Create the new log file and move it into place */
1835	if (noaction)
1836		printf("Start new log...\n");
1837	createlog(ent);
1838
1839	/*
1840	 * Save all signalling and file-compression to be done after log
1841	 * files from all entries have been rotated.  This way any one
1842	 * process will not be sent the same signal multiple times when
1843	 * multiple log files had to be rotated.
1844	 */
1845	swork = NULL;
1846	if (ent->pid_cmd_file != NULL)
1847		swork = save_sigwork(ent);
1848	if (ent->numlogs > 0 && ent->compress > COMPRESS_NONE) {
1849		/*
1850		 * The zipwork_entry will include a pointer to this
1851		 * conf_entry, so the conf_entry should not be freed.
1852		 */
1853		free_or_keep = KEEP_ENT;
1854		save_zipwork(ent, swork, ent->fsize, file1);
1855	}
1856
1857	return (free_or_keep);
1858}
1859
1860static void
1861do_sigwork(struct sigwork_entry *swork)
1862{
1863	struct sigwork_entry *nextsig;
1864	int kres, secs;
1865	char *tmp;
1866
1867	if (swork->sw_runcmd == 0 && (!(swork->sw_pidok) || swork->sw_pid == 0))
1868		return;			/* no work to do... */
1869
1870	/*
1871	 * If nosignal (-s) was specified, then do not signal any process.
1872	 * Note that a nosignal request triggers a warning message if the
1873	 * rotated logfile needs to be compressed, *unless* -R was also
1874	 * specified.  We assume that an `-sR' request came from a process
1875	 * which writes to the logfile, and as such, we assume that process
1876	 * has already made sure the logfile is not presently in use.  This
1877	 * just sets swork->sw_pidok to a special value, and do_zipwork
1878	 * will print any necessary warning(s).
1879	 */
1880	if (nosignal) {
1881		if (!rotatereq)
1882			swork->sw_pidok = -1;
1883		return;
1884	}
1885
1886	/*
1887	 * Compute the pause between consecutive signals.  Use a longer
1888	 * sleep time if we will be sending two signals to the same
1889	 * deamon or process-group.
1890	 */
1891	secs = 0;
1892	nextsig = SLIST_NEXT(swork, sw_nextp);
1893	if (nextsig != NULL) {
1894		if (swork->sw_pid == nextsig->sw_pid)
1895			secs = 10;
1896		else
1897			secs = 1;
1898	}
1899
1900	if (noaction) {
1901		if (swork->sw_runcmd)
1902			printf("\tsh -c '%s %d'\n", swork->sw_fname,
1903			    swork->sw_signum);
1904		else {
1905			printf("\tkill -%d %d \t\t# %s\n", swork->sw_signum,
1906			    (int)swork->sw_pid, swork->sw_fname);
1907			if (secs > 0)
1908				printf("\tsleep %d\n", secs);
1909		}
1910		return;
1911	}
1912
1913	if (swork->sw_runcmd) {
1914		asprintf(&tmp, "%s %d", swork->sw_fname, swork->sw_signum);
1915		if (tmp == NULL) {
1916			warn("can't allocate memory to run %s",
1917			    swork->sw_fname);
1918			return;
1919		}
1920		if (verbose)
1921			printf("Run command: %s\n", tmp);
1922		kres = system(tmp);
1923		if (kres) {
1924			warnx("%s: returned non-zero exit code: %d",
1925			    tmp, kres);
1926		}
1927		free(tmp);
1928		return;
1929	}
1930
1931	kres = kill(swork->sw_pid, swork->sw_signum);
1932	if (kres != 0) {
1933		/*
1934		 * Assume that "no such process" (ESRCH) is something
1935		 * to warn about, but is not an error.  Presumably the
1936		 * process which writes to the rotated log file(s) is
1937		 * gone, in which case we should have no problem with
1938		 * compressing the rotated log file(s).
1939		 */
1940		if (errno != ESRCH)
1941			swork->sw_pidok = 0;
1942		warn("can't notify %s, pid %d", swork->sw_pidtype,
1943		    (int)swork->sw_pid);
1944	} else {
1945		if (verbose)
1946			printf("Notified %s pid %d = %s\n", swork->sw_pidtype,
1947			    (int)swork->sw_pid, swork->sw_fname);
1948		if (secs > 0) {
1949			if (verbose)
1950				printf("Pause %d second(s) between signals\n",
1951				    secs);
1952			sleep(secs);
1953		}
1954	}
1955}
1956
1957static void
1958do_zipwork(struct zipwork_entry *zwork)
1959{
1960	const char *pgm_name, *pgm_path;
1961	int errsav, fcount, zstatus;
1962	pid_t pidzip, wpid;
1963	char zresult[MAXPATHLEN];
1964	int c;
1965
1966	assert(zwork != NULL);
1967	pgm_path = NULL;
1968	strlcpy(zresult, zwork->zw_fname, sizeof(zresult));
1969	if (zwork->zw_conf != NULL &&
1970	    zwork->zw_conf->compress > COMPRESS_NONE)
1971		for (c = 1; c < COMPRESS_TYPES; c++) {
1972			if (zwork->zw_conf->compress == c) {
1973				pgm_path = compress_type[c].path;
1974				(void) strlcat(zresult,
1975				    compress_type[c].suffix, sizeof(zresult));
1976				break;
1977			}
1978		}
1979	if (pgm_path == NULL) {
1980		warnx("invalid entry for %s in do_zipwork", zwork->zw_fname);
1981		return;
1982	}
1983	pgm_name = strrchr(pgm_path, '/');
1984	if (pgm_name == NULL)
1985		pgm_name = pgm_path;
1986	else
1987		pgm_name++;
1988
1989	if (zwork->zw_swork != NULL && zwork->zw_swork->sw_runcmd == 0 &&
1990	    zwork->zw_swork->sw_pidok <= 0) {
1991		warnx(
1992		    "log %s not compressed because daemon(s) not notified",
1993		    zwork->zw_fname);
1994		change_attrs(zwork->zw_fname, zwork->zw_conf);
1995		return;
1996	}
1997
1998	if (noaction) {
1999		printf("\t%s %s\n", pgm_name, zwork->zw_fname);
2000		change_attrs(zresult, zwork->zw_conf);
2001		return;
2002	}
2003
2004	fcount = 1;
2005	pidzip = fork();
2006	while (pidzip < 0) {
2007		/*
2008		 * The fork failed.  If the failure was due to a temporary
2009		 * problem, then wait a short time and try it again.
2010		 */
2011		errsav = errno;
2012		warn("fork() for `%s %s'", pgm_name, zwork->zw_fname);
2013		if (errsav != EAGAIN || fcount > 5)
2014			errx(1, "Exiting...");
2015		sleep(fcount * 12);
2016		fcount++;
2017		pidzip = fork();
2018	}
2019	if (!pidzip) {
2020		/* The child process executes the compression command */
2021		execl(pgm_path, pgm_path, "-f", zwork->zw_fname, (char *)0);
2022		err(1, "execl(`%s -f %s')", pgm_path, zwork->zw_fname);
2023	}
2024
2025	wpid = waitpid(pidzip, &zstatus, 0);
2026	if (wpid == -1) {
2027		/* XXX - should this be a fatal error? */
2028		warn("%s: waitpid(%d)", pgm_path, pidzip);
2029		return;
2030	}
2031	if (!WIFEXITED(zstatus)) {
2032		warnx("`%s -f %s' did not terminate normally", pgm_name,
2033		    zwork->zw_fname);
2034		return;
2035	}
2036	if (WEXITSTATUS(zstatus)) {
2037		warnx("`%s -f %s' terminated with a non-zero status (%d)",
2038		    pgm_name, zwork->zw_fname, WEXITSTATUS(zstatus));
2039		return;
2040	}
2041
2042	/* Compression was successful, set file attributes on the result. */
2043	change_attrs(zresult, zwork->zw_conf);
2044}
2045
2046/*
2047 * Save information on any process we need to signal.  Any single
2048 * process may need to be sent different signal-values for different
2049 * log files, but usually a single signal-value will cause the process
2050 * to close and re-open all of it's log files.
2051 */
2052static struct sigwork_entry *
2053save_sigwork(const struct conf_entry *ent)
2054{
2055	struct sigwork_entry *sprev, *stmp;
2056	int ndiff;
2057	size_t tmpsiz;
2058
2059	sprev = NULL;
2060	ndiff = 1;
2061	SLIST_FOREACH(stmp, &swhead, sw_nextp) {
2062		ndiff = strcmp(ent->pid_cmd_file, stmp->sw_fname);
2063		if (ndiff > 0)
2064			break;
2065		if (ndiff == 0) {
2066			if (ent->sig == stmp->sw_signum)
2067				break;
2068			if (ent->sig > stmp->sw_signum) {
2069				ndiff = 1;
2070				break;
2071			}
2072		}
2073		sprev = stmp;
2074	}
2075	if (stmp != NULL && ndiff == 0)
2076		return (stmp);
2077
2078	tmpsiz = sizeof(struct sigwork_entry) + strlen(ent->pid_cmd_file) + 1;
2079	stmp = malloc(tmpsiz);
2080
2081	stmp->sw_runcmd = 0;
2082	/* If this is a command to run we just set the flag and run command */
2083	if (ent->flags & CE_PID2CMD) {
2084		stmp->sw_pid = -1;
2085		stmp->sw_pidok = 0;
2086		stmp->sw_runcmd = 1;
2087	} else {
2088		set_swpid(stmp, ent);
2089	}
2090	stmp->sw_signum = ent->sig;
2091	strcpy(stmp->sw_fname, ent->pid_cmd_file);
2092	if (sprev == NULL)
2093		SLIST_INSERT_HEAD(&swhead, stmp, sw_nextp);
2094	else
2095		SLIST_INSERT_AFTER(sprev, stmp, sw_nextp);
2096	return (stmp);
2097}
2098
2099/*
2100 * Save information on any file we need to compress.  We may see the same
2101 * file multiple times, so check the full list to avoid duplicates.  The
2102 * list itself is sorted smallest-to-largest, because that's the order we
2103 * want to compress the files.  If the partition is very low on disk space,
2104 * then the smallest files are the most likely to compress, and compressing
2105 * them first will free up more space for the larger files.
2106 */
2107static struct zipwork_entry *
2108save_zipwork(const struct conf_entry *ent, const struct sigwork_entry *swork,
2109    int zsize, const char *zipfname)
2110{
2111	struct zipwork_entry *zprev, *ztmp;
2112	int ndiff;
2113	size_t tmpsiz;
2114
2115	/* Compute the size if the caller did not know it. */
2116	if (zsize < 0)
2117		zsize = sizefile(zipfname);
2118
2119	zprev = NULL;
2120	ndiff = 1;
2121	SLIST_FOREACH(ztmp, &zwhead, zw_nextp) {
2122		ndiff = strcmp(zipfname, ztmp->zw_fname);
2123		if (ndiff == 0)
2124			break;
2125		if (zsize > ztmp->zw_fsize)
2126			zprev = ztmp;
2127	}
2128	if (ztmp != NULL && ndiff == 0)
2129		return (ztmp);
2130
2131	tmpsiz = sizeof(struct zipwork_entry) + strlen(zipfname) + 1;
2132	ztmp = malloc(tmpsiz);
2133	ztmp->zw_conf = ent;
2134	ztmp->zw_swork = swork;
2135	ztmp->zw_fsize = zsize;
2136	strcpy(ztmp->zw_fname, zipfname);
2137	if (zprev == NULL)
2138		SLIST_INSERT_HEAD(&zwhead, ztmp, zw_nextp);
2139	else
2140		SLIST_INSERT_AFTER(zprev, ztmp, zw_nextp);
2141	return (ztmp);
2142}
2143
2144/* Send a signal to the pid specified by pidfile */
2145static void
2146set_swpid(struct sigwork_entry *swork, const struct conf_entry *ent)
2147{
2148	FILE *f;
2149	long minok, maxok, rval;
2150	char *endp, *linep, line[BUFSIZ];
2151
2152	minok = MIN_PID;
2153	maxok = MAX_PID;
2154	swork->sw_pidok = 0;
2155	swork->sw_pid = 0;
2156	swork->sw_pidtype = "daemon";
2157	if (ent->flags & CE_SIGNALGROUP) {
2158		/*
2159		 * If we are expected to signal a process-group when
2160		 * rotating this logfile, then the value read in should
2161		 * be the negative of a valid process ID.
2162		 */
2163		minok = -MAX_PID;
2164		maxok = -MIN_PID;
2165		swork->sw_pidtype = "process-group";
2166	}
2167
2168	f = fopen(ent->pid_cmd_file, "r");
2169	if (f == NULL) {
2170		if (errno == ENOENT && enforcepid == 0) {
2171			/*
2172			 * Warn if the PID file doesn't exist, but do
2173			 * not consider it an error.  Most likely it
2174			 * means the process has been terminated,
2175			 * so it should be safe to rotate any log
2176			 * files that the process would have been using.
2177			 */
2178			swork->sw_pidok = 1;
2179			warnx("pid file doesn't exist: %s", ent->pid_cmd_file);
2180		} else
2181			warn("can't open pid file: %s", ent->pid_cmd_file);
2182		return;
2183	}
2184
2185	if (fgets(line, BUFSIZ, f) == NULL) {
2186		/*
2187		 * Warn if the PID file is empty, but do not consider
2188		 * it an error.  Most likely it means the process has
2189		 * has terminated, so it should be safe to rotate any
2190		 * log files that the process would have been using.
2191		 */
2192		if (feof(f) && enforcepid == 0) {
2193			swork->sw_pidok = 1;
2194			warnx("pid/cmd file is empty: %s", ent->pid_cmd_file);
2195		} else
2196			warn("can't read from pid file: %s", ent->pid_cmd_file);
2197		(void)fclose(f);
2198		return;
2199	}
2200	(void)fclose(f);
2201
2202	errno = 0;
2203	linep = line;
2204	while (*linep == ' ')
2205		linep++;
2206	rval = strtol(linep, &endp, 10);
2207	if (*endp != '\0' && !isspacech(*endp)) {
2208		warnx("pid file does not start with a valid number: %s",
2209		    ent->pid_cmd_file);
2210	} else if (rval < minok || rval > maxok) {
2211		warnx("bad value '%ld' for process number in %s",
2212		    rval, ent->pid_cmd_file);
2213		if (verbose)
2214			warnx("\t(expecting value between %ld and %ld)",
2215			    minok, maxok);
2216	} else {
2217		swork->sw_pidok = 1;
2218		swork->sw_pid = rval;
2219	}
2220
2221	return;
2222}
2223
2224/* Log the fact that the logs were turned over */
2225static int
2226log_trim(const char *logname, const struct conf_entry *log_ent)
2227{
2228	FILE *f;
2229	const char *xtra;
2230
2231	if ((f = fopen(logname, "a")) == NULL)
2232		return (-1);
2233	xtra = "";
2234	if (log_ent->def_cfg)
2235		xtra = " using <default> rule";
2236	if (log_ent->firstcreate)
2237		fprintf(f, "%s %s newsyslog[%d]: logfile first created%s\n",
2238		    daytime, hostname, (int) getpid(), xtra);
2239	else if (log_ent->r_reason != NULL)
2240		fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s%s\n",
2241		    daytime, hostname, (int) getpid(), log_ent->r_reason, xtra);
2242	else
2243		fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s\n",
2244		    daytime, hostname, (int) getpid(), xtra);
2245	if (fclose(f) == EOF)
2246		err(1, "log_trim: fclose");
2247	return (0);
2248}
2249
2250/* Return size in kilobytes of a file */
2251static int
2252sizefile(const char *file)
2253{
2254	struct stat sb;
2255
2256	if (stat(file, &sb) < 0)
2257		return (-1);
2258	return (kbytes(dbtob(sb.st_blocks)));
2259}
2260
2261/* Return the age of old log file (file.0) */
2262static int
2263age_old_log(char *file)
2264{
2265	struct stat sb;
2266	const char *logfile_suffix;
2267	char tmp[MAXPATHLEN + sizeof(".0") + COMPRESS_SUFFIX_MAXLEN + 1];
2268
2269	if (archtodir) {
2270		char *p;
2271
2272		/* build name of archive directory into tmp */
2273		if (*archdirname == '/') {	/* absolute */
2274			strlcpy(tmp, archdirname, sizeof(tmp));
2275		} else {	/* relative */
2276			/* get directory part of logfile */
2277			strlcpy(tmp, file, sizeof(tmp));
2278			if ((p = rindex(tmp, '/')) == NULL)
2279				tmp[0] = '\0';
2280			else
2281				*(p + 1) = '\0';
2282			strlcat(tmp, archdirname, sizeof(tmp));
2283		}
2284
2285		strlcat(tmp, "/", sizeof(tmp));
2286
2287		/* get filename part of logfile */
2288		if ((p = rindex(file, '/')) == NULL)
2289			strlcat(tmp, file, sizeof(tmp));
2290		else
2291			strlcat(tmp, p + 1, sizeof(tmp));
2292	} else {
2293		(void) strlcpy(tmp, file, sizeof(tmp));
2294	}
2295
2296	strlcat(tmp, ".0", sizeof(tmp));
2297	logfile_suffix = get_logfile_suffix(tmp);
2298	if (logfile_suffix == NULL)
2299		return (-1);
2300	(void) strlcat(tmp, logfile_suffix, sizeof(tmp));
2301	if (stat(tmp, &sb) < 0)
2302		return (-1);
2303	return ((int)(ptimeget_secs(timenow) - sb.st_mtime + 1800) / 3600);
2304}
2305
2306/* Skip Over Blanks */
2307static char *
2308sob(char *p)
2309{
2310	while (p && *p && isspace(*p))
2311		p++;
2312	return (p);
2313}
2314
2315/* Skip Over Non-Blanks */
2316static char *
2317son(char *p)
2318{
2319	while (p && *p && !isspace(*p))
2320		p++;
2321	return (p);
2322}
2323
2324/* Check if string is actually a number */
2325static int
2326isnumberstr(const char *string)
2327{
2328	while (*string) {
2329		if (!isdigitch(*string++))
2330			return (0);
2331	}
2332	return (1);
2333}
2334
2335/* Check if string contains a glob */
2336static int
2337isglobstr(const char *string)
2338{
2339	char chr;
2340
2341	while ((chr = *string++)) {
2342		if (chr == '*' || chr == '?' || chr == '[')
2343			return (1);
2344	}
2345	return (0);
2346}
2347
2348/*
2349 * Save the active log file under a new name.  A link to the new name
2350 * is the quick-and-easy way to do this.  If that fails (which it will
2351 * if the destination is on another partition), then make a copy of
2352 * the file to the new location.
2353 */
2354static void
2355savelog(char *from, char *to)
2356{
2357	FILE *src, *dst;
2358	int c, res;
2359
2360	res = link(from, to);
2361	if (res == 0)
2362		return;
2363
2364	if ((src = fopen(from, "r")) == NULL)
2365		err(1, "can't fopen %s for reading", from);
2366	if ((dst = fopen(to, "w")) == NULL)
2367		err(1, "can't fopen %s for writing", to);
2368
2369	while ((c = getc(src)) != EOF) {
2370		if ((putc(c, dst)) == EOF)
2371			err(1, "error writing to %s", to);
2372	}
2373
2374	if (ferror(src))
2375		err(1, "error reading from %s", from);
2376	if ((fclose(src)) != 0)
2377		err(1, "can't fclose %s", to);
2378	if ((fclose(dst)) != 0)
2379		err(1, "can't fclose %s", from);
2380}
2381
2382/* create one or more directory components of a path */
2383static void
2384createdir(const struct conf_entry *ent, char *dirpart)
2385{
2386	int res;
2387	char *s, *d;
2388	char mkdirpath[MAXPATHLEN];
2389	struct stat st;
2390
2391	s = dirpart;
2392	d = mkdirpath;
2393
2394	for (;;) {
2395		*d++ = *s++;
2396		if (*s != '/' && *s != '\0')
2397			continue;
2398		*d = '\0';
2399		res = lstat(mkdirpath, &st);
2400		if (res != 0) {
2401			if (noaction) {
2402				printf("\tmkdir %s\n", mkdirpath);
2403			} else {
2404				res = mkdir(mkdirpath, 0755);
2405				if (res != 0)
2406					err(1, "Error on mkdir(\"%s\") for -a",
2407					    mkdirpath);
2408			}
2409		}
2410		if (*s == '\0')
2411			break;
2412	}
2413	if (verbose) {
2414		if (ent->firstcreate)
2415			printf("Created directory '%s' for new %s\n",
2416			    dirpart, ent->log);
2417		else
2418			printf("Created directory '%s' for -a\n", dirpart);
2419	}
2420}
2421
2422/*
2423 * Create a new log file, destroying any currently-existing version
2424 * of the log file in the process.  If the caller wants a backup copy
2425 * of the file to exist, they should call 'link(logfile,logbackup)'
2426 * before calling this routine.
2427 */
2428void
2429createlog(const struct conf_entry *ent)
2430{
2431	int fd, failed;
2432	struct stat st;
2433	char *realfile, *slash, tempfile[MAXPATHLEN];
2434
2435	fd = -1;
2436	realfile = ent->log;
2437
2438	/*
2439	 * If this log file is being created for the first time (-C option),
2440	 * then it may also be true that the parent directory does not exist
2441	 * yet.  Check, and create that directory if it is missing.
2442	 */
2443	if (ent->firstcreate) {
2444		strlcpy(tempfile, realfile, sizeof(tempfile));
2445		slash = strrchr(tempfile, '/');
2446		if (slash != NULL) {
2447			*slash = '\0';
2448			failed = stat(tempfile, &st);
2449			if (failed && errno != ENOENT)
2450				err(1, "Error on stat(%s)", tempfile);
2451			if (failed)
2452				createdir(ent, tempfile);
2453			else if (!S_ISDIR(st.st_mode))
2454				errx(1, "%s exists but is not a directory",
2455				    tempfile);
2456		}
2457	}
2458
2459	/*
2460	 * First create an unused filename, so it can be chown'ed and
2461	 * chmod'ed before it is moved into the real location.  mkstemp
2462	 * will create the file mode=600 & owned by us.  Note that all
2463	 * temp files will have a suffix of '.z<something>'.
2464	 */
2465	strlcpy(tempfile, realfile, sizeof(tempfile));
2466	strlcat(tempfile, ".zXXXXXX", sizeof(tempfile));
2467	if (noaction)
2468		printf("\tmktemp %s\n", tempfile);
2469	else {
2470		fd = mkstemp(tempfile);
2471		if (fd < 0)
2472			err(1, "can't mkstemp logfile %s", tempfile);
2473
2474		/*
2475		 * Add status message to what will become the new log file.
2476		 */
2477		if (!(ent->flags & CE_BINARY)) {
2478			if (log_trim(tempfile, ent))
2479				err(1, "can't add status message to log");
2480		}
2481	}
2482
2483	/* Change the owner/group, if we are supposed to */
2484	if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2485		if (noaction)
2486			printf("\tchown %u:%u %s\n", ent->uid, ent->gid,
2487			    tempfile);
2488		else {
2489			failed = fchown(fd, ent->uid, ent->gid);
2490			if (failed)
2491				err(1, "can't fchown temp file %s", tempfile);
2492		}
2493	}
2494
2495	/* Turn on NODUMP if it was requested in the config-file. */
2496	if (ent->flags & CE_NODUMP) {
2497		if (noaction)
2498			printf("\tchflags nodump %s\n", tempfile);
2499		else {
2500			failed = fchflags(fd, UF_NODUMP);
2501			if (failed) {
2502				warn("log_trim: fchflags(NODUMP)");
2503			}
2504		}
2505	}
2506
2507	/*
2508	 * Note that if the real logfile still exists, and if the call
2509	 * to rename() fails, then "neither the old file nor the new
2510	 * file shall be changed or created" (to quote the standard).
2511	 * If the call succeeds, then the file will be replaced without
2512	 * any window where some other process might find that the file
2513	 * did not exist.
2514	 * XXX - ? It may be that for some error conditions, we could
2515	 *	retry by first removing the realfile and then renaming.
2516	 */
2517	if (noaction) {
2518		printf("\tchmod %o %s\n", ent->permissions, tempfile);
2519		printf("\tmv %s %s\n", tempfile, realfile);
2520	} else {
2521		failed = fchmod(fd, ent->permissions);
2522		if (failed)
2523			err(1, "can't fchmod temp file '%s'", tempfile);
2524		failed = rename(tempfile, realfile);
2525		if (failed)
2526			err(1, "can't mv %s to %s", tempfile, realfile);
2527	}
2528
2529	if (fd >= 0)
2530		close(fd);
2531}
2532
2533/*
2534 * Change the attributes of a given filename to what was specified in
2535 * the newsyslog.conf entry.  This routine is only called for files
2536 * that newsyslog expects that it has created, and thus it is a fatal
2537 * error if this routine finds that the file does not exist.
2538 */
2539static void
2540change_attrs(const char *fname, const struct conf_entry *ent)
2541{
2542	int failed;
2543
2544	if (noaction) {
2545		printf("\tchmod %o %s\n", ent->permissions, fname);
2546
2547		if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
2548			printf("\tchown %u:%u %s\n",
2549			    ent->uid, ent->gid, fname);
2550
2551		if (ent->flags & CE_NODUMP)
2552			printf("\tchflags nodump %s\n", fname);
2553		return;
2554	}
2555
2556	failed = chmod(fname, ent->permissions);
2557	if (failed) {
2558		if (errno != EPERM)
2559			err(1, "chmod(%s) in change_attrs", fname);
2560		warn("change_attrs couldn't chmod(%s)", fname);
2561	}
2562
2563	if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2564		failed = chown(fname, ent->uid, ent->gid);
2565		if (failed)
2566			warn("can't chown %s", fname);
2567	}
2568
2569	if (ent->flags & CE_NODUMP) {
2570		failed = chflags(fname, UF_NODUMP);
2571		if (failed)
2572			warn("can't chflags %s NODUMP", fname);
2573	}
2574}
2575