newsyslog.c revision 139655
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: head/usr.sbin/newsyslog/newsyslog.c 139655 2005-01-04 02:24:01Z delphij $");
5813244Sgraichen
59130045Sgad#define	OSF
6013244Sgraichen#ifndef COMPRESS_POSTFIX
61130045Sgad#define	COMPRESS_POSTFIX ".gz"
6213244Sgraichen#endif
6380638Sobrien#ifndef	BZCOMPRESS_POSTFIX
6480638Sobrien#define	BZCOMPRESS_POSTFIX ".bz2"
6580638Sobrien#endif
6613244Sgraichen
6796001Smaxim#include <sys/param.h>
68130167Sgad#include <sys/queue.h>
6996001Smaxim#include <sys/stat.h>
7096001Smaxim#include <sys/wait.h>
7196001Smaxim
7230160Scharnier#include <ctype.h>
7330160Scharnier#include <err.h>
7495999Smaxim#include <errno.h>
7530160Scharnier#include <fcntl.h>
76111773Sgad#include <fnmatch.h>
77106905Ssobomax#include <glob.h>
7830160Scharnier#include <grp.h>
7943071Swollman#include <paths.h>
8030160Scharnier#include <pwd.h>
8130160Scharnier#include <signal.h>
8213244Sgraichen#include <stdio.h>
8313244Sgraichen#include <stdlib.h>
8413244Sgraichen#include <string.h>
8543071Swollman#include <time.h>
8616240Salex#include <unistd.h>
8713244Sgraichen
8843071Swollman#include "pathnames.h"
89119998Sgad#include "extern.h"
9043071Swollman
91130167Sgad/* Define this symbol to try out the "new order" for work items. */
92130167Sgad#define	TRY_NEWORDER
93130385Sgad#ifndef USE_NEWORDER
94130385Sgad#define	USE_NEWORDER	1	/* Initial value for dbg_new_order */
95130385Sgad#endif
96130167Sgad
97111768Sgad/*
98111768Sgad * Bit-values for the 'flags' parsed from a config-file entry.
99111768Sgad */
100130045Sgad#define	CE_COMPACT	0x0001	/* Compact the achived log files with gzip. */
101130045Sgad#define	CE_BZCOMPACT	0x0002	/* Compact the achived log files with bzip2. */
102130045Sgad#define	CE_COMPACTWAIT	0x0004	/* wait until compressing one file finishes */
103111768Sgad				/*    before starting the next step. */
104130045Sgad#define	CE_BINARY	0x0008	/* Logfile is in binary, do not add status */
105111768Sgad				/*    messages to logfile(s) when rotating. */
106130045Sgad#define	CE_NOSIGNAL	0x0010	/* There is no process to signal when */
107111768Sgad				/*    trimming this file. */
108130045Sgad#define	CE_TRIMAT	0x0020	/* trim file at a specific time. */
109130045Sgad#define	CE_GLOB		0x0040	/* name of the log is file name pattern. */
110130045Sgad#define	CE_SIGNALGROUP	0x0080	/* Signal a process-group instead of a single */
111112003Sgad				/*    process when trimming this file. */
112130045Sgad#define	CE_CREATE	0x0100	/* Create the log file if it does not exist. */
113130043Sgad#define	CE_NODUMP	0x0200	/* Set 'nodump' on newly created log file. */
11443071Swollman
115130045Sgad#define	MIN_PID         5	/* Don't touch pids lower than this */
116130045Sgad#define	MAX_PID		99999	/* was lower, see /usr/include/sys/proc.h */
117111781Sgad
118130045Sgad#define	kbytes(size)  (((size) + 1023) >> 10)
119111781Sgad
120130165Sgad#define	DEFAULT_MARKER	"<default>"
121130165Sgad#define	DEBUG_MARKER	"<debug>"
122130165Sgad
12313244Sgraichenstruct conf_entry {
12459003Shm	char *log;		/* Name of the log */
12559003Shm	char *pid_file;		/* PID file */
126111772Sgad	char *r_reason;		/* The reason this file is being rotated */
127114137Sgad	int firstcreate;	/* Creating log for the first time (-C). */
128111772Sgad	int rotate;		/* Non-zero if this file should be rotated */
129130165Sgad	int fsize;		/* size found for the log file */
130111779Sgad	uid_t uid;		/* Owner of log */
131111779Sgad	gid_t gid;		/* Group of log */
13259003Shm	int numlogs;		/* Number of logs to keep */
133130165Sgad	int trsize;		/* Size cutoff to trigger trimming the log */
13459003Shm	int hours;		/* Hours between log trimming */
135120361Sgad	struct ptime_data *trim_at;	/* Specific time to do trimming */
136139655Sdelphij	unsigned int permissions;	/* File permissions on the log */
13780646Sobrien	int flags;		/* CE_COMPACT, CE_BZCOMPACT, CE_BINARY */
13859003Shm	int sig;		/* Signal to send */
139111388Sgad	int def_cfg;		/* Using the <default> rule for this file */
14059003Shm	struct conf_entry *next;/* Linked list pointer */
14113244Sgraichen};
14213244Sgraichen
143130167Sgadstruct sigwork_entry {
144130167Sgad	SLIST_ENTRY(sigwork_entry) sw_nextp;
145130167Sgad	int	 sw_signum;		/* the signal to send */
146130167Sgad	int	 sw_pidok;		/* true if pid value is valid */
147130167Sgad	pid_t	 sw_pid;		/* the process id from the PID file */
148130167Sgad	const char *sw_pidtype;		/* "daemon" or "process group" */
149130167Sgad	char	 sw_fname[1];		/* file the PID was read from */
150130167Sgad};
151130167Sgad
152130167Sgadstruct zipwork_entry {
153130167Sgad	SLIST_ENTRY(zipwork_entry) zw_nextp;
154130167Sgad	const struct conf_entry *zw_conf;	/* for chown/perm/flag info */
155130167Sgad	const struct sigwork_entry *zw_swork;	/* to know success of signal */
156130167Sgad	int	 zw_fsize;		/* size of the file to compress */
157130167Sgad	char	 zw_fname[1];		/* the file to compress */
158130167Sgad};
159130167Sgad
160130165Sgadtypedef enum {
161130165Sgad	FREE_ENT, KEEP_ENT
162130165Sgad}	fk_entry;
163111388Sgad
164130167SgadSLIST_HEAD(swlisthead, sigwork_entry) swhead = SLIST_HEAD_INITIALIZER(swhead);
165130167SgadSLIST_HEAD(zwlisthead, zipwork_entry) zwhead = SLIST_HEAD_INITIALIZER(zwhead);
166130167Sgad
167120361Sgadint dbg_at_times;		/* -D Show details of 'trim_at' code */
168130385Sgad/*
169130385Sgad * The debug options "neworder" and "oldorder" can be used to change
170130385Sgad * which order work is done in.  Note that both options will disappear
171130385Sgad * in the near future, and the "new" order will be the only order.
172130385Sgad */
173130385Sgadint dbg_new_order = USE_NEWORDER;
174120361Sgad
17559004Shmint archtodir = 0;		/* Archive old logfiles to other directory */
176114137Sgadint createlogs;			/* Create (non-GLOB) logfiles which do not */
177114137Sgad				/*    already exist.  1=='for entries with */
178114137Sgad				/*    C flag', 2=='for all entries'. */
17959003Shmint verbose = 0;		/* Print out what's going on */
18059003Shmint needroot = 1;		/* Root privs are necessary */
18159003Shmint noaction = 0;		/* Don't do anything, just show it */
182111768Sgadint nosignal;			/* Do not send any signals */
18359003Shmint force = 0;			/* Force the trim no matter what */
184111772Sgadint rotatereq = 0;		/* -R = Always rotate the file(s) as given */
185111772Sgad				/*    on the command (this also requires   */
186111772Sgad				/*    that a list of files *are* given on  */
187111772Sgad				/*    the run command). */
188111772Sgadchar *requestor;		/* The name given on a -R request */
18959004Shmchar *archdirname;		/* Directory path to old logfiles archive */
190136127Sbrookschar *destdir = NULL;		/* Directory to treat at root for logs */
191111773Sgadconst char *conf;		/* Configuration file to use */
19259003Shm
193120361Sgadstruct ptime_data *dbg_timenow;	/* A "timenow" value set via -D option */
194120361Sgadstruct ptime_data *timenow;	/* The time to use for checking at-fields */
195120361Sgad
19671299Sjedgarchar hostname[MAXHOSTNAMELEN];	/* hostname */
197120361Sgadchar daytime[16];		/* The current time in human readable form,
198120361Sgad				 * used for rotation-tracking messages. */
19913244Sgraichen
200111773Sgadstatic struct conf_entry *get_worklist(char **files);
201111773Sgadstatic void parse_file(FILE *cf, const char *cfname, struct conf_entry **work_p,
202112020Sgad		struct conf_entry **glob_p, struct conf_entry **defconf_p);
20316240Salexstatic char *sob(char *p);
20416240Salexstatic char *son(char *p);
205119102Sgadstatic int isnumberstr(const char *);
20659003Shmstatic char *missing_field(char *p, char *errline);
207130165Sgadstatic void	 change_attrs(const char *, const struct conf_entry *);
208130165Sgadstatic fk_entry	 do_entry(struct conf_entry *);
209130165Sgadstatic fk_entry	 do_rotate(const struct conf_entry *);
210130167Sgad#ifdef TRY_NEWORDER
211130167Sgadstatic void	 do_sigwork(struct sigwork_entry *);
212130167Sgadstatic void	 do_zipwork(struct zipwork_entry *);
213130167Sgadstatic struct sigwork_entry *
214130167Sgad		 save_sigwork(const struct conf_entry *);
215130167Sgadstatic struct zipwork_entry *
216130167Sgad		 save_zipwork(const struct conf_entry *, const struct
217130167Sgad		    sigwork_entry *, int, const char *);
218130167Sgadstatic void	 set_swpid(struct sigwork_entry *, const struct conf_entry *);
219130167Sgad#endif
220130165Sgadstatic int	 sizefile(const char *);
221112020Sgadstatic void expand_globs(struct conf_entry **work_p,
222112020Sgad		struct conf_entry **glob_p);
223112020Sgadstatic void free_clist(struct conf_entry **firstent);
224111388Sgadstatic void free_entry(struct conf_entry *ent);
225111388Sgadstatic struct conf_entry *init_entry(const char *fname,
226111388Sgad		struct conf_entry *src_entry);
227111781Sgadstatic void parse_args(int argc, char **argv);
228119904Sgadstatic int parse_doption(const char *doption);
22980640Sobrienstatic void usage(void);
230119926Sgadstatic int log_trim(const char *logname, const struct conf_entry *log_ent);
231119926Sgadstatic void compress_log(char *logname, int dowait);
232119926Sgadstatic void bzcompress_log(char *logname, int dowait);
23316240Salexstatic int age_old_log(char *file);
234112003Sgadstatic int send_signal(const struct conf_entry *ent);
235130038Sgadstatic void savelog(char *from, char *to);
236114137Sgadstatic void createdir(const struct conf_entry *ent, char *dirpart);
237114137Sgadstatic void createlog(const struct conf_entry *ent);
23813244Sgraichen
239111768Sgad/*
240129975Sgad * All the following take a parameter of 'int', but expect values in the
241129975Sgad * range of unsigned char.  Define wrappers which take values of type 'char',
242129975Sgad * whether signed or unsigned, and ensure they end up in the right range.
243111768Sgad */
244129975Sgad#define	isdigitch(Anychar) isdigit((u_char)(Anychar))
245129975Sgad#define	isprintch(Anychar) isprint((u_char)(Anychar))
246129975Sgad#define	isspacech(Anychar) isspace((u_char)(Anychar))
247129975Sgad#define	tolowerch(Anychar) tolower((u_char)(Anychar))
248111768Sgad
24959004Shmint
25059004Shmmain(int argc, char **argv)
25113244Sgraichen{
252130165Sgad	fk_entry free_or_keep;
25359003Shm	struct conf_entry *p, *q;
254130167Sgad#ifdef TRY_NEWORDER
255130167Sgad	struct sigwork_entry *stmp;
256130167Sgad	struct zipwork_entry *ztmp;
257130167Sgad#endif
25825443Sache
259130167Sgad	SLIST_INIT(&swhead);
260130167Sgad	SLIST_INIT(&zwhead);
261130167Sgad
262111781Sgad	parse_args(argc, argv);
263111773Sgad	argc -= optind;
264111773Sgad	argv += optind;
265111773Sgad
26659003Shm	if (needroot && getuid() && geteuid())
26759003Shm		errx(1, "must have root privs");
268111773Sgad	p = q = get_worklist(argv);
26959003Shm
270130165Sgad	/*
271130165Sgad	 * Rotate all the files which need to be rotated.  Note that
272130165Sgad	 * some users have *hundreds* of entries in newsyslog.conf!
273130165Sgad	 */
27459003Shm	while (p) {
275130165Sgad		free_or_keep = do_entry(p);
27659003Shm		p = p->next;
277130165Sgad		if (free_or_keep == FREE_ENT)
278130165Sgad			free_entry(q);
27959003Shm		q = p;
28059003Shm	}
281130165Sgad
282130167Sgad#ifdef TRY_NEWORDER
283130167Sgad	/*
284130167Sgad	 * Send signals to any processes which need a signal to tell
285130167Sgad	 * them to close and re-open the log file(s) we have rotated.
286130167Sgad	 * Note that zipwork_entries include pointers to these
287130167Sgad	 * sigwork_entry's, so we can not free the entries here.
288130167Sgad	 */
289130167Sgad	if (!SLIST_EMPTY(&swhead)) {
290130204Sgad		if (noaction || verbose)
291130167Sgad			printf("Signal all daemon process(es)...\n");
292130167Sgad		SLIST_FOREACH(stmp, &swhead, sw_nextp)
293130167Sgad			do_sigwork(stmp);
294130204Sgad		if (noaction)
295130204Sgad			printf("\tsleep 10\n");
296130204Sgad		else {
297130204Sgad			if (verbose)
298130204Sgad				printf("Pause 10 seconds to allow daemon(s)"
299130204Sgad				    " to close log file(s)\n");
300130204Sgad			sleep(10);
301130204Sgad		}
302130167Sgad	}
303130167Sgad	/*
304130167Sgad	 * Compress all files that we're expected to compress, now
305130167Sgad	 * that all processes should have closed the files which
306130167Sgad	 * have been rotated.
307130167Sgad	 */
308130167Sgad	if (!SLIST_EMPTY(&zwhead)) {
309130204Sgad		if (noaction || verbose)
310130167Sgad			printf("Compress all rotated log file(s)...\n");
311130167Sgad		while (!SLIST_EMPTY(&zwhead)) {
312130167Sgad			ztmp = SLIST_FIRST(&zwhead);
313130167Sgad			do_zipwork(ztmp);
314130167Sgad			SLIST_REMOVE_HEAD(&zwhead, zw_nextp);
315130167Sgad			free(ztmp);
316130167Sgad		}
317130167Sgad	}
318130167Sgad	/* Now free all the sigwork entries. */
319130167Sgad	while (!SLIST_EMPTY(&swhead)) {
320130167Sgad		stmp = SLIST_FIRST(&swhead);
321130167Sgad		SLIST_REMOVE_HEAD(&swhead, sw_nextp);
322130167Sgad		free(stmp);
323130167Sgad	}
324130167Sgad#endif /* TRY_NEWORDER */
325130167Sgad
32695999Smaxim	while (wait(NULL) > 0 || errno == EINTR)
32795999Smaxim		;
32859003Shm	return (0);
32913244Sgraichen}
33013244Sgraichen
331111388Sgadstatic struct conf_entry *
332111388Sgadinit_entry(const char *fname, struct conf_entry *src_entry)
333111388Sgad{
334111388Sgad	struct conf_entry *tempwork;
335111388Sgad
336111388Sgad	if (verbose > 4)
337111388Sgad		printf("\t--> [creating entry for %s]\n", fname);
338111388Sgad
339111388Sgad	tempwork = malloc(sizeof(struct conf_entry));
340111388Sgad	if (tempwork == NULL)
341111388Sgad		err(1, "malloc of conf_entry for %s", fname);
342111388Sgad
343136174Sbrooks	if (destdir == NULL || fname[0] != '/')
344136127Sbrooks		tempwork->log = strdup(fname);
345136127Sbrooks	else
346136127Sbrooks		asprintf(&tempwork->log, "%s%s", destdir, fname);
347111388Sgad	if (tempwork->log == NULL)
348111388Sgad		err(1, "strdup for %s", fname);
349111388Sgad
350111388Sgad	if (src_entry != NULL) {
351111388Sgad		tempwork->pid_file = NULL;
352111388Sgad		if (src_entry->pid_file)
353111388Sgad			tempwork->pid_file = strdup(src_entry->pid_file);
354111772Sgad		tempwork->r_reason = NULL;
355114137Sgad		tempwork->firstcreate = 0;
356111772Sgad		tempwork->rotate = 0;
357130165Sgad		tempwork->fsize = -1;
358111388Sgad		tempwork->uid = src_entry->uid;
359111388Sgad		tempwork->gid = src_entry->gid;
360111388Sgad		tempwork->numlogs = src_entry->numlogs;
361130165Sgad		tempwork->trsize = src_entry->trsize;
362111388Sgad		tempwork->hours = src_entry->hours;
363120361Sgad		tempwork->trim_at = NULL;
364120361Sgad		if (src_entry->trim_at != NULL)
365120361Sgad			tempwork->trim_at = ptime_init(src_entry->trim_at);
366111388Sgad		tempwork->permissions = src_entry->permissions;
367111388Sgad		tempwork->flags = src_entry->flags;
368111388Sgad		tempwork->sig = src_entry->sig;
369111388Sgad		tempwork->def_cfg = src_entry->def_cfg;
370111388Sgad	} else {
371111388Sgad		/* Initialize as a "do-nothing" entry */
372111388Sgad		tempwork->pid_file = NULL;
373111772Sgad		tempwork->r_reason = NULL;
374114137Sgad		tempwork->firstcreate = 0;
375111772Sgad		tempwork->rotate = 0;
376130165Sgad		tempwork->fsize = -1;
377111779Sgad		tempwork->uid = (uid_t)-1;
378111779Sgad		tempwork->gid = (gid_t)-1;
379111388Sgad		tempwork->numlogs = 1;
380130165Sgad		tempwork->trsize = -1;
381111388Sgad		tempwork->hours = -1;
382120361Sgad		tempwork->trim_at = NULL;
383111388Sgad		tempwork->permissions = 0;
384111388Sgad		tempwork->flags = 0;
385111388Sgad		tempwork->sig = SIGHUP;
386111388Sgad		tempwork->def_cfg = 0;
387111388Sgad	}
388111388Sgad	tempwork->next = NULL;
389111388Sgad
390111388Sgad	return (tempwork);
391111388Sgad}
392111388Sgad
39359004Shmstatic void
394111388Sgadfree_entry(struct conf_entry *ent)
395111388Sgad{
396111388Sgad
397111388Sgad	if (ent == NULL)
398111388Sgad		return;
399111388Sgad
400111388Sgad	if (ent->log != NULL) {
401111388Sgad		if (verbose > 4)
402111388Sgad			printf("\t--> [freeing entry for %s]\n", ent->log);
403111388Sgad		free(ent->log);
404111388Sgad		ent->log = NULL;
405111388Sgad	}
406111388Sgad
407111388Sgad	if (ent->pid_file != NULL) {
408111388Sgad		free(ent->pid_file);
409111388Sgad		ent->pid_file = NULL;
410111388Sgad	}
411111388Sgad
412111772Sgad	if (ent->r_reason != NULL) {
413111772Sgad		free(ent->r_reason);
414111772Sgad		ent->r_reason = NULL;
415111772Sgad	}
416111772Sgad
417120361Sgad	if (ent->trim_at != NULL) {
418120361Sgad		ptime_free(ent->trim_at);
419120361Sgad		ent->trim_at = NULL;
420120361Sgad	}
421120361Sgad
422111388Sgad	free(ent);
423111388Sgad}
424111388Sgad
425111388Sgadstatic void
426112020Sgadfree_clist(struct conf_entry **firstent)
427112020Sgad{
428112020Sgad	struct conf_entry *ent, *nextent;
429112020Sgad
430112020Sgad	if (firstent == NULL)
431112020Sgad		return;			/* There is nothing to do. */
432112020Sgad
433112020Sgad	ent = *firstent;
434112020Sgad	firstent = NULL;
435112020Sgad
436112020Sgad	while (ent) {
437112020Sgad		nextent = ent->next;
438112020Sgad		free_entry(ent);
439112020Sgad		ent = nextent;
440112020Sgad	}
441112020Sgad}
442112020Sgad
443130165Sgadstatic fk_entry
44459004Shmdo_entry(struct conf_entry * ent)
44513244Sgraichen{
446130045Sgad#define	REASON_MAX	80
447130165Sgad	int modtime;
448130165Sgad	fk_entry free_or_keep;
449120361Sgad	double diffsecs;
450111772Sgad	char temp_reason[REASON_MAX];
45159003Shm
452130165Sgad	free_or_keep = FREE_ENT;
45359003Shm	if (verbose) {
45459003Shm		if (ent->flags & CE_COMPACT)
45559003Shm			printf("%s <%dZ>: ", ent->log, ent->numlogs);
45680638Sobrien		else if (ent->flags & CE_BZCOMPACT)
45780638Sobrien			printf("%s <%dJ>: ", ent->log, ent->numlogs);
45859003Shm		else
45959003Shm			printf("%s <%d>: ", ent->log, ent->numlogs);
46059003Shm	}
461130165Sgad	ent->fsize = sizefile(ent->log);
46259003Shm	modtime = age_old_log(ent->log);
463111772Sgad	ent->rotate = 0;
464114137Sgad	ent->firstcreate = 0;
465130165Sgad	if (ent->fsize < 0) {
466114137Sgad		/*
467114137Sgad		 * If either the C flag or the -C option was specified,
468114137Sgad		 * and if we won't be creating the file, then have the
469114137Sgad		 * verbose message include a hint as to why the file
470114137Sgad		 * will not be created.
471114137Sgad		 */
472114137Sgad		temp_reason[0] = '\0';
473114137Sgad		if (createlogs > 1)
474114137Sgad			ent->firstcreate = 1;
475114137Sgad		else if ((ent->flags & CE_CREATE) && createlogs)
476114137Sgad			ent->firstcreate = 1;
477114137Sgad		else if (ent->flags & CE_CREATE)
478114137Sgad			strncpy(temp_reason, " (no -C option)", REASON_MAX);
479114137Sgad		else if (createlogs)
480114137Sgad			strncpy(temp_reason, " (no C flag)", REASON_MAX);
481114137Sgad
482114137Sgad		if (ent->firstcreate) {
483114137Sgad			if (verbose)
484114137Sgad				printf("does not exist -> will create.\n");
485114137Sgad			createlog(ent);
486114137Sgad		} else if (verbose) {
487114137Sgad			printf("does not exist, skipped%s.\n", temp_reason);
488114137Sgad		}
48959003Shm	} else {
490111772Sgad		if (ent->flags & CE_TRIMAT && !force && !rotatereq) {
491120361Sgad			diffsecs = ptimeget_diff(timenow, ent->trim_at);
492120361Sgad			if (diffsecs < 0.0) {
493120361Sgad				/* trim_at is some time in the future. */
494120361Sgad				if (verbose) {
495120361Sgad					ptime_adjust4dst(ent->trim_at,
496120361Sgad					    timenow);
49743071Swollman					printf("--> will trim at %s",
498120361Sgad					    ptimeget_ctime(ent->trim_at));
499120361Sgad				}
500130165Sgad				return (free_or_keep);
501120361Sgad			} else if (diffsecs >= 3600.0) {
502120361Sgad				/*
503120361Sgad				 * trim_at is more than an hour in the past,
504120361Sgad				 * so find the next valid trim_at time, and
505120361Sgad				 * tell the user what that will be.
506120361Sgad				 */
507120361Sgad				if (verbose && dbg_at_times)
508120361Sgad					printf("\n\t--> prev trim at %s\t",
509120361Sgad					    ptimeget_ctime(ent->trim_at));
510120361Sgad				if (verbose) {
511120361Sgad					ptimeset_nxtime(ent->trim_at);
512120361Sgad					printf("--> will trim at %s",
513120361Sgad					    ptimeget_ctime(ent->trim_at));
514120361Sgad				}
515130165Sgad				return (free_or_keep);
516120361Sgad			} else if (verbose && noaction && dbg_at_times) {
517120361Sgad				/*
518120361Sgad				 * If we are just debugging at-times, then
519120361Sgad				 * a detailed message is helpful.  Also
520120361Sgad				 * skip "doing" any commands, since they
521120361Sgad				 * would all be turned off by no-action.
522120361Sgad				 */
523120361Sgad				printf("\n\t--> timematch at %s",
524120361Sgad				    ptimeget_ctime(ent->trim_at));
525130165Sgad				return (free_or_keep);
52643071Swollman			} else if (verbose && ent->hours <= 0) {
52743071Swollman				printf("--> time is up\n");
52843071Swollman			}
52943071Swollman		}
530130165Sgad		if (verbose && (ent->trsize > 0))
531130165Sgad			printf("size (Kb): %d [%d] ", ent->fsize, ent->trsize);
53259003Shm		if (verbose && (ent->hours > 0))
53359003Shm			printf(" age (hr): %d [%d] ", modtime, ent->hours);
534111772Sgad
535111772Sgad		/*
536111772Sgad		 * Figure out if this logfile needs to be rotated.
537111772Sgad		 */
538111772Sgad		temp_reason[0] = '\0';
539111772Sgad		if (rotatereq) {
540111772Sgad			ent->rotate = 1;
541111772Sgad			snprintf(temp_reason, REASON_MAX, " due to -R from %s",
542111772Sgad			    requestor);
543111772Sgad		} else if (force) {
544111772Sgad			ent->rotate = 1;
545111772Sgad			snprintf(temp_reason, REASON_MAX, " due to -F request");
546130165Sgad		} else if ((ent->trsize > 0) && (ent->fsize >= ent->trsize)) {
547111772Sgad			ent->rotate = 1;
548111772Sgad			snprintf(temp_reason, REASON_MAX, " due to size>%dK",
549130165Sgad			    ent->trsize);
550111772Sgad		} else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) {
551111772Sgad			ent->rotate = 1;
552111772Sgad		} else if ((ent->hours > 0) && ((modtime >= ent->hours) ||
553111772Sgad		    (modtime < 0))) {
554111772Sgad			ent->rotate = 1;
555111772Sgad		}
556111772Sgad
557111772Sgad		/*
558111772Sgad		 * If the file needs to be rotated, then rotate it.
559111772Sgad		 */
560111772Sgad		if (ent->rotate) {
561111772Sgad			if (temp_reason[0] != '\0')
562111772Sgad				ent->r_reason = strdup(temp_reason);
56359003Shm			if (verbose)
56459003Shm				printf("--> trimming log....\n");
56559003Shm			if (noaction && !verbose) {
56659003Shm				if (ent->flags & CE_COMPACT)
56759003Shm					printf("%s <%dZ>: trimming\n",
56859003Shm					    ent->log, ent->numlogs);
56980638Sobrien				else if (ent->flags & CE_BZCOMPACT)
57080638Sobrien					printf("%s <%dJ>: trimming\n",
57180638Sobrien					    ent->log, ent->numlogs);
57259003Shm				else
57359003Shm					printf("%s <%d>: trimming\n",
57459003Shm					    ent->log, ent->numlogs);
57559003Shm			}
576130165Sgad			free_or_keep = do_rotate(ent);
57759003Shm		} else {
57859003Shm			if (verbose)
57959003Shm				printf("--> skipping\n");
58059003Shm		}
58159003Shm	}
582130165Sgad	return (free_or_keep);
583111772Sgad#undef REASON_MAX
58413244Sgraichen}
58513244Sgraichen
586112003Sgad/* Send a signal to the pid specified by pidfile */
587112003Sgadstatic int
588112003Sgadsend_signal(const struct conf_entry *ent)
589112003Sgad{
590112003Sgad	pid_t target_pid;
591112003Sgad	int did_notify;
592112003Sgad	FILE *f;
593112003Sgad	long minok, maxok, rval;
594112003Sgad	const char *target_name;
595112003Sgad	char *endp, *linep, line[BUFSIZ];
596112003Sgad
597112003Sgad	did_notify = 0;
598112003Sgad	f = fopen(ent->pid_file, "r");
599112003Sgad	if (f == NULL) {
600112003Sgad		warn("can't open pid file: %s", ent->pid_file);
601112003Sgad		return (did_notify);
602112003Sgad		/* NOTREACHED */
603112003Sgad	}
604112003Sgad
605112003Sgad	if (fgets(line, BUFSIZ, f) == NULL) {
606112003Sgad		/*
607112003Sgad		 * XXX - If the pid file is empty, is that really a
608112003Sgad		 *	problem?  Wouldn't that mean that the process
609112003Sgad		 *	has shut down?  In that case there would be no
610112003Sgad		 *	problem with compressing the rotated log file.
611112003Sgad		 */
612112003Sgad		if (feof(f))
613112003Sgad			warnx("pid file is empty: %s",  ent->pid_file);
614112003Sgad		else
615112003Sgad			warn("can't read from pid file: %s", ent->pid_file);
616112003Sgad		(void) fclose(f);
617112003Sgad		return (did_notify);
618112003Sgad		/* NOTREACHED */
619112003Sgad	}
620112003Sgad	(void) fclose(f);
621112003Sgad
622112003Sgad	target_name = "daemon";
623112003Sgad	minok = MIN_PID;
624112003Sgad	maxok = MAX_PID;
625112003Sgad	if (ent->flags & CE_SIGNALGROUP) {
626112003Sgad		/*
627112003Sgad		 * If we are expected to signal a process-group when
628112003Sgad		 * rotating this logfile, then the value read in should
629112003Sgad		 * be the negative of a valid process ID.
630112003Sgad		 */
631112003Sgad		target_name = "process-group";
632112003Sgad		minok = -MAX_PID;
633112003Sgad		maxok = -MIN_PID;
634112003Sgad	}
635112003Sgad
636112003Sgad	errno = 0;
637112003Sgad	linep = line;
638112003Sgad	while (*linep == ' ')
639112003Sgad		linep++;
640112003Sgad	rval = strtol(linep, &endp, 10);
641112003Sgad	if (*endp != '\0' && !isspacech(*endp)) {
642112003Sgad		warnx("pid file does not start with a valid number: %s",
643112003Sgad		    ent->pid_file);
644112003Sgad		rval = 0;
645112003Sgad	} else if (rval < minok || rval > maxok) {
646112003Sgad		warnx("bad value '%ld' for process number in %s",
647112003Sgad		    rval, ent->pid_file);
648112003Sgad		if (verbose)
649112003Sgad			warnx("\t(expecting value between %ld and %ld)",
650112003Sgad			    minok, maxok);
651112003Sgad		rval = 0;
652112003Sgad	}
653112003Sgad	if (rval == 0) {
654112003Sgad		return (did_notify);
655112003Sgad		/* NOTREACHED */
656112003Sgad	}
657112003Sgad
658112003Sgad	target_pid = rval;
659112003Sgad
660112003Sgad	if (noaction) {
661112003Sgad		did_notify = 1;
662112003Sgad		printf("\tkill -%d %d\n", ent->sig, (int) target_pid);
663112003Sgad	} else if (kill(target_pid, ent->sig)) {
664112003Sgad		/*
665112003Sgad		 * XXX - Iff the error was "no such process", should that
666112003Sgad		 *	really be an error for us?  Perhaps the process
667112003Sgad		 *	is already gone, in which case there would be no
668112003Sgad		 *	problem with compressing the rotated log file.
669112003Sgad		 */
670112003Sgad		warn("can't notify %s, pid %d", target_name,
671112003Sgad		    (int) target_pid);
672112003Sgad	} else {
673112003Sgad		did_notify = 1;
674112003Sgad		if (verbose)
675112003Sgad			printf("%s pid %d notified\n", target_name,
676112003Sgad			    (int) target_pid);
677112003Sgad	}
678112003Sgad
679112003Sgad	return (did_notify);
680112003Sgad}
681112003Sgad
68259004Shmstatic void
683111781Sgadparse_args(int argc, char **argv)
68413244Sgraichen{
685111781Sgad	int ch;
68659003Shm	char *p;
68713244Sgraichen
688120361Sgad	timenow = ptime_init(NULL);
689120361Sgad	ptimeset_time(timenow, time(NULL));
690120361Sgad	(void)strncpy(daytime, ptimeget_ctime(timenow) + 4, 15);
69159003Shm	daytime[15] = '\0';
69213244Sgraichen
69359003Shm	/* Let's get our hostname */
694111781Sgad	(void)gethostname(hostname, sizeof(hostname));
69513244Sgraichen
69613244Sgraichen	/* Truncate domain */
697111781Sgad	if ((p = strchr(hostname, '.')) != NULL)
69813244Sgraichen		*p = '\0';
699111768Sgad
700111768Sgad	/* Parse command line options. */
701136127Sbrooks	while ((ch = getopt(argc, argv, "a:d:f:nrsvCD:FR:")) != -1)
702111781Sgad		switch (ch) {
70359004Shm		case 'a':
70459004Shm			archtodir++;
70559004Shm			archdirname = optarg;
70659004Shm			break;
707136127Sbrooks		case 'd':
708136127Sbrooks			destdir = optarg;
709136127Sbrooks			break;
710111768Sgad		case 'f':
711111768Sgad			conf = optarg;
712111768Sgad			break;
713111768Sgad		case 'n':
714111768Sgad			noaction++;
715111768Sgad			break;
71659003Shm		case 'r':
71759003Shm			needroot = 0;
71859003Shm			break;
719111768Sgad		case 's':
720111768Sgad			nosignal = 1;
721111768Sgad			break;
72259003Shm		case 'v':
72359003Shm			verbose++;
72459003Shm			break;
725114137Sgad		case 'C':
726114137Sgad			/* Useful for things like rc.diskless... */
727114137Sgad			createlogs++;
728114137Sgad			break;
729119904Sgad		case 'D':
730119904Sgad			/*
731119904Sgad			 * Set some debugging option.  The specific option
732119904Sgad			 * depends on the value of optarg.  These options
733119904Sgad			 * may come and go without notice or documentation.
734119904Sgad			 */
735119904Sgad			if (parse_doption(optarg))
736119904Sgad				break;
737119904Sgad			usage();
738119904Sgad			/* NOTREACHED */
73934584Spst		case 'F':
74034584Spst			force++;
74134584Spst			break;
742111772Sgad		case 'R':
743111772Sgad			rotatereq++;
744111772Sgad			requestor = strdup(optarg);
745111772Sgad			break;
746111781Sgad		case 'm':	/* Used by OpenBSD for "monitor mode" */
74759003Shm		default:
74859003Shm			usage();
749111768Sgad			/* NOTREACHED */
75059003Shm		}
751111772Sgad
752111772Sgad	if (rotatereq) {
753111772Sgad		if (optind == argc) {
754111772Sgad			warnx("At least one filename must be given when -R is specified.");
755111772Sgad			usage();
756111772Sgad			/* NOTREACHED */
757111772Sgad		}
758111772Sgad		/* Make sure "requestor" value is safe for a syslog message. */
759111772Sgad		for (p = requestor; *p != '\0'; p++) {
760111772Sgad			if (!isprintch(*p) && (*p != '\t'))
761111772Sgad				*p = '.';
762111772Sgad		}
763111772Sgad	}
764119904Sgad
765119904Sgad	if (dbg_timenow) {
766119904Sgad		/*
767119904Sgad		 * Note that the 'daytime' variable is not changed.
768119904Sgad		 * That is only used in messages that track when a
769119904Sgad		 * logfile is rotated, and if a file *is* rotated,
770119904Sgad		 * then it will still rotated at the "real now" time.
771119904Sgad		 */
772120361Sgad		ptime_free(timenow);
773119904Sgad		timenow = dbg_timenow;
774119904Sgad		fprintf(stderr, "Debug: Running as if TimeNow is %s",
775120361Sgad		    ptimeget_ctime(dbg_timenow));
776119904Sgad	}
777119904Sgad
77843071Swollman}
77913244Sgraichen
780120361Sgad/*
781120361Sgad * These debugging options are mainly meant for developer use, such
782120361Sgad * as writing regression-tests.  They would not be needed by users
783120361Sgad * during normal operation of newsyslog...
784120361Sgad */
785119904Sgadstatic int
786119904Sgadparse_doption(const char *doption)
787119904Sgad{
788119904Sgad	const char TN[] = "TN=";
789120361Sgad	int res;
790119904Sgad
791119904Sgad	if (strncmp(doption, TN, sizeof(TN) - 1) == 0) {
792119904Sgad		/*
793120361Sgad		 * The "TimeNow" debugging option.  This might be off
794120361Sgad		 * by an hour when crossing a timezone change.
795119904Sgad		 */
796120361Sgad		dbg_timenow = ptime_init(NULL);
797120361Sgad		res = ptime_relparse(dbg_timenow, PTM_PARSE_ISO8601,
798120361Sgad		    time(NULL), doption + sizeof(TN) - 1);
799120361Sgad		if (res == -2) {
800120361Sgad			warnx("Non-existent time specified on -D %s", doption);
801120361Sgad			return (0);			/* failure */
802120361Sgad		} else if (res < 0) {
803119904Sgad			warnx("Malformed time given on -D %s", doption);
804119904Sgad			return (0);			/* failure */
805119904Sgad		}
806119904Sgad		return (1);			/* successfully parsed */
807119904Sgad
808119904Sgad	}
809119904Sgad
810120361Sgad	if (strcmp(doption, "ats") == 0) {
811120361Sgad		dbg_at_times++;
812120361Sgad		return (1);			/* successfully parsed */
813120361Sgad	}
814120361Sgad
815130167Sgad	if (strcmp(doption, "neworder") == 0) {
816130167Sgad#ifdef TRY_NEWORDER
817130167Sgad		dbg_new_order++;
818130167Sgad#else
819130167Sgad		warnx("NOTE: The code for 'neworder' was not compiled in.");
820130167Sgad#endif
821130167Sgad		return (1);			/* successfully parsed */
822130167Sgad	}
823130205Sgad	if (strcmp(doption, "oldorder") == 0) {
824130205Sgad#ifdef TRY_NEWORDER
825130205Sgad		dbg_new_order = 0;
826130205Sgad#else
827130205Sgad		warnx("NOTE: The code for 'neworder' was not compiled in.");
828130205Sgad#endif
829130205Sgad		return (1);			/* successfully parsed */
830130205Sgad	}
831130167Sgad
832130165Sgad	warnx("Unknown -D (debug) option: '%s'", doption);
833119904Sgad	return (0);				/* failure */
834119904Sgad}
835119904Sgad
83659004Shmstatic void
83759004Shmusage(void)
83813244Sgraichen{
83980646Sobrien
84080646Sobrien	fprintf(stderr,
841136186Sbrooks	    "usage: newsyslog [-CFnrsv] [-a directory] [-d directory] [-f config-file]\n"
842111772Sgad	    "                 [ [-R requestor] filename ... ]\n");
84359003Shm	exit(1);
84413244Sgraichen}
84513244Sgraichen
84659004Shm/*
847111773Sgad * Parse a configuration file and return a linked list of all the logs
848111773Sgad * which should be processed.
84913244Sgraichen */
85059003Shmstatic struct conf_entry *
851111773Sgadget_worklist(char **files)
85213244Sgraichen{
85359003Shm	FILE *f;
854111773Sgad	const char *fname;
855111773Sgad	char **given;
856111773Sgad	struct conf_entry *defconf, *dupent, *ent, *firstnew;
857112020Sgad	struct conf_entry *globlist, *lastnew, *worklist;
858112020Sgad	int gmatch, fnres;
859111773Sgad
860112020Sgad	defconf = globlist = worklist = NULL;
861111773Sgad
862111773Sgad	fname = conf;
863111773Sgad	if (fname == NULL)
864111773Sgad		fname = _PATH_CONF;
865111773Sgad
866111773Sgad	if (strcmp(fname, "-") != 0)
867111773Sgad		f = fopen(fname, "r");
868111773Sgad	else {
869111773Sgad		f = stdin;
870111773Sgad		fname = "<stdin>";
871111773Sgad	}
872111773Sgad	if (!f)
873111773Sgad		err(1, "%s", conf);
874111773Sgad
875112020Sgad	parse_file(f, fname, &worklist, &globlist, &defconf);
876111773Sgad	(void) fclose(f);
877111773Sgad
878111773Sgad	/*
879111773Sgad	 * All config-file information has been read in and turned into
880112020Sgad	 * a worklist and a globlist.  If there were no specific files
881112020Sgad	 * given on the run command, then the only thing left to do is to
882112020Sgad	 * call a routine which finds all files matched by the globlist
883112020Sgad	 * and adds them to the worklist.  Then return the worklist.
884111773Sgad	 */
885111773Sgad	if (*files == NULL) {
886112020Sgad		expand_globs(&worklist, &globlist);
887112020Sgad		free_clist(&globlist);
888111773Sgad		if (defconf != NULL)
889111773Sgad			free_entry(defconf);
890111773Sgad		return (worklist);
891111773Sgad		/* NOTREACHED */
892111773Sgad	}
893111773Sgad
894111773Sgad	/*
895111773Sgad	 * If newsyslog was given a specific list of files to process,
896111773Sgad	 * it may be that some of those files were not listed in any
897111773Sgad	 * config file.  Those unlisted files should get the default
898111773Sgad	 * rotation action.  First, create the default-rotation action
899111773Sgad	 * if none was found in a system config file.
900111773Sgad	 */
901111773Sgad	if (defconf == NULL) {
902111773Sgad		defconf = init_entry(DEFAULT_MARKER, NULL);
903111773Sgad		defconf->numlogs = 3;
904130165Sgad		defconf->trsize = 50;
905111773Sgad		defconf->permissions = S_IRUSR|S_IWUSR;
906111773Sgad	}
907111773Sgad
908111773Sgad	/*
909111773Sgad	 * If newsyslog was run with a list of specific filenames,
910111773Sgad	 * then create a new worklist which has only those files in
911111773Sgad	 * it, picking up the rotation-rules for those files from
912111773Sgad	 * the original worklist.
913111773Sgad	 *
914111773Sgad	 * XXX - Note that this will copy multiple rules for a single
915111773Sgad	 *	logfile, if multiple entries are an exact match for
916111773Sgad	 *	that file.  That matches the historic behavior, but do
917111773Sgad	 *	we want to continue to allow it?  If so, it should
918111773Sgad	 *	probably be handled more intelligently.
919111773Sgad	 */
920112020Sgad	firstnew = lastnew = NULL;
921111773Sgad	for (given = files; *given; ++given) {
922111773Sgad		/*
923111773Sgad		 * First try to find exact-matches for this given file.
924111773Sgad		 */
925112020Sgad		gmatch = 0;
926111773Sgad		for (ent = worklist; ent; ent = ent->next) {
927111773Sgad			if (strcmp(ent->log, *given) == 0) {
928111773Sgad				gmatch++;
929111773Sgad				dupent = init_entry(*given, ent);
930111773Sgad				if (!firstnew)
931111773Sgad					firstnew = dupent;
932111773Sgad				else
933112020Sgad					lastnew->next = dupent;
934112020Sgad				lastnew = dupent;
935111773Sgad			}
936111773Sgad		}
937111773Sgad		if (gmatch) {
938111773Sgad			if (verbose > 2)
939111773Sgad				printf("\t+ Matched entry %s\n", *given);
940111773Sgad			continue;
941111773Sgad		}
942111773Sgad
943111773Sgad		/*
944111773Sgad		 * There was no exact-match for this given file, so look
945111773Sgad		 * for a "glob" entry which does match.
946111773Sgad		 */
947112020Sgad		gmatch = 0;
948112020Sgad		if (verbose > 2 && globlist != NULL)
949112020Sgad			printf("\t+ Checking globs for %s\n", *given);
950112020Sgad		for (ent = globlist; ent; ent = ent->next) {
951112020Sgad			fnres = fnmatch(ent->log, *given, FNM_PATHNAME);
952112020Sgad			if (verbose > 2)
953112020Sgad				printf("\t+    = %d for pattern %s\n", fnres,
954112020Sgad				    ent->log);
955112020Sgad			if (fnres == 0) {
956111773Sgad				gmatch++;
957111773Sgad				dupent = init_entry(*given, ent);
958111773Sgad				if (!firstnew)
959111773Sgad					firstnew = dupent;
960111773Sgad				else
961112020Sgad					lastnew->next = dupent;
962112020Sgad				lastnew = dupent;
963112020Sgad				/* This new entry is not a glob! */
964111773Sgad				dupent->flags &= ~CE_GLOB;
965111773Sgad				/* Only allow a match to one glob-entry */
966111773Sgad				break;
967111773Sgad			}
968111773Sgad		}
969111773Sgad		if (gmatch) {
970111773Sgad			if (verbose > 2)
971111773Sgad				printf("\t+ Matched %s via %s\n", *given,
972111773Sgad				    ent->log);
973111773Sgad			continue;
974111773Sgad		}
975111773Sgad
976111773Sgad		/*
977111773Sgad		 * This given file was not found in any config file, so
978111773Sgad		 * add a worklist item based on the default entry.
979111773Sgad		 */
980111773Sgad		if (verbose > 2)
981111773Sgad			printf("\t+ No entry matched %s  (will use %s)\n",
982111773Sgad			    *given, DEFAULT_MARKER);
983111773Sgad		dupent = init_entry(*given, defconf);
984111773Sgad		if (!firstnew)
985111773Sgad			firstnew = dupent;
986111773Sgad		else
987112020Sgad			lastnew->next = dupent;
988111773Sgad		/* Mark that it was *not* found in a config file */
989111773Sgad		dupent->def_cfg = 1;
990112020Sgad		lastnew = dupent;
991111773Sgad	}
992111773Sgad
993111773Sgad	/*
994112020Sgad	 * Free all the entries in the original work list, the list of
995112020Sgad	 * glob entries, and the default entry.
996111773Sgad	 */
997112020Sgad	free_clist(&worklist);
998112020Sgad	free_clist(&globlist);
999112020Sgad	free_entry(defconf);
1000111773Sgad
1001112020Sgad	/* And finally, return a worklist which matches the given files. */
1002112013Sgad	return (firstnew);
1003111773Sgad}
1004111773Sgad
1005111773Sgad/*
1006112020Sgad * Expand the list of entries with filename patterns, and add all files
1007112020Sgad * which match those glob-entries onto the worklist.
1008112020Sgad */
1009112020Sgadstatic void
1010112020Sgadexpand_globs(struct conf_entry **work_p, struct conf_entry **glob_p)
1011112020Sgad{
1012112020Sgad	int gmatch, gres, i;
1013112020Sgad	char *mfname;
1014112020Sgad	struct conf_entry *dupent, *ent, *firstmatch, *globent;
1015112020Sgad	struct conf_entry *lastmatch;
1016112020Sgad	glob_t pglob;
1017112020Sgad	struct stat st_fm;
1018112020Sgad
1019112020Sgad	if ((glob_p == NULL) || (*glob_p == NULL))
1020112020Sgad		return;			/* There is nothing to do. */
1021112020Sgad
1022112020Sgad	/*
1023112020Sgad	 * The worklist contains all fully-specified (non-GLOB) names.
1024112020Sgad	 *
1025112020Sgad	 * Now expand the list of filename-pattern (GLOB) entries into
1026112020Sgad	 * a second list, which (by definition) will only match files
1027112020Sgad	 * that already exist.  Do not add a glob-related entry for any
1028112020Sgad	 * file which already exists in the fully-specified list.
1029112020Sgad	 */
1030112020Sgad	firstmatch = lastmatch = NULL;
1031112020Sgad	for (globent = *glob_p; globent; globent = globent->next) {
1032112020Sgad
1033112020Sgad		gres = glob(globent->log, GLOB_NOCHECK, NULL, &pglob);
1034112020Sgad		if (gres != 0) {
1035112020Sgad			warn("cannot expand pattern (%d): %s", gres,
1036112020Sgad			    globent->log);
1037112020Sgad			continue;
1038112020Sgad		}
1039112020Sgad
1040112020Sgad		if (verbose > 2)
1041112020Sgad			printf("\t+ Expanding pattern %s\n", globent->log);
1042112020Sgad		for (i = 0; i < pglob.gl_matchc; i++) {
1043112020Sgad			mfname = pglob.gl_pathv[i];
1044112020Sgad
1045112020Sgad			/* See if this file already has a specific entry. */
1046112020Sgad			gmatch = 0;
1047112020Sgad			for (ent = *work_p; ent; ent = ent->next) {
1048112020Sgad				if (strcmp(mfname, ent->log) == 0) {
1049112020Sgad					gmatch++;
1050112020Sgad					break;
1051112020Sgad				}
1052112020Sgad			}
1053112020Sgad			if (gmatch)
1054112020Sgad				continue;
1055112020Sgad
1056112020Sgad			/* Make sure the named matched is a file. */
1057112020Sgad			gres = lstat(mfname, &st_fm);
1058112020Sgad			if (gres != 0) {
1059112020Sgad				/* Error on a file that glob() matched?!? */
1060112020Sgad				warn("Skipping %s - lstat() error", mfname);
1061112020Sgad				continue;
1062112020Sgad			}
1063112020Sgad			if (!S_ISREG(st_fm.st_mode)) {
1064112020Sgad				/* We only rotate files! */
1065112020Sgad				if (verbose > 2)
1066112020Sgad					printf("\t+  . skipping %s (!file)\n",
1067112020Sgad					    mfname);
1068112020Sgad				continue;
1069112020Sgad			}
1070112020Sgad
1071112020Sgad			if (verbose > 2)
1072112020Sgad				printf("\t+  . add file %s\n", mfname);
1073112020Sgad			dupent = init_entry(mfname, globent);
1074112020Sgad			if (!firstmatch)
1075112020Sgad				firstmatch = dupent;
1076112020Sgad			else
1077112020Sgad				lastmatch->next = dupent;
1078112020Sgad			lastmatch = dupent;
1079112020Sgad			/* This new entry is not a glob! */
1080112020Sgad			dupent->flags &= ~CE_GLOB;
1081112020Sgad		}
1082112020Sgad		globfree(&pglob);
1083112020Sgad		if (verbose > 2)
1084112020Sgad			printf("\t+ Done with pattern %s\n", globent->log);
1085112020Sgad	}
1086112020Sgad
1087112020Sgad	/* Add the list of matched files to the end of the worklist. */
1088112020Sgad	if (!*work_p)
1089112020Sgad		*work_p = firstmatch;
1090112020Sgad	else {
1091112020Sgad		ent = *work_p;
1092112020Sgad		while (ent->next)
1093112020Sgad			ent = ent->next;
1094112020Sgad		ent->next = firstmatch;
1095112020Sgad	}
1096112020Sgad
1097112020Sgad}
1098112020Sgad
1099112020Sgad/*
1100111773Sgad * Parse a configuration file and update a linked list of all the logs to
1101111773Sgad * process.
1102111773Sgad */
1103111773Sgadstatic void
1104111773Sgadparse_file(FILE *cf, const char *cfname, struct conf_entry **work_p,
1105112020Sgad    struct conf_entry **glob_p, struct conf_entry **defconf_p)
1106111773Sgad{
110759003Shm	char line[BUFSIZ], *parse, *q;
1108107737Ssobomax	char *cp, *errline, *group;
1109112020Sgad	struct conf_entry *lastglob, *lastwork, *working;
1110111781Sgad	struct passwd *pwd;
111159003Shm	struct group *grp;
1112120361Sgad	int eol, ptm_opts, res, special;
111313244Sgraichen
1114111773Sgad	/*
1115111773Sgad	 * XXX - for now, assume that only one config file will be read,
1116111773Sgad	 *	ie, this routine is only called one time.
1117111773Sgad	 */
1118112020Sgad	lastglob = lastwork = NULL;
111980646Sobrien
1120130165Sgad	errline = NULL;
1121111773Sgad	while (fgets(line, BUFSIZ, cf)) {
1122107737Ssobomax		if ((line[0] == '\n') || (line[0] == '#') ||
1123107737Ssobomax		    (strlen(line) == 0))
112459003Shm			continue;
1125130165Sgad		if (errline != NULL)
1126130165Sgad			free(errline);
112759003Shm		errline = strdup(line);
1128107737Ssobomax		for (cp = line + 1; *cp != '\0'; cp++) {
1129107737Ssobomax			if (*cp != '#')
1130107737Ssobomax				continue;
1131107737Ssobomax			if (*(cp - 1) == '\\') {
1132107737Ssobomax				strcpy(cp - 1, cp);
1133107737Ssobomax				cp--;
1134107737Ssobomax				continue;
1135107737Ssobomax			}
1136107737Ssobomax			*cp = '\0';
1137107737Ssobomax			break;
1138107737Ssobomax		}
113960373Sdes
114060373Sdes		q = parse = missing_field(sob(line), errline);
114160373Sdes		parse = son(line);
114260373Sdes		if (!*parse)
114380646Sobrien			errx(1, "malformed line (missing fields):\n%s",
114480646Sobrien			    errline);
114560373Sdes		*parse = '\0';
114660373Sdes
1147130165Sgad		/*
1148130165Sgad		 * Allow people to set debug options via the config file.
1149130165Sgad		 * (NOTE: debug optons are undocumented, and may disappear
1150130165Sgad		 * at any time, etc).
1151130165Sgad		 */
1152130165Sgad		if (strcasecmp(DEBUG_MARKER, q) == 0) {
1153130165Sgad			q = parse = missing_field(sob(++parse), errline);
1154130165Sgad			parse = son(parse);
1155130165Sgad			if (!*parse)
1156130165Sgad				warnx("debug line specifies no option:\n%s",
1157130165Sgad				    errline);
1158130165Sgad			else {
1159130165Sgad				*parse = '\0';
1160130165Sgad				parse_doption(q);
1161130165Sgad			}
1162130165Sgad			continue;
1163130165Sgad		}
1164130165Sgad
1165112020Sgad		special = 0;
1166111388Sgad		working = init_entry(q, NULL);
1167111388Sgad		if (strcasecmp(DEFAULT_MARKER, q) == 0) {
1168112020Sgad			special = 1;
1169111773Sgad			if (defconf_p == NULL) {
1170111773Sgad				warnx("Ignoring entry for %s in %s!", q,
1171111773Sgad				    cfname);
1172111773Sgad				free_entry(working);
1173111773Sgad				continue;
1174111773Sgad			} else if (*defconf_p != NULL) {
1175111388Sgad				warnx("Ignoring duplicate entry for %s!", q);
1176111388Sgad				free_entry(working);
1177111388Sgad				continue;
1178111388Sgad			}
1179111773Sgad			*defconf_p = working;
118059003Shm		}
118113244Sgraichen
118259003Shm		q = parse = missing_field(sob(++parse), errline);
118359003Shm		parse = son(parse);
118425518Sbrian		if (!*parse)
118580646Sobrien			errx(1, "malformed line (missing fields):\n%s",
118680646Sobrien			    errline);
118759003Shm		*parse = '\0';
118859003Shm		if ((group = strchr(q, ':')) != NULL ||
118959003Shm		    (group = strrchr(q, '.')) != NULL) {
119059003Shm			*group++ = '\0';
119159003Shm			if (*q) {
1192119102Sgad				if (!(isnumberstr(q))) {
1193111781Sgad					if ((pwd = getpwnam(q)) == NULL)
119459003Shm						errx(1,
119580646Sobrien				     "error in config file; unknown user:\n%s",
119659003Shm						    errline);
1197111781Sgad					working->uid = pwd->pw_uid;
119859003Shm				} else
119959003Shm					working->uid = atoi(q);
120059003Shm			} else
1201111779Sgad				working->uid = (uid_t)-1;
120213244Sgraichen
120359003Shm			q = group;
120459003Shm			if (*q) {
1205119102Sgad				if (!(isnumberstr(q))) {
120659003Shm					if ((grp = getgrnam(q)) == NULL)
120759003Shm						errx(1,
120880646Sobrien				    "error in config file; unknown group:\n%s",
120959003Shm						    errline);
121059003Shm					working->gid = grp->gr_gid;
121159003Shm				} else
121259003Shm					working->gid = atoi(q);
121359003Shm			} else
1214111779Sgad				working->gid = (gid_t)-1;
121513244Sgraichen
121659003Shm			q = parse = missing_field(sob(++parse), errline);
121759003Shm			parse = son(parse);
121859003Shm			if (!*parse)
121980646Sobrien				errx(1, "malformed line (missing fields):\n%s",
122080646Sobrien				    errline);
122159003Shm			*parse = '\0';
1222111779Sgad		} else {
1223111779Sgad			working->uid = (uid_t)-1;
1224111779Sgad			working->gid = (gid_t)-1;
1225111779Sgad		}
122659003Shm
122759003Shm		if (!sscanf(q, "%o", &working->permissions))
122859003Shm			errx(1, "error in config file; bad permissions:\n%s",
122959003Shm			    errline);
123059003Shm
123159003Shm		q = parse = missing_field(sob(++parse), errline);
123259003Shm		parse = son(parse);
123325518Sbrian		if (!*parse)
123480646Sobrien			errx(1, "malformed line (missing fields):\n%s",
123580646Sobrien			    errline);
123659003Shm		*parse = '\0';
1237111400Sgad		if (!sscanf(q, "%d", &working->numlogs) || working->numlogs < 0)
1238111400Sgad			errx(1, "error in config file; bad value for count of logs to save:\n%s",
123959003Shm			    errline);
124013244Sgraichen
124159003Shm		q = parse = missing_field(sob(++parse), errline);
124259003Shm		parse = son(parse);
124325518Sbrian		if (!*parse)
124480646Sobrien			errx(1, "malformed line (missing fields):\n%s",
124580646Sobrien			    errline);
124659003Shm		*parse = '\0';
1247114762Sgad		if (isdigitch(*q))
1248130165Sgad			working->trsize = atoi(q);
1249130165Sgad		else if (strcmp(q, "*") == 0)
1250130165Sgad			working->trsize = -1;
1251114762Sgad		else {
1252114762Sgad			warnx("Invalid value of '%s' for 'size' in line:\n%s",
1253114762Sgad			    q, errline);
1254130165Sgad			working->trsize = -1;
1255114762Sgad		}
125659003Shm
125759003Shm		working->flags = 0;
125859003Shm		q = parse = missing_field(sob(++parse), errline);
125959003Shm		parse = son(parse);
126025518Sbrian		eol = !*parse;
126159003Shm		*parse = '\0';
126243071Swollman		{
126359003Shm			char *ep;
126459003Shm			u_long ul;
126513244Sgraichen
126643071Swollman			ul = strtoul(q, &ep, 10);
126743071Swollman			if (ep == q)
126843071Swollman				working->hours = 0;
126943071Swollman			else if (*ep == '*')
127043071Swollman				working->hours = -1;
127143071Swollman			else if (ul > INT_MAX)
127243071Swollman				errx(1, "interval is too large:\n%s", errline);
127343071Swollman			else
127443071Swollman				working->hours = ul;
127543071Swollman
1276120361Sgad			if (*ep == '\0' || strcmp(ep, "*") == 0)
1277120361Sgad				goto no_trimat;
1278120361Sgad			if (*ep != '@' && *ep != '$')
127943071Swollman				errx(1, "malformed interval/at:\n%s", errline);
1280120361Sgad
1281120361Sgad			working->flags |= CE_TRIMAT;
1282120361Sgad			working->trim_at = ptime_init(NULL);
1283120361Sgad			ptm_opts = PTM_PARSE_ISO8601;
1284120361Sgad			if (*ep == '$')
1285120361Sgad				ptm_opts = PTM_PARSE_DWM;
1286120361Sgad			ptm_opts |= PTM_PARSE_MATCHDOM;
1287120361Sgad			res = ptime_relparse(working->trim_at, ptm_opts,
1288120361Sgad			    ptimeget_secs(timenow), ep + 1);
1289120361Sgad			if (res == -2)
1290120361Sgad				errx(1, "nonexistent time for 'at' value:\n%s",
1291120361Sgad				    errline);
1292120361Sgad			else if (res < 0)
1293120361Sgad				errx(1, "malformed 'at' value:\n%s", errline);
129443071Swollman		}
1295120361Sgadno_trimat:
129643071Swollman
129725518Sbrian		if (eol)
129859003Shm			q = NULL;
129925518Sbrian		else {
130059003Shm			q = parse = sob(++parse);	/* Optional field */
130159003Shm			parse = son(parse);
130259003Shm			if (!*parse)
130359003Shm				eol = 1;
130459003Shm			*parse = '\0';
130525518Sbrian		}
130625443Sache
1307111768Sgad		for (; q && *q && !isspacech(*q); q++) {
1308111768Sgad			switch (tolowerch(*q)) {
1309111768Sgad			case 'b':
131059003Shm				working->flags |= CE_BINARY;
1311111768Sgad				break;
1312114137Sgad			case 'c':
1313111768Sgad				/*
1314114137Sgad				 * XXX - 	Ick! Ugly! Remove ASAP!
1315114137Sgad				 * We want `c' and `C' for "create".  But we
1316114137Sgad				 * will temporarily treat `c' as `g', because
1317114137Sgad				 * FreeBSD releases <= 4.8 have a typo of
1318114137Sgad				 * checking  ('G' || 'c')  for CE_GLOB.
1319111768Sgad				 */
1320114137Sgad				if (*q == 'c') {
1321114137Sgad					warnx("Assuming 'g' for 'c' in flags for line:\n%s",
1322114137Sgad					    errline);
1323114137Sgad					warnx("The 'c' flag will eventually mean 'CREATE'");
1324114137Sgad					working->flags |= CE_GLOB;
1325114137Sgad					break;
1326114137Sgad				}
1327114137Sgad				working->flags |= CE_CREATE;
1328114137Sgad				break;
1329130043Sgad			case 'd':
1330130043Sgad				working->flags |= CE_NODUMP;
1331130043Sgad				break;
1332111768Sgad			case 'g':
1333106905Ssobomax				working->flags |= CE_GLOB;
1334111768Sgad				break;
1335111768Sgad			case 'j':
1336111768Sgad				working->flags |= CE_BZCOMPACT;
1337111768Sgad				break;
1338111768Sgad			case 'n':
1339111768Sgad				working->flags |= CE_NOSIGNAL;
1340111768Sgad				break;
1341112003Sgad			case 'u':
1342112003Sgad				working->flags |= CE_SIGNALGROUP;
1343112003Sgad				break;
1344111768Sgad			case 'w':
1345107916Ssobomax				working->flags |= CE_COMPACTWAIT;
1346111768Sgad				break;
1347111768Sgad			case 'z':
1348111768Sgad				working->flags |= CE_COMPACT;
1349111768Sgad				break;
1350111768Sgad			case '-':
1351111768Sgad				break;
1352111781Sgad			case 'f':	/* Used by OpenBSD for "CE_FOLLOW" */
1353111781Sgad			case 'm':	/* Used by OpenBSD for "CE_MONITOR" */
1354111781Sgad			case 'p':	/* Used by NetBSD  for "CE_PLAIN0" */
1355111768Sgad			default:
135680646Sobrien				errx(1, "illegal flag in config file -- %c",
135780646Sobrien				    *q);
1358111768Sgad			}
135959003Shm		}
136059003Shm
136125518Sbrian		if (eol)
136259003Shm			q = NULL;
136325518Sbrian		else {
136459003Shm			q = parse = sob(++parse);	/* Optional field */
136559003Shm			parse = son(parse);
136659003Shm			if (!*parse)
136759003Shm				eol = 1;
136859003Shm			*parse = '\0';
136925518Sbrian		}
137025443Sache
137125443Sache		working->pid_file = NULL;
137225443Sache		if (q && *q) {
137325443Sache			if (*q == '/')
137425443Sache				working->pid_file = strdup(q);
137536817Sache			else if (isdigit(*q))
137636817Sache				goto got_sig;
137759003Shm			else
137880646Sobrien				errx(1,
137980646Sobrien			"illegal pid file or signal number in config file:\n%s",
138080646Sobrien				    errline);
138125443Sache		}
138236817Sache		if (eol)
138359003Shm			q = NULL;
138436817Sache		else {
138559003Shm			q = parse = sob(++parse);	/* Optional field */
138659003Shm			*(parse = son(parse)) = '\0';
138736817Sache		}
138836817Sache
138936817Sache		working->sig = SIGHUP;
139036817Sache		if (q && *q) {
139136817Sache			if (isdigit(*q)) {
139259003Shm		got_sig:
139336817Sache				working->sig = atoi(q);
139436817Sache			} else {
139559003Shm		err_sig:
139680646Sobrien				errx(1,
139780646Sobrien				    "illegal signal number in config file:\n%s",
139880646Sobrien				    errline);
139936817Sache			}
140036817Sache			if (working->sig < 1 || working->sig >= NSIG)
140136817Sache				goto err_sig;
140236817Sache		}
1403111768Sgad
1404111768Sgad		/*
1405111768Sgad		 * Finish figuring out what pid-file to use (if any) in
1406111768Sgad		 * later processing if this logfile needs to be rotated.
1407111768Sgad		 */
1408111768Sgad		if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) {
1409111768Sgad			/*
1410111768Sgad			 * This config-entry specified 'n' for nosignal,
1411111768Sgad			 * see if it also specified an explicit pid_file.
1412111768Sgad			 * This would be a pretty pointless combination.
1413111768Sgad			 */
1414111768Sgad			if (working->pid_file != NULL) {
1415111768Sgad				warnx("Ignoring '%s' because flag 'n' was specified in line:\n%s",
1416111768Sgad				    working->pid_file, errline);
1417111768Sgad				free(working->pid_file);
1418111768Sgad				working->pid_file = NULL;
1419111768Sgad			}
1420111768Sgad		} else if (working->pid_file == NULL) {
1421111768Sgad			/*
1422111768Sgad			 * This entry did not specify the 'n' flag, which
1423111768Sgad			 * means it should signal syslogd unless it had
1424112003Sgad			 * specified some other pid-file (and obviously the
1425112003Sgad			 * syslog pid-file will not be for a process-group).
1426112003Sgad			 * Also, we should only try to notify syslog if we
1427112003Sgad			 * are root.
1428111768Sgad			 */
1429112003Sgad			if (working->flags & CE_SIGNALGROUP) {
1430112003Sgad				warnx("Ignoring flag 'U' in line:\n%s",
1431112003Sgad				    errline);
1432112003Sgad				working->flags &= ~CE_SIGNALGROUP;
1433112003Sgad			}
1434111768Sgad			if (needroot)
1435111768Sgad				working->pid_file = strdup(_PATH_SYSLOGPID);
1436111768Sgad		}
1437111768Sgad
1438112020Sgad		/*
1439112020Sgad		 * Add this entry to the appropriate list of entries, unless
1440112020Sgad		 * it was some kind of special entry (eg: <default>).
1441112020Sgad		 */
1442112020Sgad		if (special) {
1443112020Sgad			;			/* Do not add to any list */
1444112020Sgad		} else if (working->flags & CE_GLOB) {
1445112020Sgad			if (!*glob_p)
1446112020Sgad				*glob_p = working;
1447112020Sgad			else
1448112020Sgad				lastglob->next = working;
1449112020Sgad			lastglob = working;
1450112020Sgad		} else {
1451112020Sgad			if (!*work_p)
1452112020Sgad				*work_p = working;
1453112020Sgad			else
1454112020Sgad				lastwork->next = working;
1455112020Sgad			lastwork = working;
1456112020Sgad		}
1457130165Sgad	}
1458130165Sgad	if (errline != NULL)
145959003Shm		free(errline);
146013244Sgraichen}
146113244Sgraichen
146259003Shmstatic char *
146359004Shmmissing_field(char *p, char *errline)
146413244Sgraichen{
146580646Sobrien
146659003Shm	if (!p || !*p)
146759003Shm		errx(1, "missing field in config file:\n%s", errline);
146859003Shm	return (p);
146913244Sgraichen}
147013244Sgraichen
1471130165Sgadstatic fk_entry
1472130165Sgaddo_rotate(const struct conf_entry *ent)
147313244Sgraichen{
147471299Sjedgar	char dirpart[MAXPATHLEN], namepart[MAXPATHLEN];
147571299Sjedgar	char file1[MAXPATHLEN], file2[MAXPATHLEN];
147671299Sjedgar	char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN];
147780638Sobrien	char jfile1[MAXPATHLEN];
1478130038Sgad	int flags, notified, need_notification, numlogs_c;
1479130165Sgad	fk_entry free_or_keep;
148059003Shm	struct stat st;
148113244Sgraichen
1482119927Sgad	flags = ent->flags;
1483130165Sgad	free_or_keep = FREE_ENT;
1484119927Sgad
148559004Shm	if (archtodir) {
148659004Shm		char *p;
148713244Sgraichen
148859004Shm		/* build complete name of archive directory into dirpart */
148959004Shm		if (*archdirname == '/') {	/* absolute */
149071299Sjedgar			strlcpy(dirpart, archdirname, sizeof(dirpart));
149159004Shm		} else {	/* relative */
149259004Shm			/* get directory part of logfile */
1493119927Sgad			strlcpy(dirpart, ent->log, sizeof(dirpart));
149459004Shm			if ((p = rindex(dirpart, '/')) == NULL)
149559004Shm				dirpart[0] = '\0';
149659004Shm			else
149759004Shm				*(p + 1) = '\0';
149871299Sjedgar			strlcat(dirpart, archdirname, sizeof(dirpart));
149959004Shm		}
150059004Shm
150159004Shm		/* check if archive directory exists, if not, create it */
150259004Shm		if (lstat(dirpart, &st))
1503114137Sgad			createdir(ent, dirpart);
150459004Shm
150559004Shm		/* get filename part of logfile */
1506119927Sgad		if ((p = rindex(ent->log, '/')) == NULL)
1507119927Sgad			strlcpy(namepart, ent->log, sizeof(namepart));
150859004Shm		else
150971299Sjedgar			strlcpy(namepart, p + 1, sizeof(namepart));
151059004Shm
151159004Shm		/* name of oldest log */
151280646Sobrien		(void) snprintf(file1, sizeof(file1), "%s/%s.%d", dirpart,
1513119927Sgad		    namepart, ent->numlogs);
151471299Sjedgar		(void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
151571299Sjedgar		    COMPRESS_POSTFIX);
151680638Sobrien		snprintf(jfile1, sizeof(jfile1), "%s%s", file1,
151780638Sobrien		    BZCOMPRESS_POSTFIX);
151859004Shm	} else {
151959004Shm		/* name of oldest log */
1520119927Sgad		(void) snprintf(file1, sizeof(file1), "%s.%d", ent->log,
1521119927Sgad		    ent->numlogs);
152271299Sjedgar		(void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
152371299Sjedgar		    COMPRESS_POSTFIX);
152480638Sobrien		snprintf(jfile1, sizeof(jfile1), "%s%s", file1,
152580638Sobrien		    BZCOMPRESS_POSTFIX);
152659004Shm	}
152759004Shm
152859003Shm	if (noaction) {
1529111967Sgad		printf("\trm -f %s\n", file1);
1530111967Sgad		printf("\trm -f %s\n", zfile1);
1531111967Sgad		printf("\trm -f %s\n", jfile1);
153259003Shm	} else {
153359003Shm		(void) unlink(file1);
153459003Shm		(void) unlink(zfile1);
153580638Sobrien		(void) unlink(jfile1);
153659003Shm	}
153713244Sgraichen
153859003Shm	/* Move down log files */
1539119927Sgad	numlogs_c = ent->numlogs;		/* copy for countdown */
1540119927Sgad	while (numlogs_c--) {
154159004Shm
154271299Sjedgar		(void) strlcpy(file2, file1, sizeof(file2));
154359004Shm
154459004Shm		if (archtodir)
154580646Sobrien			(void) snprintf(file1, sizeof(file1), "%s/%s.%d",
1546119927Sgad			    dirpart, namepart, numlogs_c);
154759004Shm		else
1548119927Sgad			(void) snprintf(file1, sizeof(file1), "%s.%d",
1549119927Sgad			    ent->log, numlogs_c);
155059004Shm
155171299Sjedgar		(void) strlcpy(zfile1, file1, sizeof(zfile1));
155271299Sjedgar		(void) strlcpy(zfile2, file2, sizeof(zfile2));
155359003Shm		if (lstat(file1, &st)) {
155480646Sobrien			(void) strlcat(zfile1, COMPRESS_POSTFIX,
155580646Sobrien			    sizeof(zfile1));
155680646Sobrien			(void) strlcat(zfile2, COMPRESS_POSTFIX,
155780646Sobrien			    sizeof(zfile2));
155880638Sobrien			if (lstat(zfile1, &st)) {
155980638Sobrien				strlcpy(zfile1, file1, sizeof(zfile1));
156080638Sobrien				strlcpy(zfile2, file2, sizeof(zfile2));
156180638Sobrien				strlcat(zfile1, BZCOMPRESS_POSTFIX,
156280638Sobrien				    sizeof(zfile1));
156380638Sobrien				strlcat(zfile2, BZCOMPRESS_POSTFIX,
156480638Sobrien				    sizeof(zfile2));
156580638Sobrien				if (lstat(zfile1, &st))
156680638Sobrien					continue;
156780638Sobrien			}
156859003Shm		}
1569130165Sgad		if (noaction)
1570111967Sgad			printf("\tmv %s %s\n", zfile1, zfile2);
1571130165Sgad		else {
1572130165Sgad			/* XXX - Ought to be checking for failure! */
1573130165Sgad			(void)rename(zfile1, zfile2);
157459003Shm		}
1575130165Sgad		change_attrs(zfile2, ent);
157659003Shm	}
157713244Sgraichen
1578130038Sgad	if (ent->numlogs > 0) {
1579129974Sgad		if (noaction) {
1580130038Sgad			/*
1581130038Sgad			 * Note that savelog() may succeed with using link()
1582130038Sgad			 * for the archtodir case, but there is no good way
1583130038Sgad			 * of knowing if it will when doing "noaction", so
1584130038Sgad			 * here we claim that it will have to do a copy...
1585130038Sgad			 */
1586130038Sgad			if (archtodir)
1587130038Sgad				printf("\tcp %s %s\n", ent->log, file1);
1588130038Sgad			else
1589130038Sgad				printf("\tln %s %s\n", ent->log, file1);
1590130165Sgad		} else {
1591130038Sgad			if (!(flags & CE_BINARY)) {
1592130038Sgad				/* Report the trimming to the old log */
1593130038Sgad				log_trim(ent->log, ent);
1594130038Sgad			}
1595130038Sgad			savelog(ent->log, file1);
159659004Shm		}
1597130165Sgad		change_attrs(file1, ent);
159818075Sjkh	}
159918075Sjkh
1600130038Sgad	/* Create the new log file and move it into place */
1601130038Sgad	if (noaction)
1602111781Sgad		printf("Start new log...\n");
1603130038Sgad	createlog(ent);
160425443Sache
1605130167Sgad#ifdef TRY_NEWORDER
1606111966Sgad	/*
1607130167Sgad	 * Save all signalling and file-compression to be done after log
1608130167Sgad	 * files from all entries have been rotated.  This way any one
1609130167Sgad	 * process will not be sent the same signal multiple times when
1610130167Sgad	 * multiple log files had to be rotated.
1611130167Sgad	 */
1612130167Sgad	if (dbg_new_order) {
1613130167Sgad		struct sigwork_entry *swork;
1614130167Sgad
1615130167Sgad		swork = NULL;
1616130167Sgad		if (ent->pid_file != NULL)
1617130167Sgad			swork = save_sigwork(ent);
1618130167Sgad		if (ent->numlogs > 0 && (flags & (CE_COMPACT | CE_BZCOMPACT))) {
1619130167Sgad			/*
1620130167Sgad			 * The zipwork_entry will include a pointer to this
1621130167Sgad			 * conf_entry, so the conf_entry should not be freed.
1622130167Sgad			 */
1623130167Sgad			free_or_keep = KEEP_ENT;
1624130167Sgad			save_zipwork(ent, swork, ent->fsize, file1);
1625130167Sgad		}
1626130167Sgad		return (free_or_keep);
1627130167Sgad	}
1628130167Sgad#endif /* TRY_NEWORDER */
1629130167Sgad
1630130167Sgad	/*
1631111966Sgad	 * Find out if there is a process to signal.  If nosignal (-s) was
1632111966Sgad	 * specified, then do not signal any process.  Note that nosignal
1633111966Sgad	 * will trigger a warning message if the rotated logfile needs to
1634111966Sgad	 * be compressed, *unless* -R was specified.  This is because there
1635111966Sgad	 * presumably still are process(es) writing to the old logfile, but
1636111966Sgad	 * we assume that a -sR request comes from a process which writes
1637111966Sgad	 * to the logfile, and as such, that process has already made sure
1638111966Sgad	 * that the logfile is not presently in use.
1639111966Sgad	 */
164025443Sache	need_notification = notified = 0;
1641111779Sgad	if (ent->pid_file != NULL) {
164225443Sache		need_notification = 1;
1643111966Sgad		if (!nosignal)
1644112003Sgad			notified = send_signal(ent);	/* the normal case! */
1645111966Sgad		else if (rotatereq)
1646111966Sgad			need_notification = 0;
164725443Sache	}
1648112003Sgad
164980638Sobrien	if ((flags & CE_COMPACT) || (flags & CE_BZCOMPACT)) {
165025443Sache		if (need_notification && !notified)
165180646Sobrien			warnx(
1652112003Sgad			    "log %s.0 not compressed because daemon(s) not notified",
1653119927Sgad			    ent->log);
1654130165Sgad		else if (noaction) {
1655130165Sgad			printf("\tsleep 10\n");
1656111967Sgad			if (flags & CE_COMPACT)
1657119927Sgad				printf("\tgzip %s.0\n", ent->log);
1658111967Sgad			else
1659119927Sgad				printf("\tbzip2 %s.0\n", ent->log);
1660130165Sgad		} else {
166125443Sache			if (notified) {
166225443Sache				if (verbose)
1663112003Sgad					printf("small pause to allow daemon(s) to close log\n");
166431460Sache				sleep(10);
166525443Sache			}
166659004Shm			if (archtodir) {
166780646Sobrien				(void) snprintf(file1, sizeof(file1), "%s/%s",
166880646Sobrien				    dirpart, namepart);
166980638Sobrien				if (flags & CE_COMPACT)
1670107916Ssobomax					compress_log(file1,
1671107916Ssobomax					    flags & CE_COMPACTWAIT);
167280638Sobrien				else if (flags & CE_BZCOMPACT)
1673107916Ssobomax					bzcompress_log(file1,
1674107916Ssobomax					    flags & CE_COMPACTWAIT);
167559004Shm			} else {
167680638Sobrien				if (flags & CE_COMPACT)
1677119927Sgad					compress_log(ent->log,
1678107916Ssobomax					    flags & CE_COMPACTWAIT);
167980638Sobrien				else if (flags & CE_BZCOMPACT)
1680119927Sgad					bzcompress_log(ent->log,
1681107916Ssobomax					    flags & CE_COMPACTWAIT);
168259004Shm			}
168325443Sache		}
168459003Shm	}
1685130165Sgad	return (free_or_keep);
168613244Sgraichen}
168713244Sgraichen
1688130167Sgad#ifdef TRY_NEWORDER
1689130167Sgadstatic void
1690130167Sgaddo_sigwork(struct sigwork_entry *swork)
1691130167Sgad{
1692130204Sgad	struct sigwork_entry *nextsig;
1693130204Sgad	int kres, secs;
1694130167Sgad
1695130167Sgad	if (!(swork->sw_pidok) || swork->sw_pid == 0)
1696130167Sgad		return;			/* no work to do... */
1697130167Sgad
1698130167Sgad	/*
1699130167Sgad	 * If nosignal (-s) was specified, then do not signal any process.
1700130167Sgad	 * Note that a nosignal request triggers a warning message if the
1701130167Sgad	 * rotated logfile needs to be compressed, *unless* -R was also
1702130167Sgad	 * specified.  We assume that an `-sR' request came from a process
1703130167Sgad	 * which writes to the logfile, and as such, we assume that process
1704130167Sgad	 * has already made sure the logfile is not presently in use.  This
1705130167Sgad	 * just sets swork->sw_pidok to a special value, and do_zipwork
1706130167Sgad	 * will print any necessary warning(s).
1707130167Sgad	 */
1708130167Sgad	if (nosignal) {
1709130167Sgad		if (!rotatereq)
1710130167Sgad			swork->sw_pidok = -1;
1711130167Sgad		return;
1712130167Sgad	}
1713130167Sgad
1714130204Sgad	/*
1715130204Sgad	 * Compute the pause between consecutive signals.  Use a longer
1716130204Sgad	 * sleep time if we will be sending two signals to the same
1717130204Sgad	 * deamon or process-group.
1718130204Sgad	 */
1719130204Sgad	secs = 0;
1720130204Sgad	nextsig = SLIST_NEXT(swork, sw_nextp);
1721130204Sgad	if (nextsig != NULL) {
1722130204Sgad		if (swork->sw_pid == nextsig->sw_pid)
1723130204Sgad			secs = 10;
1724130204Sgad		else
1725130204Sgad			secs = 1;
1726130204Sgad	}
1727130204Sgad
1728130167Sgad	if (noaction) {
1729130204Sgad		printf("\tkill -%d %d \t\t# %s\n", swork->sw_signum,
1730130204Sgad		    (int)swork->sw_pid, swork->sw_fname);
1731130204Sgad		if (secs > 0)
1732130204Sgad			printf("\tsleep %d\n", secs);
1733130167Sgad		return;
1734130167Sgad	}
1735130167Sgad
1736130167Sgad	kres = kill(swork->sw_pid, swork->sw_signum);
1737130167Sgad	if (kres != 0) {
1738130167Sgad		/*
1739130167Sgad		 * Assume that "no such process" (ESRCH) is something
1740130167Sgad		 * to warn about, but is not an error.  Presumably the
1741130167Sgad		 * process which writes to the rotated log file(s) is
1742130167Sgad		 * gone, in which case we should have no problem with
1743130167Sgad		 * compressing the rotated log file(s).
1744130167Sgad		 */
1745130167Sgad		if (errno != ESRCH)
1746130167Sgad			swork->sw_pidok = 0;
1747130167Sgad		warn("can't notify %s, pid %d", swork->sw_pidtype,
1748130167Sgad		    (int)swork->sw_pid);
1749130167Sgad	} else {
1750130204Sgad		if (verbose)
1751130204Sgad			printf("Notified %s pid %d = %s\n", swork->sw_pidtype,
1752130204Sgad			    (int)swork->sw_pid, swork->sw_fname);
1753130204Sgad		if (secs > 0) {
1754130204Sgad			if (verbose)
1755130204Sgad				printf("Pause %d second(s) between signals\n",
1756130204Sgad				    secs);
1757130204Sgad			sleep(secs);
1758130167Sgad		}
1759130167Sgad	}
1760130167Sgad}
1761130167Sgad
1762130167Sgadstatic void
1763130167Sgaddo_zipwork(struct zipwork_entry *zwork)
1764130167Sgad{
1765130167Sgad	const char *pgm_name, *pgm_path;
1766130167Sgad	int zstatus;
1767130167Sgad	pid_t pidzip, wpid;
1768130167Sgad	char zresult[MAXPATHLEN];
1769130167Sgad
1770130167Sgad	pgm_path = NULL;
1771130167Sgad	strlcpy(zresult, zwork->zw_fname, sizeof(zresult));
1772130167Sgad	if (zwork != NULL && zwork->zw_conf != NULL) {
1773130167Sgad		if (zwork->zw_conf->flags & CE_COMPACT) {
1774130167Sgad			pgm_path = _PATH_GZIP;
1775130167Sgad			strlcat(zresult, COMPRESS_POSTFIX, sizeof(zresult));
1776130167Sgad		} else if (zwork->zw_conf->flags & CE_BZCOMPACT) {
1777130167Sgad			pgm_path = _PATH_BZIP2;
1778130167Sgad			strlcat(zresult, BZCOMPRESS_POSTFIX, sizeof(zresult));
1779130167Sgad		}
1780130167Sgad	}
1781130167Sgad	if (pgm_path == NULL) {
1782130167Sgad		warnx("invalid entry for %s in do_zipwork", zwork->zw_fname);
1783130167Sgad		return;
1784130167Sgad	}
1785130167Sgad
1786130167Sgad	if (zwork->zw_swork != NULL && zwork->zw_swork->sw_pidok <= 0) {
1787130167Sgad		warnx(
1788130167Sgad		    "log %s not compressed because daemon(s) not notified",
1789130167Sgad		    zwork->zw_fname);
1790130167Sgad		change_attrs(zwork->zw_fname, zwork->zw_conf);
1791130167Sgad		return;
1792130167Sgad	}
1793130167Sgad
1794130167Sgad	if (noaction) {
1795130167Sgad		pgm_name = strrchr(pgm_path, '/');
1796130167Sgad		if (pgm_name == NULL)
1797130167Sgad			pgm_name = pgm_path;
1798130167Sgad		else
1799130167Sgad			pgm_name++;
1800130167Sgad		printf("\t%s %s\n", pgm_name, zwork->zw_fname);
1801130167Sgad		change_attrs(zresult, zwork->zw_conf);
1802130167Sgad		return;
1803130167Sgad	}
1804130167Sgad
1805130167Sgad	pidzip = fork();
1806130167Sgad	if (pidzip < 0)
1807130167Sgad		err(1, "gzip fork");
1808130167Sgad	else if (!pidzip) {
1809130167Sgad		/* The child process executes the compression command */
1810130167Sgad		execl(pgm_path, pgm_path, "-f", zwork->zw_fname, (char *)0);
1811130794Sgad		err(1, "%s", pgm_path);
1812130167Sgad	}
1813130167Sgad
1814130167Sgad	wpid = waitpid(pidzip, &zstatus, 0);
1815130167Sgad	if (wpid == -1) {
1816130167Sgad		warn("%s: waitpid(%d)", pgm_path, pidzip);
1817130167Sgad		return;
1818130167Sgad	}
1819130167Sgad	if (!WIFEXITED(zstatus)) {
1820130167Sgad		warn("%s: did not terminate normally", pgm_path);
1821130167Sgad		return;
1822130167Sgad	}
1823130167Sgad	if (WEXITSTATUS(zstatus)) {
1824130167Sgad		warn("%s: terminated with %d (non-zero) status",
1825130167Sgad		    pgm_path, WEXITSTATUS(zstatus));
1826130167Sgad		return;
1827130167Sgad	}
1828130167Sgad
1829130167Sgad	/* Compression was successful, set file attributes on the result. */
1830130167Sgad	change_attrs(zresult, zwork->zw_conf);
1831130167Sgad}
1832130167Sgad
1833130167Sgad/*
1834130167Sgad * Save information on any process we need to signal.  Any single
1835130167Sgad * process may need to be sent different signal-values for different
1836130167Sgad * log files, but usually a single signal-value will cause the process
1837130167Sgad * to close and re-open all of it's log files.
1838130167Sgad */
1839130167Sgadstatic struct sigwork_entry *
1840130167Sgadsave_sigwork(const struct conf_entry *ent)
1841130167Sgad{
1842130167Sgad	struct sigwork_entry *sprev, *stmp;
1843130167Sgad	int ndiff;
1844130167Sgad	size_t tmpsiz;
1845130167Sgad
1846130167Sgad	sprev = NULL;
1847130167Sgad	ndiff = 1;
1848130167Sgad	SLIST_FOREACH(stmp, &swhead, sw_nextp) {
1849130167Sgad		ndiff = strcmp(ent->pid_file, stmp->sw_fname);
1850130167Sgad		if (ndiff > 0)
1851130167Sgad			break;
1852130167Sgad		if (ndiff == 0) {
1853130167Sgad			if (ent->sig == stmp->sw_signum)
1854130167Sgad				break;
1855130167Sgad			if (ent->sig > stmp->sw_signum) {
1856130167Sgad				ndiff = 1;
1857130167Sgad				break;
1858130167Sgad			}
1859130167Sgad		}
1860130167Sgad		sprev = stmp;
1861130167Sgad	}
1862130167Sgad	if (stmp != NULL && ndiff == 0)
1863130167Sgad		return (stmp);
1864130167Sgad
1865130167Sgad	tmpsiz = sizeof(struct sigwork_entry) + strlen(ent->pid_file) + 1;
1866130167Sgad	stmp = malloc(tmpsiz);
1867130167Sgad	set_swpid(stmp, ent);
1868130167Sgad	stmp->sw_signum = ent->sig;
1869130167Sgad	strcpy(stmp->sw_fname, ent->pid_file);
1870130167Sgad	if (sprev == NULL)
1871130167Sgad		SLIST_INSERT_HEAD(&swhead, stmp, sw_nextp);
1872130167Sgad	else
1873130167Sgad		SLIST_INSERT_AFTER(sprev, stmp, sw_nextp);
1874130167Sgad	return (stmp);
1875130167Sgad}
1876130167Sgad
1877130167Sgad/*
1878130167Sgad * Save information on any file we need to compress.  We may see the same
1879130167Sgad * file multiple times, so check the full list to avoid duplicates.  The
1880130167Sgad * list itself is sorted smallest-to-largest, because that's the order we
1881130167Sgad * want to compress the files.  If the partition is very low on disk space,
1882130167Sgad * then the smallest files are the most likely to compress, and compressing
1883130167Sgad * them first will free up more space for the larger files.
1884130167Sgad */
1885130167Sgadstatic struct zipwork_entry *
1886130167Sgadsave_zipwork(const struct conf_entry *ent, const struct sigwork_entry *swork,
1887130167Sgad    int zsize, const char *zipfname)
1888130167Sgad{
1889130167Sgad	struct zipwork_entry *zprev, *ztmp;
1890130167Sgad	int ndiff;
1891130167Sgad	size_t tmpsiz;
1892130167Sgad
1893130167Sgad	/* Compute the size if the caller did not know it. */
1894130167Sgad	if (zsize < 0)
1895130167Sgad		zsize = sizefile(zipfname);
1896130167Sgad
1897130167Sgad	zprev = NULL;
1898130167Sgad	ndiff = 1;
1899130167Sgad	SLIST_FOREACH(ztmp, &zwhead, zw_nextp) {
1900130707Sgad		ndiff = strcmp(zipfname, ztmp->zw_fname);
1901130167Sgad		if (ndiff == 0)
1902130167Sgad			break;
1903130167Sgad		if (zsize > ztmp->zw_fsize)
1904130167Sgad			zprev = ztmp;
1905130167Sgad	}
1906130167Sgad	if (ztmp != NULL && ndiff == 0)
1907130167Sgad		return (ztmp);
1908130167Sgad
1909130167Sgad	tmpsiz = sizeof(struct zipwork_entry) + strlen(zipfname) + 1;
1910130167Sgad	ztmp = malloc(tmpsiz);
1911130167Sgad	ztmp->zw_conf = ent;
1912130167Sgad	ztmp->zw_swork = swork;
1913130167Sgad	ztmp->zw_fsize = zsize;
1914130167Sgad	strcpy(ztmp->zw_fname, zipfname);
1915130167Sgad	if (zprev == NULL)
1916130167Sgad		SLIST_INSERT_HEAD(&zwhead, ztmp, zw_nextp);
1917130167Sgad	else
1918130167Sgad		SLIST_INSERT_AFTER(zprev, ztmp, zw_nextp);
1919130167Sgad	return (ztmp);
1920130167Sgad}
1921130167Sgad
1922130167Sgad/* Send a signal to the pid specified by pidfile */
1923130167Sgadstatic void
1924130167Sgadset_swpid(struct sigwork_entry *swork, const struct conf_entry *ent)
1925130167Sgad{
1926130167Sgad	FILE *f;
1927130167Sgad	long minok, maxok, rval;
1928130167Sgad	char *endp, *linep, line[BUFSIZ];
1929130167Sgad
1930130167Sgad	minok = MIN_PID;
1931130167Sgad	maxok = MAX_PID;
1932130167Sgad	swork->sw_pidok = 0;
1933130167Sgad	swork->sw_pid = 0;
1934130167Sgad	swork->sw_pidtype = "daemon";
1935130167Sgad	if (ent->flags & CE_SIGNALGROUP) {
1936130167Sgad		/*
1937130167Sgad		 * If we are expected to signal a process-group when
1938130167Sgad		 * rotating this logfile, then the value read in should
1939130167Sgad		 * be the negative of a valid process ID.
1940130167Sgad		 */
1941130167Sgad		minok = -MAX_PID;
1942130167Sgad		maxok = -MIN_PID;
1943130167Sgad		swork->sw_pidtype = "process-group";
1944130167Sgad	}
1945130167Sgad
1946130167Sgad	f = fopen(ent->pid_file, "r");
1947130167Sgad	if (f == NULL) {
1948130167Sgad		warn("can't open pid file: %s", ent->pid_file);
1949130167Sgad		return;
1950130167Sgad	}
1951130167Sgad
1952130167Sgad	if (fgets(line, BUFSIZ, f) == NULL) {
1953130167Sgad		/*
1954130167Sgad		 * Warn if the PID file is empty, but do not consider
1955130167Sgad		 * it an error.  Most likely it means the process has
1956130167Sgad		 * has terminated, so it should be safe to rotate any
1957130167Sgad		 * log files that the process would have been using.
1958130167Sgad		 */
1959130167Sgad		if (feof(f)) {
1960130167Sgad			swork->sw_pidok = 1;
1961130167Sgad			warnx("pid file is empty: %s", ent->pid_file);
1962130167Sgad		} else
1963130167Sgad			warn("can't read from pid file: %s", ent->pid_file);
1964130167Sgad		(void)fclose(f);
1965130167Sgad		return;
1966130167Sgad	}
1967130167Sgad	(void)fclose(f);
1968130167Sgad
1969130167Sgad	errno = 0;
1970130167Sgad	linep = line;
1971130167Sgad	while (*linep == ' ')
1972130167Sgad		linep++;
1973130167Sgad	rval = strtol(linep, &endp, 10);
1974130167Sgad	if (*endp != '\0' && !isspacech(*endp)) {
1975130167Sgad		warnx("pid file does not start with a valid number: %s",
1976130167Sgad		    ent->pid_file);
1977130167Sgad	} else if (rval < minok || rval > maxok) {
1978130167Sgad		warnx("bad value '%ld' for process number in %s",
1979130167Sgad		    rval, ent->pid_file);
1980130167Sgad		if (verbose)
1981130167Sgad			warnx("\t(expecting value between %ld and %ld)",
1982130167Sgad			    minok, maxok);
1983130167Sgad	} else {
1984130167Sgad		swork->sw_pidok = 1;
1985130167Sgad		swork->sw_pid = rval;
1986130167Sgad	}
1987130167Sgad
1988130167Sgad	return;
1989130167Sgad}
1990130167Sgad#endif /* TRY_NEWORDER */
1991130167Sgad
199213244Sgraichen/* Log the fact that the logs were turned over */
199359004Shmstatic int
1994119926Sgadlog_trim(const char *logname, const struct conf_entry *log_ent)
199513244Sgraichen{
199659003Shm	FILE *f;
1997111388Sgad	const char *xtra;
199859003Shm
1999119926Sgad	if ((f = fopen(logname, "a")) == NULL)
200059003Shm		return (-1);
2001111388Sgad	xtra = "";
2002111768Sgad	if (log_ent->def_cfg)
2003111388Sgad		xtra = " using <default> rule";
2004114137Sgad	if (log_ent->firstcreate)
2005114137Sgad		fprintf(f, "%s %s newsyslog[%d]: logfile first created%s\n",
2006114137Sgad		    daytime, hostname, (int) getpid(), xtra);
2007114137Sgad	else if (log_ent->r_reason != NULL)
2008111772Sgad		fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s%s\n",
2009111772Sgad		    daytime, hostname, (int) getpid(), log_ent->r_reason, xtra);
2010111772Sgad	else
2011111772Sgad		fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s\n",
2012111772Sgad		    daytime, hostname, (int) getpid(), xtra);
201359003Shm	if (fclose(f) == EOF)
2014127858Scharnier		err(1, "log_trim: fclose");
201559003Shm	return (0);
201613244Sgraichen}
201713244Sgraichen
2018130043Sgad/*
2019130043Sgad * XXX - Note that both compress_log and bzcompress_log will lose the
2020130043Sgad *	NODUMP flag if it was set on somelog.0.  Fixing that in newsyslog
2021130043Sgad *	(as opposed to fixing gzip/bzip2) will require some restructuring
2022130043Sgad *	of the code.  That restructuring is planned for a later update...
2023130043Sgad */
202459004Shm/* Fork of gzip to compress the old log file */
202559004Shmstatic void
2026119926Sgadcompress_log(char *logname, int dowait)
202713244Sgraichen{
202859003Shm	pid_t pid;
202971299Sjedgar	char tmp[MAXPATHLEN];
203059003Shm
2031107916Ssobomax	while (dowait && (wait(NULL) > 0 || errno == EINTR))
2032107916Ssobomax		;
2033119926Sgad	(void) snprintf(tmp, sizeof(tmp), "%s.0", logname);
203425443Sache	pid = fork();
203559003Shm	if (pid < 0)
203680638Sobrien		err(1, "gzip fork");
203759003Shm	else if (!pid) {
203879452Sbrian		(void) execl(_PATH_GZIP, _PATH_GZIP, "-f", tmp, (char *)0);
203943071Swollman		err(1, _PATH_GZIP);
204059003Shm	}
204113244Sgraichen}
204213244Sgraichen
204380638Sobrien/* Fork of bzip2 to compress the old log file */
204480638Sobrienstatic void
2045119926Sgadbzcompress_log(char *logname, int dowait)
204680638Sobrien{
204780638Sobrien	pid_t pid;
204880638Sobrien	char tmp[MAXPATHLEN];
204980638Sobrien
2050107916Ssobomax	while (dowait && (wait(NULL) > 0 || errno == EINTR))
2051107916Ssobomax		;
2052119926Sgad	snprintf(tmp, sizeof(tmp), "%s.0", logname);
205380638Sobrien	pid = fork();
205480638Sobrien	if (pid < 0)
205580638Sobrien		err(1, "bzip2 fork");
205680638Sobrien	else if (!pid) {
205786360Sobrien		execl(_PATH_BZIP2, _PATH_BZIP2, "-f", tmp, (char *)0);
205880638Sobrien		err(1, _PATH_BZIP2);
205980638Sobrien	}
206080638Sobrien}
206180638Sobrien
206213244Sgraichen/* Return size in kilobytes of a file */
206359004Shmstatic int
2064130165Sgadsizefile(const char *file)
206513244Sgraichen{
206659003Shm	struct stat sb;
206713244Sgraichen
206859003Shm	if (stat(file, &sb) < 0)
206959003Shm		return (-1);
207059003Shm	return (kbytes(dbtob(sb.st_blocks)));
207113244Sgraichen}
207213244Sgraichen
207313244Sgraichen/* Return the age of old log file (file.0) */
207459004Shmstatic int
207559004Shmage_old_log(char *file)
207613244Sgraichen{
207759003Shm	struct stat sb;
2078114764Sgad	char *endp;
2079114764Sgad	char tmp[MAXPATHLEN + sizeof(".0") + sizeof(COMPRESS_POSTFIX) +
2080114764Sgad		sizeof(BZCOMPRESS_POSTFIX) + 1];
208113244Sgraichen
208259004Shm	if (archtodir) {
208359004Shm		char *p;
208459004Shm
208559004Shm		/* build name of archive directory into tmp */
208659004Shm		if (*archdirname == '/') {	/* absolute */
208771299Sjedgar			strlcpy(tmp, archdirname, sizeof(tmp));
208859004Shm		} else {	/* relative */
208959004Shm			/* get directory part of logfile */
209071299Sjedgar			strlcpy(tmp, file, sizeof(tmp));
209159004Shm			if ((p = rindex(tmp, '/')) == NULL)
209259004Shm				tmp[0] = '\0';
209359004Shm			else
209459004Shm				*(p + 1) = '\0';
209571299Sjedgar			strlcat(tmp, archdirname, sizeof(tmp));
209659004Shm		}
209759004Shm
209871299Sjedgar		strlcat(tmp, "/", sizeof(tmp));
209959004Shm
210059004Shm		/* get filename part of logfile */
210159004Shm		if ((p = rindex(file, '/')) == NULL)
210271299Sjedgar			strlcat(tmp, file, sizeof(tmp));
210359004Shm		else
210471299Sjedgar			strlcat(tmp, p + 1, sizeof(tmp));
210559004Shm	} else {
210671299Sjedgar		(void) strlcpy(tmp, file, sizeof(tmp));
210759004Shm	}
210859004Shm
2109114764Sgad	strlcat(tmp, ".0", sizeof(tmp));
2110114764Sgad	if (stat(tmp, &sb) < 0) {
2111114764Sgad		/*
2112114764Sgad		 * A plain '.0' file does not exist.  Try again, first
2113114764Sgad		 * with the added suffix of '.gz', then with an added
2114114764Sgad		 * suffix of '.bz2' instead of '.gz'.
2115114764Sgad		 */
2116114764Sgad		endp = strchr(tmp, '\0');
2117114764Sgad		strlcat(tmp, COMPRESS_POSTFIX, sizeof(tmp));
2118114764Sgad		if (stat(tmp, &sb) < 0) {
2119114764Sgad			*endp = '\0';		/* Remove .gz */
2120114764Sgad			strlcat(tmp, BZCOMPRESS_POSTFIX, sizeof(tmp));
2121114764Sgad			if (stat(tmp, &sb) < 0)
2122114764Sgad				return (-1);
2123114764Sgad		}
2124114764Sgad	}
2125120361Sgad	return ((int)(ptimeget_secs(timenow) - sb.st_mtime + 1800) / 3600);
212613244Sgraichen}
212713244Sgraichen
212813244Sgraichen/* Skip Over Blanks */
2129111820Sgadstatic char *
213059004Shmsob(char *p)
213113244Sgraichen{
213259003Shm	while (p && *p && isspace(*p))
213359003Shm		p++;
213459003Shm	return (p);
213513244Sgraichen}
213613244Sgraichen
213713244Sgraichen/* Skip Over Non-Blanks */
2138111820Sgadstatic char *
213959004Shmson(char *p)
214013244Sgraichen{
214159003Shm	while (p && *p && !isspace(*p))
214259003Shm		p++;
214359003Shm	return (p);
214413244Sgraichen}
214543071Swollman
2146119102Sgad/* Check if string is actually a number */
2147119102Sgadstatic int
2148119102Sgadisnumberstr(const char *string)
2149119102Sgad{
2150119102Sgad	while (*string) {
2151119102Sgad		if (!isdigitch(*string++))
2152119102Sgad			return (0);
2153119102Sgad	}
2154119102Sgad	return (1);
2155119102Sgad}
2156119102Sgad
2157130038Sgad/*
2158130038Sgad * Save the active log file under a new name.  A link to the new name
2159130038Sgad * is the quick-and-easy way to do this.  If that fails (which it will
2160130038Sgad * if the destination is on another partition), then make a copy of
2161130038Sgad * the file to the new location.
2162130038Sgad */
216359004Shmstatic void
2164130038Sgadsavelog(char *from, char *to)
216559004Shm{
216659004Shm	FILE *src, *dst;
2167130038Sgad	int c, res;
216859004Shm
2169130038Sgad	res = link(from, to);
2170130038Sgad	if (res == 0)
2171130038Sgad		return;
2172130038Sgad
217359004Shm	if ((src = fopen(from, "r")) == NULL)
217459004Shm		err(1, "can't fopen %s for reading", from);
217559004Shm	if ((dst = fopen(to, "w")) == NULL)
217659004Shm		err(1, "can't fopen %s for writing", to);
217759004Shm
217859004Shm	while ((c = getc(src)) != EOF) {
217959004Shm		if ((putc(c, dst)) == EOF)
218059004Shm			err(1, "error writing to %s", to);
218159004Shm	}
218259004Shm
218359004Shm	if (ferror(src))
218459004Shm		err(1, "error reading from %s", from);
218559004Shm	if ((fclose(src)) != 0)
218659004Shm		err(1, "can't fclose %s", to);
218759004Shm	if ((fclose(dst)) != 0)
218859004Shm		err(1, "can't fclose %s", from);
218959004Shm}
219059004Shm
219159004Shm/* create one or more directory components of a path */
219259004Shmstatic void
2193114137Sgadcreatedir(const struct conf_entry *ent, char *dirpart)
219459004Shm{
2195111398Sgad	int res;
219659004Shm	char *s, *d;
219771299Sjedgar	char mkdirpath[MAXPATHLEN];
219859004Shm	struct stat st;
219959004Shm
220059004Shm	s = dirpart;
220159004Shm	d = mkdirpath;
220259004Shm
220359004Shm	for (;;) {
220459004Shm		*d++ = *s++;
2205111398Sgad		if (*s != '/' && *s != '\0')
2206111398Sgad			continue;
2207111398Sgad		*d = '\0';
2208111398Sgad		res = lstat(mkdirpath, &st);
2209111398Sgad		if (res != 0) {
2210111398Sgad			if (noaction) {
2211111967Sgad				printf("\tmkdir %s\n", mkdirpath);
2212111398Sgad			} else {
2213111398Sgad				res = mkdir(mkdirpath, 0755);
2214111398Sgad				if (res != 0)
2215111398Sgad					err(1, "Error on mkdir(\"%s\") for -a",
2216111398Sgad					    mkdirpath);
2217111398Sgad			}
221859004Shm		}
221959004Shm		if (*s == '\0')
222059004Shm			break;
222159004Shm	}
2222114137Sgad	if (verbose) {
2223114137Sgad		if (ent->firstcreate)
2224114137Sgad			printf("Created directory '%s' for new %s\n",
2225114137Sgad			    dirpart, ent->log);
2226114137Sgad		else
2227114137Sgad			printf("Created directory '%s' for -a\n", dirpart);
2228114137Sgad	}
222959004Shm}
223059004Shm
2231114137Sgad/*
2232114137Sgad * Create a new log file, destroying any currently-existing version
2233114137Sgad * of the log file in the process.  If the caller wants a backup copy
2234114137Sgad * of the file to exist, they should call 'link(logfile,logbackup)'
2235114137Sgad * before calling this routine.
2236114137Sgad */
2237114137Sgadvoid
2238114137Sgadcreatelog(const struct conf_entry *ent)
2239114137Sgad{
2240114137Sgad	int fd, failed;
2241114137Sgad	struct stat st;
2242114137Sgad	char *realfile, *slash, tempfile[MAXPATHLEN];
2243114137Sgad
2244114137Sgad	fd = -1;
2245114137Sgad	realfile = ent->log;
2246114137Sgad
2247114137Sgad	/*
2248114137Sgad	 * If this log file is being created for the first time (-C option),
2249114137Sgad	 * then it may also be true that the parent directory does not exist
2250114137Sgad	 * yet.  Check, and create that directory if it is missing.
2251114137Sgad	 */
2252114137Sgad	if (ent->firstcreate) {
2253114137Sgad		strlcpy(tempfile, realfile, sizeof(tempfile));
2254114137Sgad		slash = strrchr(tempfile, '/');
2255114137Sgad		if (slash != NULL) {
2256114137Sgad			*slash = '\0';
2257131581Ssobomax			failed = stat(tempfile, &st);
2258114137Sgad			if (failed && errno != ENOENT)
2259131581Ssobomax				err(1, "Error on stat(%s)", tempfile);
2260114137Sgad			if (failed)
2261114137Sgad				createdir(ent, tempfile);
2262114137Sgad			else if (!S_ISDIR(st.st_mode))
2263114137Sgad				errx(1, "%s exists but is not a directory",
2264114137Sgad				    tempfile);
2265114137Sgad		}
2266114137Sgad	}
2267114137Sgad
2268114137Sgad	/*
2269114137Sgad	 * First create an unused filename, so it can be chown'ed and
2270114137Sgad	 * chmod'ed before it is moved into the real location.  mkstemp
2271114137Sgad	 * will create the file mode=600 & owned by us.  Note that all
2272114137Sgad	 * temp files will have a suffix of '.z<something>'.
2273114137Sgad	 */
2274114137Sgad	strlcpy(tempfile, realfile, sizeof(tempfile));
2275114137Sgad	strlcat(tempfile, ".zXXXXXX", sizeof(tempfile));
2276114137Sgad	if (noaction)
2277114137Sgad		printf("\tmktemp %s\n", tempfile);
2278114137Sgad	else {
2279114137Sgad		fd = mkstemp(tempfile);
2280114137Sgad		if (fd < 0)
2281114137Sgad			err(1, "can't mkstemp logfile %s", tempfile);
2282114137Sgad
2283114137Sgad		/*
2284114137Sgad		 * Add status message to what will become the new log file.
2285114137Sgad		 */
2286114137Sgad		if (!(ent->flags & CE_BINARY)) {
2287114137Sgad			if (log_trim(tempfile, ent))
2288114137Sgad				err(1, "can't add status message to log");
2289114137Sgad		}
2290114137Sgad	}
2291114137Sgad
2292114137Sgad	/* Change the owner/group, if we are supposed to */
2293114137Sgad	if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2294114137Sgad		if (noaction)
2295114137Sgad			printf("\tchown %u:%u %s\n", ent->uid, ent->gid,
2296114137Sgad			    tempfile);
2297114137Sgad		else {
2298114137Sgad			failed = fchown(fd, ent->uid, ent->gid);
2299114137Sgad			if (failed)
2300114137Sgad				err(1, "can't fchown temp file %s", tempfile);
2301114137Sgad		}
2302114137Sgad	}
2303114137Sgad
2304130043Sgad	/* Turn on NODUMP if it was requested in the config-file. */
2305130043Sgad	if (ent->flags & CE_NODUMP) {
2306130043Sgad		if (noaction)
2307130043Sgad			printf("\tchflags nodump %s\n", tempfile);
2308130043Sgad		else {
2309130043Sgad			failed = fchflags(fd, UF_NODUMP);
2310130043Sgad			if (failed) {
2311130043Sgad				warn("log_trim: fchflags(NODUMP)");
2312130043Sgad			}
2313130043Sgad		}
2314130043Sgad	}
2315130043Sgad
2316114137Sgad	/*
2317114137Sgad	 * Note that if the real logfile still exists, and if the call
2318114137Sgad	 * to rename() fails, then "neither the old file nor the new
2319114137Sgad	 * file shall be changed or created" (to quote the standard).
2320114137Sgad	 * If the call succeeds, then the file will be replaced without
2321114137Sgad	 * any window where some other process might find that the file
2322114137Sgad	 * did not exist.
2323114137Sgad	 * XXX - ? It may be that for some error conditions, we could
2324114137Sgad	 *	retry by first removing the realfile and then renaming.
2325114137Sgad	 */
2326114137Sgad	if (noaction) {
2327114137Sgad		printf("\tchmod %o %s\n", ent->permissions, tempfile);
2328114137Sgad		printf("\tmv %s %s\n", tempfile, realfile);
2329114137Sgad	} else {
2330114137Sgad		failed = fchmod(fd, ent->permissions);
2331114137Sgad		if (failed)
2332114137Sgad			err(1, "can't fchmod temp file '%s'", tempfile);
2333114137Sgad		failed = rename(tempfile, realfile);
2334114137Sgad		if (failed)
2335114137Sgad			err(1, "can't mv %s to %s", tempfile, realfile);
2336114137Sgad	}
2337114137Sgad
2338114137Sgad	if (fd >= 0)
2339114137Sgad		close(fd);
2340114137Sgad}
2341130165Sgad
2342130165Sgadstatic void
2343130165Sgadchange_attrs(const char *fname, const struct conf_entry *ent)
2344130165Sgad{
2345130165Sgad	int failed;
2346130165Sgad
2347130165Sgad	if (noaction) {
2348130165Sgad		printf("\tchmod %o %s\n", ent->permissions, fname);
2349130165Sgad
2350130165Sgad		if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
2351130165Sgad			printf("\tchown %u:%u %s\n",
2352130165Sgad			    ent->uid, ent->gid, fname);
2353130165Sgad
2354130165Sgad		if (ent->flags & CE_NODUMP)
2355130165Sgad			printf("\tchflags nodump %s\n", fname);
2356130165Sgad		return;
2357130165Sgad	}
2358130165Sgad
2359130165Sgad	failed = chmod(fname, ent->permissions);
2360130165Sgad	if (failed)
2361130165Sgad		warn("can't chmod %s", fname);
2362130165Sgad
2363130165Sgad	if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2364130165Sgad		failed = chown(fname, ent->uid, ent->gid);
2365130165Sgad		if (failed)
2366130165Sgad			warn("can't chown %s", fname);
2367130165Sgad	}
2368130165Sgad
2369130165Sgad	if (ent->flags & CE_NODUMP) {
2370130165Sgad		failed = chflags(fname, UF_NODUMP);
2371130165Sgad		if (failed)
2372130165Sgad			warn("can't chflags %s NODUMP", fname);
2373130165Sgad	}
2374130165Sgad}
2375