newsyslog.c revision 111966
113244Sgraichen/*
213244Sgraichen * This file contains changes from the Open Software Foundation.
313244Sgraichen */
413244Sgraichen
513244Sgraichen/*
659004Shm * Copyright 1988, 1989 by the Massachusetts Institute of Technology
759004Shm *
859004Shm * Permission to use, copy, modify, and distribute this software and its
959004Shm * documentation for any purpose and without fee is hereby granted, provided
1059004Shm * that the above copyright notice appear in all copies and that both that
1159004Shm * copyright notice and this permission notice appear in supporting
1259004Shm * documentation, and that the names of M.I.T. and the M.I.T. S.I.P.B. not be
1359004Shm * used in advertising or publicity pertaining to distribution of the
1459004Shm * software without specific, written prior permission. M.I.T. and the M.I.T.
1559004Shm * S.I.P.B. make no representations about the suitability of this software
1659004Shm * for any purpose.  It is provided "as is" without express or implied
1759004Shm * warranty.
1859004Shm *
1959004Shm */
2013244Sgraichen
2113244Sgraichen/*
2259004Shm * newsyslog - roll over selected logs at the appropriate time, keeping the a
2359004Shm * specified number of backup files around.
2413244Sgraichen */
2513244Sgraichen
2613244Sgraichen#ifndef lint
2730160Scharnierstatic const char rcsid[] =
2859003Shm"$FreeBSD: head/usr.sbin/newsyslog/newsyslog.c 111966 2003-03-07 21:06:32Z gad $";
2959004Shm#endif	/* not lint */
3013244Sgraichen
3143071Swollman#define OSF
3213244Sgraichen#ifndef COMPRESS_POSTFIX
3343071Swollman#define COMPRESS_POSTFIX ".gz"
3413244Sgraichen#endif
3580638Sobrien#ifndef	BZCOMPRESS_POSTFIX
3680638Sobrien#define	BZCOMPRESS_POSTFIX ".bz2"
3780638Sobrien#endif
3813244Sgraichen
3996001Smaxim#include <sys/param.h>
4096001Smaxim#include <sys/stat.h>
4196001Smaxim#include <sys/wait.h>
4296001Smaxim
4330160Scharnier#include <ctype.h>
4430160Scharnier#include <err.h>
4595999Smaxim#include <errno.h>
4630160Scharnier#include <fcntl.h>
47111773Sgad#include <fnmatch.h>
48106905Ssobomax#include <glob.h>
4930160Scharnier#include <grp.h>
5043071Swollman#include <paths.h>
5130160Scharnier#include <pwd.h>
5230160Scharnier#include <signal.h>
5313244Sgraichen#include <stdio.h>
5413244Sgraichen#include <stdlib.h>
5513244Sgraichen#include <string.h>
5643071Swollman#include <time.h>
5716240Salex#include <unistd.h>
5813244Sgraichen
5943071Swollman#include "pathnames.h"
6043071Swollman
61111768Sgad/*
62111768Sgad * Bit-values for the 'flags' parsed from a config-file entry.
63111768Sgad */
64111768Sgad#define CE_COMPACT	0x0001	/* Compact the achived log files with gzip. */
65111768Sgad#define CE_BZCOMPACT	0x0002	/* Compact the achived log files with bzip2. */
66111781Sgad#define CE_COMPACTWAIT	0x0004	/* wait until compressing one file finishes */
67111768Sgad				/*    before starting the next step. */
68111768Sgad#define CE_BINARY	0x0008	/* Logfile is in binary, do not add status */
69111768Sgad				/*    messages to logfile(s) when rotating. */
70111781Sgad#define CE_NOSIGNAL	0x0010	/* There is no process to signal when */
71111768Sgad				/*    trimming this file. */
72111781Sgad#define CE_TRIMAT	0x0020	/* trim file at a specific time. */
73111781Sgad#define CE_GLOB		0x0040	/* name of the log is file name pattern. */
7443071Swollman
75111781Sgad#define MIN_PID         5	/* Don't touch pids lower than this */
76111781Sgad#define MAX_PID		99999	/* was lower, see /usr/include/sys/proc.h */
77111781Sgad
78111781Sgad#define kbytes(size)  (((size) + 1023) >> 10)
79111781Sgad
8013244Sgraichenstruct conf_entry {
8159003Shm	char *log;		/* Name of the log */
8259003Shm	char *pid_file;		/* PID file */
83111772Sgad	char *r_reason;		/* The reason this file is being rotated */
84111772Sgad	int rotate;		/* Non-zero if this file should be rotated */
85111779Sgad	uid_t uid;		/* Owner of log */
86111779Sgad	gid_t gid;		/* Group of log */
8759003Shm	int numlogs;		/* Number of logs to keep */
8859003Shm	int size;		/* Size cutoff to trigger trimming the log */
8959003Shm	int hours;		/* Hours between log trimming */
9059003Shm	time_t trim_at;		/* Specific time to do trimming */
9159003Shm	int permissions;	/* File permissions on the log */
9280646Sobrien	int flags;		/* CE_COMPACT, CE_BZCOMPACT, CE_BINARY */
9359003Shm	int sig;		/* Signal to send */
94111388Sgad	int def_cfg;		/* Using the <default> rule for this file */
9559003Shm	struct conf_entry *next;/* Linked list pointer */
9613244Sgraichen};
9713244Sgraichen
98111388Sgad#define DEFAULT_MARKER "<default>"
99111388Sgad
10059004Shmint archtodir = 0;		/* Archive old logfiles to other directory */
10159003Shmint verbose = 0;		/* Print out what's going on */
10259003Shmint needroot = 1;		/* Root privs are necessary */
10359003Shmint noaction = 0;		/* Don't do anything, just show it */
104111768Sgadint nosignal;			/* Do not send any signals */
10559003Shmint force = 0;			/* Force the trim no matter what */
106111772Sgadint rotatereq = 0;		/* -R = Always rotate the file(s) as given */
107111772Sgad				/*    on the command (this also requires   */
108111772Sgad				/*    that a list of files *are* given on  */
109111772Sgad				/*    the run command). */
110111772Sgadchar *requestor;		/* The name given on a -R request */
11159004Shmchar *archdirname;		/* Directory path to old logfiles archive */
112111773Sgadconst char *conf;		/* Configuration file to use */
11359003Shmtime_t timenow;
11459003Shm
11571299Sjedgarchar hostname[MAXHOSTNAMELEN];	/* hostname */
116108164Strhodeschar daytime[16];		/* timenow in human readable form */
11713244Sgraichen
118111773Sgadstatic struct conf_entry *get_worklist(char **files);
119111773Sgadstatic void parse_file(FILE *cf, const char *cfname, struct conf_entry **work_p,
120111773Sgad		struct conf_entry **defconf_p);
12116240Salexstatic char *sob(char *p);
12216240Salexstatic char *son(char *p);
12359003Shmstatic char *missing_field(char *p, char *errline);
12459003Shmstatic void do_entry(struct conf_entry * ent);
125111388Sgadstatic void free_entry(struct conf_entry *ent);
126111388Sgadstatic struct conf_entry *init_entry(const char *fname,
127111388Sgad		struct conf_entry *src_entry);
128111781Sgadstatic void parse_args(int argc, char **argv);
12980640Sobrienstatic void usage(void);
130111779Sgadstatic void dotrim(const struct conf_entry *ent, char *log,
131111780Sgad		int numdays, int flags);
132111768Sgadstatic int log_trim(const char *log, const struct conf_entry *log_ent);
133107916Ssobomaxstatic void compress_log(char *log, int dowait);
134107916Ssobomaxstatic void bzcompress_log(char *log, int dowait);
13516240Salexstatic int sizefile(char *file);
13616240Salexstatic int age_old_log(char *file);
13780640Sobrienstatic pid_t get_pid(const char *pid_file);
13893659Scjcstatic time_t parse8601(char *s, char *errline);
139111779Sgadstatic void movefile(char *from, char *to, int perm, uid_t owner_uid,
140111779Sgad		gid_t group_gid);
14159004Shmstatic void createdir(char *dirpart);
14293659Scjcstatic time_t parseDWM(char *s, char *errline);
14313244Sgraichen
144111768Sgad/*
145111768Sgad * All the following are defined to work on an 'int', in the
146111768Sgad * range 0 to 255, plus EOF.  Define wrappers which can take
147111768Sgad * values of type 'char', either signed or unsigned.
148111768Sgad */
149111772Sgad#define isprintch(Anychar)    isprint(((int) Anychar) & 255)
150111768Sgad#define isspacech(Anychar)    isspace(((int) Anychar) & 255)
151111768Sgad#define tolowerch(Anychar)    tolower(((int) Anychar) & 255)
152111768Sgad
15359004Shmint
15459004Shmmain(int argc, char **argv)
15513244Sgraichen{
15659003Shm	struct conf_entry *p, *q;
157111529Sgad	char *savglob;
158106905Ssobomax	glob_t pglob;
159106905Ssobomax	int i;
16025443Sache
161111781Sgad	parse_args(argc, argv);
162111773Sgad	argc -= optind;
163111773Sgad	argv += optind;
164111773Sgad
16559003Shm	if (needroot && getuid() && geteuid())
16659003Shm		errx(1, "must have root privs");
167111773Sgad	p = q = get_worklist(argv);
16859003Shm
16959003Shm	while (p) {
170106905Ssobomax		if ((p->flags & CE_GLOB) == 0) {
171106905Ssobomax			do_entry(p);
172106905Ssobomax		} else {
173111773Sgad			if (verbose > 2)
174111773Sgad				printf("\t+ Processing pattern %s\n", p->log);
175106905Ssobomax			if (glob(p->log, GLOB_NOCHECK, NULL, &pglob) != 0) {
176106905Ssobomax				warn("can't expand pattern: %s", p->log);
177106905Ssobomax			} else {
178111529Sgad				savglob = p->log;
179106905Ssobomax				for (i = 0; i < pglob.gl_matchc; i++) {
180106905Ssobomax					p->log = pglob.gl_pathv[i];
181106905Ssobomax					do_entry(p);
182106905Ssobomax				}
183106905Ssobomax				globfree(&pglob);
184111529Sgad				p->log = savglob;
185111773Sgad				if (verbose > 2)
186111773Sgad					printf("\t+ Done with pattern\n");
187106905Ssobomax			}
188106905Ssobomax		}
18959003Shm		p = p->next;
190111388Sgad		free_entry(q);
19159003Shm		q = p;
19259003Shm	}
19395999Smaxim	while (wait(NULL) > 0 || errno == EINTR)
19495999Smaxim		;
19559003Shm	return (0);
19613244Sgraichen}
19713244Sgraichen
198111388Sgadstatic struct conf_entry *
199111388Sgadinit_entry(const char *fname, struct conf_entry *src_entry)
200111388Sgad{
201111388Sgad	struct conf_entry *tempwork;
202111388Sgad
203111388Sgad	if (verbose > 4)
204111388Sgad		printf("\t--> [creating entry for %s]\n", fname);
205111388Sgad
206111388Sgad	tempwork = malloc(sizeof(struct conf_entry));
207111388Sgad	if (tempwork == NULL)
208111388Sgad		err(1, "malloc of conf_entry for %s", fname);
209111388Sgad
210111388Sgad	tempwork->log = strdup(fname);
211111388Sgad	if (tempwork->log == NULL)
212111388Sgad		err(1, "strdup for %s", fname);
213111388Sgad
214111388Sgad	if (src_entry != NULL) {
215111388Sgad		tempwork->pid_file = NULL;
216111388Sgad		if (src_entry->pid_file)
217111388Sgad			tempwork->pid_file = strdup(src_entry->pid_file);
218111772Sgad		tempwork->r_reason = NULL;
219111772Sgad		tempwork->rotate = 0;
220111388Sgad		tempwork->uid = src_entry->uid;
221111388Sgad		tempwork->gid = src_entry->gid;
222111388Sgad		tempwork->numlogs = src_entry->numlogs;
223111388Sgad		tempwork->size = src_entry->size;
224111388Sgad		tempwork->hours = src_entry->hours;
225111388Sgad		tempwork->trim_at = src_entry->trim_at;
226111388Sgad		tempwork->permissions = src_entry->permissions;
227111388Sgad		tempwork->flags = src_entry->flags;
228111388Sgad		tempwork->sig = src_entry->sig;
229111388Sgad		tempwork->def_cfg = src_entry->def_cfg;
230111388Sgad	} else {
231111388Sgad		/* Initialize as a "do-nothing" entry */
232111388Sgad		tempwork->pid_file = NULL;
233111772Sgad		tempwork->r_reason = NULL;
234111772Sgad		tempwork->rotate = 0;
235111779Sgad		tempwork->uid = (uid_t)-1;
236111779Sgad		tempwork->gid = (gid_t)-1;
237111388Sgad		tempwork->numlogs = 1;
238111388Sgad		tempwork->size = -1;
239111388Sgad		tempwork->hours = -1;
240111388Sgad		tempwork->trim_at = (time_t)0;
241111388Sgad		tempwork->permissions = 0;
242111388Sgad		tempwork->flags = 0;
243111388Sgad		tempwork->sig = SIGHUP;
244111388Sgad		tempwork->def_cfg = 0;
245111388Sgad	}
246111388Sgad	tempwork->next = NULL;
247111388Sgad
248111388Sgad	return (tempwork);
249111388Sgad}
250111388Sgad
25159004Shmstatic void
252111388Sgadfree_entry(struct conf_entry *ent)
253111388Sgad{
254111388Sgad
255111388Sgad	if (ent == NULL)
256111388Sgad		return;
257111388Sgad
258111388Sgad	if (ent->log != NULL) {
259111388Sgad		if (verbose > 4)
260111388Sgad			printf("\t--> [freeing entry for %s]\n", ent->log);
261111388Sgad		free(ent->log);
262111388Sgad		ent->log = NULL;
263111388Sgad	}
264111388Sgad
265111388Sgad	if (ent->pid_file != NULL) {
266111388Sgad		free(ent->pid_file);
267111388Sgad		ent->pid_file = NULL;
268111388Sgad	}
269111388Sgad
270111772Sgad	if (ent->r_reason != NULL) {
271111772Sgad		free(ent->r_reason);
272111772Sgad		ent->r_reason = NULL;
273111772Sgad	}
274111772Sgad
275111388Sgad	free(ent);
276111388Sgad}
277111388Sgad
278111388Sgadstatic void
27959004Shmdo_entry(struct conf_entry * ent)
28013244Sgraichen{
281111772Sgad#define REASON_MAX	80
28259003Shm	int size, modtime;
283111772Sgad	char temp_reason[REASON_MAX];
28459003Shm
28559003Shm	if (verbose) {
28659003Shm		if (ent->flags & CE_COMPACT)
28759003Shm			printf("%s <%dZ>: ", ent->log, ent->numlogs);
28880638Sobrien		else if (ent->flags & CE_BZCOMPACT)
28980638Sobrien			printf("%s <%dJ>: ", ent->log, ent->numlogs);
29059003Shm		else
29159003Shm			printf("%s <%d>: ", ent->log, ent->numlogs);
29259003Shm	}
29359003Shm	size = sizefile(ent->log);
29459003Shm	modtime = age_old_log(ent->log);
295111772Sgad	ent->rotate = 0;
29659003Shm	if (size < 0) {
29759003Shm		if (verbose)
29859003Shm			printf("does not exist.\n");
29959003Shm	} else {
300111772Sgad		if (ent->flags & CE_TRIMAT && !force && !rotatereq) {
30143071Swollman			if (timenow < ent->trim_at
30259003Shm			    || difftime(timenow, ent->trim_at) >= 60 * 60) {
30343071Swollman				if (verbose)
30443071Swollman					printf("--> will trim at %s",
30559003Shm					    ctime(&ent->trim_at));
30643071Swollman				return;
30743071Swollman			} else if (verbose && ent->hours <= 0) {
30843071Swollman				printf("--> time is up\n");
30943071Swollman			}
31043071Swollman		}
31159003Shm		if (verbose && (ent->size > 0))
31259003Shm			printf("size (Kb): %d [%d] ", size, ent->size);
31359003Shm		if (verbose && (ent->hours > 0))
31459003Shm			printf(" age (hr): %d [%d] ", modtime, ent->hours);
315111772Sgad
316111772Sgad		/*
317111772Sgad		 * Figure out if this logfile needs to be rotated.
318111772Sgad		 */
319111772Sgad		temp_reason[0] = '\0';
320111772Sgad		if (rotatereq) {
321111772Sgad			ent->rotate = 1;
322111772Sgad			snprintf(temp_reason, REASON_MAX, " due to -R from %s",
323111772Sgad			    requestor);
324111772Sgad		} else if (force) {
325111772Sgad			ent->rotate = 1;
326111772Sgad			snprintf(temp_reason, REASON_MAX, " due to -F request");
327111772Sgad		} else if ((ent->size > 0) && (size >= ent->size)) {
328111772Sgad			ent->rotate = 1;
329111772Sgad			snprintf(temp_reason, REASON_MAX, " due to size>%dK",
330111772Sgad			    ent->size);
331111772Sgad		} else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) {
332111772Sgad			ent->rotate = 1;
333111772Sgad		} else if ((ent->hours > 0) && ((modtime >= ent->hours) ||
334111772Sgad		    (modtime < 0))) {
335111772Sgad			ent->rotate = 1;
336111772Sgad		}
337111772Sgad
338111772Sgad		/*
339111772Sgad		 * If the file needs to be rotated, then rotate it.
340111772Sgad		 */
341111772Sgad		if (ent->rotate) {
342111772Sgad			if (temp_reason[0] != '\0')
343111772Sgad				ent->r_reason = strdup(temp_reason);
34459003Shm			if (verbose)
34559003Shm				printf("--> trimming log....\n");
34659003Shm			if (noaction && !verbose) {
34759003Shm				if (ent->flags & CE_COMPACT)
34859003Shm					printf("%s <%dZ>: trimming\n",
34959003Shm					    ent->log, ent->numlogs);
35080638Sobrien				else if (ent->flags & CE_BZCOMPACT)
35180638Sobrien					printf("%s <%dJ>: trimming\n",
35280638Sobrien					    ent->log, ent->numlogs);
35359003Shm				else
35459003Shm					printf("%s <%d>: trimming\n",
35559003Shm					    ent->log, ent->numlogs);
35659003Shm			}
357111780Sgad			dotrim(ent, ent->log, ent->numlogs, ent->flags);
35859003Shm		} else {
35959003Shm			if (verbose)
36059003Shm				printf("--> skipping\n");
36159003Shm		}
36259003Shm	}
363111772Sgad#undef REASON_MAX
36413244Sgraichen}
36513244Sgraichen
36659004Shmstatic void
367111781Sgadparse_args(int argc, char **argv)
36813244Sgraichen{
369111781Sgad	int ch;
37059003Shm	char *p;
37113244Sgraichen
372111781Sgad	timenow = time(NULL);
373108164Strhodes	(void)strncpy(daytime, ctime(&timenow) + 4, 15);
37459003Shm	daytime[15] = '\0';
37513244Sgraichen
37659003Shm	/* Let's get our hostname */
377111781Sgad	(void)gethostname(hostname, sizeof(hostname));
37813244Sgraichen
37913244Sgraichen	/* Truncate domain */
380111781Sgad	if ((p = strchr(hostname, '.')) != NULL)
38113244Sgraichen		*p = '\0';
382111768Sgad
383111768Sgad	/* Parse command line options. */
384111781Sgad	while ((ch = getopt(argc, argv, "a:f:nrsvFR:")) != -1)
385111781Sgad		switch (ch) {
38659004Shm		case 'a':
38759004Shm			archtodir++;
38859004Shm			archdirname = optarg;
38959004Shm			break;
390111768Sgad		case 'f':
391111768Sgad			conf = optarg;
392111768Sgad			break;
393111768Sgad		case 'n':
394111768Sgad			noaction++;
395111768Sgad			break;
39659003Shm		case 'r':
39759003Shm			needroot = 0;
39859003Shm			break;
399111768Sgad		case 's':
400111768Sgad			nosignal = 1;
401111768Sgad			break;
40259003Shm		case 'v':
40359003Shm			verbose++;
40459003Shm			break;
40534584Spst		case 'F':
40634584Spst			force++;
40734584Spst			break;
408111772Sgad		case 'R':
409111772Sgad			rotatereq++;
410111772Sgad			requestor = strdup(optarg);
411111772Sgad			break;
412111781Sgad		case 'm':	/* Used by OpenBSD for "monitor mode" */
41359003Shm		default:
41459003Shm			usage();
415111768Sgad			/* NOTREACHED */
41659003Shm		}
417111772Sgad
418111772Sgad	if (rotatereq) {
419111772Sgad		if (optind == argc) {
420111772Sgad			warnx("At least one filename must be given when -R is specified.");
421111772Sgad			usage();
422111772Sgad			/* NOTREACHED */
423111772Sgad		}
424111772Sgad		/* Make sure "requestor" value is safe for a syslog message. */
425111772Sgad		for (p = requestor; *p != '\0'; p++) {
426111772Sgad			if (!isprintch(*p) && (*p != '\t'))
427111772Sgad				*p = '.';
428111772Sgad		}
429111772Sgad	}
43043071Swollman}
43113244Sgraichen
43259004Shmstatic void
43359004Shmusage(void)
43413244Sgraichen{
43580646Sobrien
43680646Sobrien	fprintf(stderr,
437111772Sgad	    "usage: newsyslog [-Fnrsv] [-a directory] [-f config-file]\n"
438111772Sgad	    "                 [ [-R requestor] filename ... ]\n");
43959003Shm	exit(1);
44013244Sgraichen}
44113244Sgraichen
44259004Shm/*
443111773Sgad * Parse a configuration file and return a linked list of all the logs
444111773Sgad * which should be processed.
44513244Sgraichen */
44659003Shmstatic struct conf_entry *
447111773Sgadget_worklist(char **files)
44813244Sgraichen{
44959003Shm	FILE *f;
450111773Sgad	const char *fname;
451111773Sgad	char **given;
452111773Sgad	struct conf_entry *defconf, *dupent, *ent, *firstnew;
453111773Sgad	struct conf_entry *newlist, *worklist;
454111773Sgad	int gmatch;
455111773Sgad
456111773Sgad	defconf = worklist = NULL;
457111773Sgad
458111773Sgad	fname = conf;
459111773Sgad	if (fname == NULL)
460111773Sgad		fname = _PATH_CONF;
461111773Sgad
462111773Sgad	if (strcmp(fname, "-") != 0)
463111773Sgad		f = fopen(fname, "r");
464111773Sgad	else {
465111773Sgad		f = stdin;
466111773Sgad		fname = "<stdin>";
467111773Sgad	}
468111773Sgad	if (!f)
469111773Sgad		err(1, "%s", conf);
470111773Sgad
471111773Sgad	parse_file(f, fname, &worklist, &defconf);
472111773Sgad	(void) fclose(f);
473111773Sgad
474111773Sgad	/*
475111773Sgad	 * All config-file information has been read in and turned into
476111773Sgad	 * a worklist.  If there were no specific files given on the run
477111773Sgad	 * command, then the work of this routine is done.
478111773Sgad	 */
479111773Sgad	if (*files == NULL) {
480111773Sgad		if (defconf != NULL)
481111773Sgad			free_entry(defconf);
482111773Sgad		return (worklist);
483111773Sgad		/* NOTREACHED */
484111773Sgad	}
485111773Sgad
486111773Sgad	/*
487111773Sgad	 * If newsyslog was given a specific list of files to process,
488111773Sgad	 * it may be that some of those files were not listed in any
489111773Sgad	 * config file.  Those unlisted files should get the default
490111773Sgad	 * rotation action.  First, create the default-rotation action
491111773Sgad	 * if none was found in a system config file.
492111773Sgad	 */
493111773Sgad	if (defconf == NULL) {
494111773Sgad		defconf = init_entry(DEFAULT_MARKER, NULL);
495111773Sgad		defconf->numlogs = 3;
496111773Sgad		defconf->size = 50;
497111773Sgad		defconf->permissions = S_IRUSR|S_IWUSR;
498111773Sgad	}
499111773Sgad
500111773Sgad	/*
501111773Sgad	 * If newsyslog was run with a list of specific filenames,
502111773Sgad	 * then create a new worklist which has only those files in
503111773Sgad	 * it, picking up the rotation-rules for those files from
504111773Sgad	 * the original worklist.
505111773Sgad	 *
506111773Sgad	 * XXX - Note that this will copy multiple rules for a single
507111773Sgad	 *	logfile, if multiple entries are an exact match for
508111773Sgad	 *	that file.  That matches the historic behavior, but do
509111773Sgad	 *	we want to continue to allow it?  If so, it should
510111773Sgad	 *	probably be handled more intelligently.
511111773Sgad	 */
512111773Sgad	firstnew = newlist = NULL;
513111773Sgad	for (given = files; *given; ++given) {
514111773Sgad		gmatch = 0;
515111773Sgad		/*
516111773Sgad		 * First try to find exact-matches for this given file.
517111773Sgad		 */
518111773Sgad		for (ent = worklist; ent; ent = ent->next) {
519111773Sgad			if ((ent->flags & CE_GLOB) != 0)
520111773Sgad				continue;
521111773Sgad			if (strcmp(ent->log, *given) == 0) {
522111773Sgad				gmatch++;
523111773Sgad				dupent = init_entry(*given, ent);
524111773Sgad				if (!firstnew)
525111773Sgad					firstnew = dupent;
526111773Sgad				else
527111773Sgad					newlist->next = dupent;
528111773Sgad				newlist = dupent;
529111773Sgad			}
530111773Sgad		}
531111773Sgad		if (gmatch) {
532111773Sgad			if (verbose > 2)
533111773Sgad				printf("\t+ Matched entry %s\n", *given);
534111773Sgad			continue;
535111773Sgad		}
536111773Sgad
537111773Sgad		/*
538111773Sgad		 * There was no exact-match for this given file, so look
539111773Sgad		 * for a "glob" entry which does match.
540111773Sgad		 */
541111773Sgad		for (ent = worklist; ent; ent = ent->next) {
542111773Sgad			if ((ent->flags & CE_GLOB) == 0)
543111773Sgad				continue;
544111773Sgad			if (fnmatch(ent->log, *given, FNM_PATHNAME) == 0) {
545111773Sgad				gmatch++;
546111773Sgad				dupent = init_entry(*given, ent);
547111773Sgad				if (!firstnew)
548111773Sgad					firstnew = dupent;
549111773Sgad				else
550111773Sgad					newlist->next = dupent;
551111773Sgad				newlist = dupent;
552111773Sgad				/* This work entry is *not* a glob! */
553111773Sgad				dupent->flags &= ~CE_GLOB;
554111773Sgad				/* Only allow a match to one glob-entry */
555111773Sgad				break;
556111773Sgad			}
557111773Sgad		}
558111773Sgad		if (gmatch) {
559111773Sgad			if (verbose > 2)
560111773Sgad				printf("\t+ Matched %s via %s\n", *given,
561111773Sgad				    ent->log);
562111773Sgad			continue;
563111773Sgad		}
564111773Sgad
565111773Sgad		/*
566111773Sgad		 * This given file was not found in any config file, so
567111773Sgad		 * add a worklist item based on the default entry.
568111773Sgad		 */
569111773Sgad		if (verbose > 2)
570111773Sgad			printf("\t+ No entry matched %s  (will use %s)\n",
571111773Sgad			    *given, DEFAULT_MARKER);
572111773Sgad		dupent = init_entry(*given, defconf);
573111773Sgad		if (!firstnew)
574111773Sgad			firstnew = dupent;
575111773Sgad		else
576111773Sgad			newlist->next = dupent;
577111773Sgad		/* Mark that it was *not* found in a config file */
578111773Sgad		dupent->def_cfg = 1;
579111773Sgad		newlist = dupent;
580111773Sgad	}
581111773Sgad
582111773Sgad	/*
583111773Sgad	 * Free all the entries in the original work list, and then
584111773Sgad	 * return the new work list.
585111773Sgad	 */
586111773Sgad	while (worklist) {
587111773Sgad		ent = worklist->next;
588111773Sgad		free_entry(worklist);
589111773Sgad		worklist = ent;
590111773Sgad	}
591111773Sgad
592111773Sgad	free_entry(defconf);
593111773Sgad	return (newlist);
594111773Sgad}
595111773Sgad
596111773Sgad/*
597111773Sgad * Parse a configuration file and update a linked list of all the logs to
598111773Sgad * process.
599111773Sgad */
600111773Sgadstatic void
601111773Sgadparse_file(FILE *cf, const char *cfname, struct conf_entry **work_p,
602111773Sgad    struct conf_entry **defconf_p)
603111773Sgad{
60459003Shm	char line[BUFSIZ], *parse, *q;
605107737Ssobomax	char *cp, *errline, *group;
606111773Sgad	struct conf_entry *working, *worklist;
607111781Sgad	struct passwd *pwd;
60859003Shm	struct group *grp;
60925518Sbrian	int eol;
61013244Sgraichen
611111773Sgad	/*
612111773Sgad	 * XXX - for now, assume that only one config file will be read,
613111773Sgad	 *	ie, this routine is only called one time.
614111773Sgad	 */
615111773Sgad	worklist = NULL;
61680646Sobrien
617111773Sgad	while (fgets(line, BUFSIZ, cf)) {
618107737Ssobomax		if ((line[0] == '\n') || (line[0] == '#') ||
619107737Ssobomax		    (strlen(line) == 0))
62059003Shm			continue;
62159003Shm		errline = strdup(line);
622107737Ssobomax		for (cp = line + 1; *cp != '\0'; cp++) {
623107737Ssobomax			if (*cp != '#')
624107737Ssobomax				continue;
625107737Ssobomax			if (*(cp - 1) == '\\') {
626107737Ssobomax				strcpy(cp - 1, cp);
627107737Ssobomax				cp--;
628107737Ssobomax				continue;
629107737Ssobomax			}
630107737Ssobomax			*cp = '\0';
631107737Ssobomax			break;
632107737Ssobomax		}
63360373Sdes
63460373Sdes		q = parse = missing_field(sob(line), errline);
63560373Sdes		parse = son(line);
63660373Sdes		if (!*parse)
63780646Sobrien			errx(1, "malformed line (missing fields):\n%s",
63880646Sobrien			    errline);
63960373Sdes		*parse = '\0';
64060373Sdes
641111388Sgad		working = init_entry(q, NULL);
642111388Sgad		if (strcasecmp(DEFAULT_MARKER, q) == 0) {
643111773Sgad			if (defconf_p == NULL) {
644111773Sgad				warnx("Ignoring entry for %s in %s!", q,
645111773Sgad				    cfname);
646111773Sgad				free_entry(working);
647111773Sgad				continue;
648111773Sgad			} else if (*defconf_p != NULL) {
649111388Sgad				warnx("Ignoring duplicate entry for %s!", q);
650111388Sgad				free_entry(working);
651111388Sgad				continue;
652111388Sgad			}
653111773Sgad			*defconf_p = working;
65459003Shm		} else {
655111773Sgad			if (!*work_p)
656111773Sgad				*work_p = working;
657111388Sgad			else
658111388Sgad				worklist->next = working;
659111388Sgad			worklist = working;
66059003Shm		}
66113244Sgraichen
66259003Shm		q = parse = missing_field(sob(++parse), errline);
66359003Shm		parse = son(parse);
66425518Sbrian		if (!*parse)
66580646Sobrien			errx(1, "malformed line (missing fields):\n%s",
66680646Sobrien			    errline);
66759003Shm		*parse = '\0';
66859003Shm		if ((group = strchr(q, ':')) != NULL ||
66959003Shm		    (group = strrchr(q, '.')) != NULL) {
67059003Shm			*group++ = '\0';
67159003Shm			if (*q) {
67259003Shm				if (!(isnumber(*q))) {
673111781Sgad					if ((pwd = getpwnam(q)) == NULL)
67459003Shm						errx(1,
67580646Sobrien				     "error in config file; unknown user:\n%s",
67659003Shm						    errline);
677111781Sgad					working->uid = pwd->pw_uid;
67859003Shm				} else
67959003Shm					working->uid = atoi(q);
68059003Shm			} else
681111779Sgad				working->uid = (uid_t)-1;
68213244Sgraichen
68359003Shm			q = group;
68459003Shm			if (*q) {
68559003Shm				if (!(isnumber(*q))) {
68659003Shm					if ((grp = getgrnam(q)) == NULL)
68759003Shm						errx(1,
68880646Sobrien				    "error in config file; unknown group:\n%s",
68959003Shm						    errline);
69059003Shm					working->gid = grp->gr_gid;
69159003Shm				} else
69259003Shm					working->gid = atoi(q);
69359003Shm			} else
694111779Sgad				working->gid = (gid_t)-1;
69513244Sgraichen
69659003Shm			q = parse = missing_field(sob(++parse), errline);
69759003Shm			parse = son(parse);
69859003Shm			if (!*parse)
69980646Sobrien				errx(1, "malformed line (missing fields):\n%s",
70080646Sobrien				    errline);
70159003Shm			*parse = '\0';
702111779Sgad		} else {
703111779Sgad			working->uid = (uid_t)-1;
704111779Sgad			working->gid = (gid_t)-1;
705111779Sgad		}
70659003Shm
70759003Shm		if (!sscanf(q, "%o", &working->permissions))
70859003Shm			errx(1, "error in config file; bad permissions:\n%s",
70959003Shm			    errline);
71059003Shm
71159003Shm		q = parse = missing_field(sob(++parse), errline);
71259003Shm		parse = son(parse);
71325518Sbrian		if (!*parse)
71480646Sobrien			errx(1, "malformed line (missing fields):\n%s",
71580646Sobrien			    errline);
71659003Shm		*parse = '\0';
717111400Sgad		if (!sscanf(q, "%d", &working->numlogs) || working->numlogs < 0)
718111400Sgad			errx(1, "error in config file; bad value for count of logs to save:\n%s",
71959003Shm			    errline);
72013244Sgraichen
72159003Shm		q = parse = missing_field(sob(++parse), errline);
72259003Shm		parse = son(parse);
72325518Sbrian		if (!*parse)
72480646Sobrien			errx(1, "malformed line (missing fields):\n%s",
72580646Sobrien			    errline);
72659003Shm		*parse = '\0';
72759003Shm		if (isdigit(*q))
72859003Shm			working->size = atoi(q);
72959003Shm		else
73059003Shm			working->size = -1;
73159003Shm
73259003Shm		working->flags = 0;
73359003Shm		q = parse = missing_field(sob(++parse), errline);
73459003Shm		parse = son(parse);
73525518Sbrian		eol = !*parse;
73659003Shm		*parse = '\0';
73743071Swollman		{
73859003Shm			char *ep;
73959003Shm			u_long ul;
74013244Sgraichen
74143071Swollman			ul = strtoul(q, &ep, 10);
74243071Swollman			if (ep == q)
74343071Swollman				working->hours = 0;
74443071Swollman			else if (*ep == '*')
74543071Swollman				working->hours = -1;
74643071Swollman			else if (ul > INT_MAX)
74743071Swollman				errx(1, "interval is too large:\n%s", errline);
74843071Swollman			else
74943071Swollman				working->hours = ul;
75043071Swollman
75180646Sobrien			if (*ep != '\0' && *ep != '@' && *ep != '*' &&
75280646Sobrien			    *ep != '$')
75343071Swollman				errx(1, "malformed interval/at:\n%s", errline);
75443071Swollman			if (*ep == '@') {
75593659Scjc				if ((working->trim_at = parse8601(ep + 1, errline))
75659003Shm				    == (time_t) - 1)
75743071Swollman					errx(1, "malformed at:\n%s", errline);
75843071Swollman				working->flags |= CE_TRIMAT;
75959004Shm			} else if (*ep == '$') {
76093659Scjc				if ((working->trim_at = parseDWM(ep + 1, errline))
76159004Shm				    == (time_t) - 1)
76259004Shm					errx(1, "malformed at:\n%s", errline);
76359004Shm				working->flags |= CE_TRIMAT;
76443071Swollman			}
76543071Swollman		}
76643071Swollman
76725518Sbrian		if (eol)
76859003Shm			q = NULL;
76925518Sbrian		else {
77059003Shm			q = parse = sob(++parse);	/* Optional field */
77159003Shm			parse = son(parse);
77259003Shm			if (!*parse)
77359003Shm				eol = 1;
77459003Shm			*parse = '\0';
77525518Sbrian		}
77625443Sache
777111768Sgad		for (; q && *q && !isspacech(*q); q++) {
778111768Sgad			switch (tolowerch(*q)) {
779111768Sgad			case 'b':
78059003Shm				working->flags |= CE_BINARY;
781111768Sgad				break;
782111781Sgad			case 'c':	/* Used by NetBSD  for "CE_CREATE" */
783111768Sgad				/*
784111768Sgad				 * netbsd uses 'c' for "create".  We will
785111768Sgad				 * temporarily accept it for 'g', because
786111768Sgad				 * earlier freebsd versions had a typo
787111768Sgad				 * of ('G' || 'c')...
788111768Sgad				 */
789111768Sgad				warnx("Assuming 'g' for 'c' in flags for line:\n%s",
790111768Sgad				    errline);
791111768Sgad				/* FALLTHROUGH */
792111768Sgad			case 'g':
793106905Ssobomax				working->flags |= CE_GLOB;
794111768Sgad				break;
795111768Sgad			case 'j':
796111768Sgad				working->flags |= CE_BZCOMPACT;
797111768Sgad				break;
798111768Sgad			case 'n':
799111768Sgad				working->flags |= CE_NOSIGNAL;
800111768Sgad				break;
801111768Sgad			case 'w':
802107916Ssobomax				working->flags |= CE_COMPACTWAIT;
803111768Sgad				break;
804111768Sgad			case 'z':
805111768Sgad				working->flags |= CE_COMPACT;
806111768Sgad				break;
807111768Sgad			case '-':
808111768Sgad				break;
809111781Sgad			case 'f':	/* Used by OpenBSD for "CE_FOLLOW" */
810111781Sgad			case 'm':	/* Used by OpenBSD for "CE_MONITOR" */
811111781Sgad			case 'p':	/* Used by NetBSD  for "CE_PLAIN0" */
812111768Sgad			default:
81380646Sobrien				errx(1, "illegal flag in config file -- %c",
81480646Sobrien				    *q);
815111768Sgad			}
81659003Shm		}
81759003Shm
81825518Sbrian		if (eol)
81959003Shm			q = NULL;
82025518Sbrian		else {
82159003Shm			q = parse = sob(++parse);	/* Optional field */
82259003Shm			parse = son(parse);
82359003Shm			if (!*parse)
82459003Shm				eol = 1;
82559003Shm			*parse = '\0';
82625518Sbrian		}
82725443Sache
82825443Sache		working->pid_file = NULL;
82925443Sache		if (q && *q) {
83025443Sache			if (*q == '/')
83125443Sache				working->pid_file = strdup(q);
83236817Sache			else if (isdigit(*q))
83336817Sache				goto got_sig;
83459003Shm			else
83580646Sobrien				errx(1,
83680646Sobrien			"illegal pid file or signal number in config file:\n%s",
83780646Sobrien				    errline);
83825443Sache		}
83936817Sache		if (eol)
84059003Shm			q = NULL;
84136817Sache		else {
84259003Shm			q = parse = sob(++parse);	/* Optional field */
84359003Shm			*(parse = son(parse)) = '\0';
84436817Sache		}
84536817Sache
84636817Sache		working->sig = SIGHUP;
84736817Sache		if (q && *q) {
84836817Sache			if (isdigit(*q)) {
84959003Shm		got_sig:
85036817Sache				working->sig = atoi(q);
85136817Sache			} else {
85259003Shm		err_sig:
85380646Sobrien				errx(1,
85480646Sobrien				    "illegal signal number in config file:\n%s",
85580646Sobrien				    errline);
85636817Sache			}
85736817Sache			if (working->sig < 1 || working->sig >= NSIG)
85836817Sache				goto err_sig;
85936817Sache		}
860111768Sgad
861111768Sgad		/*
862111768Sgad		 * Finish figuring out what pid-file to use (if any) in
863111768Sgad		 * later processing if this logfile needs to be rotated.
864111768Sgad		 */
865111768Sgad		if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) {
866111768Sgad			/*
867111768Sgad			 * This config-entry specified 'n' for nosignal,
868111768Sgad			 * see if it also specified an explicit pid_file.
869111768Sgad			 * This would be a pretty pointless combination.
870111768Sgad			 */
871111768Sgad			if (working->pid_file != NULL) {
872111768Sgad				warnx("Ignoring '%s' because flag 'n' was specified in line:\n%s",
873111768Sgad				    working->pid_file, errline);
874111768Sgad				free(working->pid_file);
875111768Sgad				working->pid_file = NULL;
876111768Sgad			}
877111768Sgad		} else if (working->pid_file == NULL) {
878111768Sgad			/*
879111768Sgad			 * This entry did not specify the 'n' flag, which
880111768Sgad			 * means it should signal syslogd unless it had
881111768Sgad			 * specified some other pid-file.  But we only
882111768Sgad			 * try to notify syslog if we are root
883111768Sgad			 */
884111768Sgad			if (needroot)
885111768Sgad				working->pid_file = strdup(_PATH_SYSLOGPID);
886111768Sgad		}
887111768Sgad
88859003Shm		free(errline);
889111768Sgad		errline = NULL;
89059003Shm	}
89113244Sgraichen}
89213244Sgraichen
89359003Shmstatic char *
89459004Shmmissing_field(char *p, char *errline)
89513244Sgraichen{
89680646Sobrien
89759003Shm	if (!p || !*p)
89859003Shm		errx(1, "missing field in config file:\n%s", errline);
89959003Shm	return (p);
90013244Sgraichen}
90113244Sgraichen
90259004Shmstatic void
903111780Sgaddotrim(const struct conf_entry *ent, char *log, int numdays, int flags)
90413244Sgraichen{
90571299Sjedgar	char dirpart[MAXPATHLEN], namepart[MAXPATHLEN];
90671299Sjedgar	char file1[MAXPATHLEN], file2[MAXPATHLEN];
90771299Sjedgar	char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN];
90880638Sobrien	char jfile1[MAXPATHLEN];
90994352Ssheldonh	char tfile[MAXPATHLEN];
91059003Shm	int notified, need_notification, fd, _numdays;
91159003Shm	struct stat st;
91259003Shm	pid_t pid;
91313244Sgraichen
91459004Shm	if (archtodir) {
91559004Shm		char *p;
91613244Sgraichen
91759004Shm		/* build complete name of archive directory into dirpart */
91859004Shm		if (*archdirname == '/') {	/* absolute */
91971299Sjedgar			strlcpy(dirpart, archdirname, sizeof(dirpart));
92059004Shm		} else {	/* relative */
92159004Shm			/* get directory part of logfile */
92271299Sjedgar			strlcpy(dirpart, log, sizeof(dirpart));
92359004Shm			if ((p = rindex(dirpart, '/')) == NULL)
92459004Shm				dirpart[0] = '\0';
92559004Shm			else
92659004Shm				*(p + 1) = '\0';
92771299Sjedgar			strlcat(dirpart, archdirname, sizeof(dirpart));
92859004Shm		}
92959004Shm
93059004Shm		/* check if archive directory exists, if not, create it */
93159004Shm		if (lstat(dirpart, &st))
93259004Shm			createdir(dirpart);
93359004Shm
93459004Shm		/* get filename part of logfile */
93559004Shm		if ((p = rindex(log, '/')) == NULL)
93671299Sjedgar			strlcpy(namepart, log, sizeof(namepart));
93759004Shm		else
93871299Sjedgar			strlcpy(namepart, p + 1, sizeof(namepart));
93959004Shm
94059004Shm		/* name of oldest log */
94180646Sobrien		(void) snprintf(file1, sizeof(file1), "%s/%s.%d", dirpart,
94280646Sobrien		    namepart, numdays);
94371299Sjedgar		(void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
94471299Sjedgar		    COMPRESS_POSTFIX);
94580638Sobrien		snprintf(jfile1, sizeof(jfile1), "%s%s", file1,
94680638Sobrien		    BZCOMPRESS_POSTFIX);
94759004Shm	} else {
94859004Shm		/* name of oldest log */
94971299Sjedgar		(void) snprintf(file1, sizeof(file1), "%s.%d", log, numdays);
95071299Sjedgar		(void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
95171299Sjedgar		    COMPRESS_POSTFIX);
95280638Sobrien		snprintf(jfile1, sizeof(jfile1), "%s%s", file1,
95380638Sobrien		    BZCOMPRESS_POSTFIX);
95459004Shm	}
95559004Shm
95659003Shm	if (noaction) {
95759003Shm		printf("rm -f %s\n", file1);
95859003Shm		printf("rm -f %s\n", zfile1);
95980638Sobrien		printf("rm -f %s\n", jfile1);
96059003Shm	} else {
96159003Shm		(void) unlink(file1);
96259003Shm		(void) unlink(zfile1);
96380638Sobrien		(void) unlink(jfile1);
96459003Shm	}
96513244Sgraichen
96659003Shm	/* Move down log files */
96718188Sjkh	_numdays = numdays;	/* preserve */
96859003Shm	while (numdays--) {
96959004Shm
97071299Sjedgar		(void) strlcpy(file2, file1, sizeof(file2));
97159004Shm
97259004Shm		if (archtodir)
97380646Sobrien			(void) snprintf(file1, sizeof(file1), "%s/%s.%d",
97480646Sobrien			    dirpart, namepart, numdays);
97559004Shm		else
97680646Sobrien			(void) snprintf(file1, sizeof(file1), "%s.%d", log,
97780646Sobrien			    numdays);
97859004Shm
97971299Sjedgar		(void) strlcpy(zfile1, file1, sizeof(zfile1));
98071299Sjedgar		(void) strlcpy(zfile2, file2, sizeof(zfile2));
98159003Shm		if (lstat(file1, &st)) {
98280646Sobrien			(void) strlcat(zfile1, COMPRESS_POSTFIX,
98380646Sobrien			    sizeof(zfile1));
98480646Sobrien			(void) strlcat(zfile2, COMPRESS_POSTFIX,
98580646Sobrien			    sizeof(zfile2));
98680638Sobrien			if (lstat(zfile1, &st)) {
98780638Sobrien				strlcpy(zfile1, file1, sizeof(zfile1));
98880638Sobrien				strlcpy(zfile2, file2, sizeof(zfile2));
98980638Sobrien				strlcat(zfile1, BZCOMPRESS_POSTFIX,
99080638Sobrien				    sizeof(zfile1));
99180638Sobrien				strlcat(zfile2, BZCOMPRESS_POSTFIX,
99280638Sobrien				    sizeof(zfile2));
99380638Sobrien				if (lstat(zfile1, &st))
99480638Sobrien					continue;
99580638Sobrien			}
99659003Shm		}
99759003Shm		if (noaction) {
99859003Shm			printf("mv %s %s\n", zfile1, zfile2);
999111780Sgad			printf("chmod %o %s\n", ent->permissions, zfile2);
1000111779Sgad			if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
1001111779Sgad				printf("chown %u:%u %s\n",
1002111779Sgad				    ent->uid, ent->gid, zfile2);
100359003Shm		} else {
100459003Shm			(void) rename(zfile1, zfile2);
1005111780Sgad			if (chmod(zfile2, ent->permissions))
1006111780Sgad				warn("can't chmod %s", file2);
1007111779Sgad			if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
1008111779Sgad				if (chown(zfile2, ent->uid, ent->gid))
1009111779Sgad					warn("can't chown %s", zfile2);
101059003Shm		}
101159003Shm	}
1012111388Sgad	if (!noaction && !(flags & CE_BINARY)) {
1013111388Sgad		/* Report the trimming to the old log */
1014111779Sgad		(void) log_trim(log, ent);
1015111388Sgad	}
101613244Sgraichen
101718188Sjkh	if (!_numdays) {
101818075Sjkh		if (noaction)
101959003Shm			printf("rm %s\n", log);
102018075Sjkh		else
102159003Shm			(void) unlink(log);
102259003Shm	} else {
102318075Sjkh		if (noaction)
102459003Shm			printf("mv %s to %s\n", log, file1);
102559004Shm		else {
102659004Shm			if (archtodir)
1027111780Sgad				movefile(log, file1, ent->permissions, ent->uid,
1028111779Sgad				    ent->gid);
102959004Shm			else
103059004Shm				(void) rename(log, file1);
103159004Shm		}
103218075Sjkh	}
103318075Sjkh
1034111781Sgad	/* Now move the new log file into place */
103559003Shm	if (noaction)
1036111781Sgad		printf("Start new log...\n");
103759003Shm	else {
103894352Ssheldonh		strlcpy(tfile, log, sizeof(tfile));
103994352Ssheldonh		strlcat(tfile, ".XXXXXX", sizeof(tfile));
104094352Ssheldonh		mkstemp(tfile);
1041111780Sgad		fd = creat(tfile, ent->permissions);
104259003Shm		if (fd < 0)
104359003Shm			err(1, "can't start new log");
1044111779Sgad		if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
1045111779Sgad			if (fchown(fd, ent->uid, ent->gid))
1046111779Sgad			    err(1, "can't chown new log file");
104759003Shm		(void) close(fd);
1048111388Sgad		if (!(flags & CE_BINARY)) {
1049111388Sgad			/* Add status message to new log file */
1050111779Sgad			if (log_trim(tfile, ent))
105159003Shm				err(1, "can't add status message to log");
1052111388Sgad		}
105359003Shm	}
105459003Shm	if (noaction)
1055111780Sgad		printf("chmod %o %s...\n", ent->permissions, log);
105694352Ssheldonh	else {
1057111780Sgad		(void) chmod(tfile, ent->permissions);
105894352Ssheldonh		if (rename(tfile, log) < 0) {
105994352Ssheldonh			err(1, "can't start new log");
106094352Ssheldonh			(void) unlink(tfile);
106194352Ssheldonh		}
106294352Ssheldonh	}
106325443Sache
1064111966Sgad	/*
1065111966Sgad	 * Find out if there is a process to signal.  If nosignal (-s) was
1066111966Sgad	 * specified, then do not signal any process.  Note that nosignal
1067111966Sgad	 * will trigger a warning message if the rotated logfile needs to
1068111966Sgad	 * be compressed, *unless* -R was specified.  This is because there
1069111966Sgad	 * presumably still are process(es) writing to the old logfile, but
1070111966Sgad	 * we assume that a -sR request comes from a process which writes
1071111966Sgad	 * to the logfile, and as such, that process has already made sure
1072111966Sgad	 * that the logfile is not presently in use.
1073111966Sgad	 */
107425443Sache	pid = 0;
107525443Sache	need_notification = notified = 0;
1076111779Sgad	if (ent->pid_file != NULL) {
107725443Sache		need_notification = 1;
1078111966Sgad		if (!nosignal)
1079111966Sgad			pid = get_pid(ent->pid_file);	/* the normal case! */
1080111966Sgad		else if (rotatereq)
1081111966Sgad			need_notification = 0;
108225443Sache	}
108325443Sache	if (pid) {
108425443Sache		if (noaction) {
108525443Sache			notified = 1;
1086111780Sgad			printf("kill -%d %d\n", ent->sig, (int) pid);
1087111780Sgad		} else if (kill(pid, ent->sig))
108859003Shm			warn("can't notify daemon, pid %d", (int) pid);
108925443Sache		else {
109025443Sache			notified = 1;
109125443Sache			if (verbose)
109259003Shm				printf("daemon pid %d notified\n", (int) pid);
109325443Sache		}
109425443Sache	}
109580638Sobrien	if ((flags & CE_COMPACT) || (flags & CE_BZCOMPACT)) {
109625443Sache		if (need_notification && !notified)
109780646Sobrien			warnx(
109880646Sobrien			    "log %s not compressed because daemon not notified",
109980646Sobrien			    log);
110025443Sache		else if (noaction)
110159003Shm			printf("Compress %s.0\n", log);
110225443Sache		else {
110325443Sache			if (notified) {
110425443Sache				if (verbose)
110525443Sache					printf("small pause to allow daemon to close log\n");
110631460Sache				sleep(10);
110725443Sache			}
110859004Shm			if (archtodir) {
110980646Sobrien				(void) snprintf(file1, sizeof(file1), "%s/%s",
111080646Sobrien				    dirpart, namepart);
111180638Sobrien				if (flags & CE_COMPACT)
1112107916Ssobomax					compress_log(file1,
1113107916Ssobomax					    flags & CE_COMPACTWAIT);
111480638Sobrien				else if (flags & CE_BZCOMPACT)
1115107916Ssobomax					bzcompress_log(file1,
1116107916Ssobomax					    flags & CE_COMPACTWAIT);
111759004Shm			} else {
111880638Sobrien				if (flags & CE_COMPACT)
1119107916Ssobomax					compress_log(log,
1120107916Ssobomax					    flags & CE_COMPACTWAIT);
112180638Sobrien				else if (flags & CE_BZCOMPACT)
1122107916Ssobomax					bzcompress_log(log,
1123107916Ssobomax					    flags & CE_COMPACTWAIT);
112459004Shm			}
112525443Sache		}
112659003Shm	}
112713244Sgraichen}
112813244Sgraichen
112913244Sgraichen/* Log the fact that the logs were turned over */
113059004Shmstatic int
1131111768Sgadlog_trim(const char *log, const struct conf_entry *log_ent)
113213244Sgraichen{
113359003Shm	FILE *f;
1134111388Sgad	const char *xtra;
113559003Shm
113659003Shm	if ((f = fopen(log, "a")) == NULL)
113759003Shm		return (-1);
1138111388Sgad	xtra = "";
1139111768Sgad	if (log_ent->def_cfg)
1140111388Sgad		xtra = " using <default> rule";
1141111772Sgad	if (log_ent->r_reason != NULL)
1142111772Sgad		fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s%s\n",
1143111772Sgad		    daytime, hostname, (int) getpid(), log_ent->r_reason, xtra);
1144111772Sgad	else
1145111772Sgad		fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s\n",
1146111772Sgad		    daytime, hostname, (int) getpid(), xtra);
114759003Shm	if (fclose(f) == EOF)
114859003Shm		err(1, "log_trim: fclose:");
114959003Shm	return (0);
115013244Sgraichen}
115113244Sgraichen
115259004Shm/* Fork of gzip to compress the old log file */
115359004Shmstatic void
1154107916Ssobomaxcompress_log(char *log, int dowait)
115513244Sgraichen{
115659003Shm	pid_t pid;
115771299Sjedgar	char tmp[MAXPATHLEN];
115859003Shm
1159107916Ssobomax	while (dowait && (wait(NULL) > 0 || errno == EINTR))
1160107916Ssobomax		;
116171299Sjedgar	(void) snprintf(tmp, sizeof(tmp), "%s.0", log);
116225443Sache	pid = fork();
116359003Shm	if (pid < 0)
116480638Sobrien		err(1, "gzip fork");
116559003Shm	else if (!pid) {
116679452Sbrian		(void) execl(_PATH_GZIP, _PATH_GZIP, "-f", tmp, (char *)0);
116743071Swollman		err(1, _PATH_GZIP);
116859003Shm	}
116913244Sgraichen}
117013244Sgraichen
117180638Sobrien/* Fork of bzip2 to compress the old log file */
117280638Sobrienstatic void
1173107916Ssobomaxbzcompress_log(char *log, int dowait)
117480638Sobrien{
117580638Sobrien	pid_t pid;
117680638Sobrien	char tmp[MAXPATHLEN];
117780638Sobrien
1178107916Ssobomax	while (dowait && (wait(NULL) > 0 || errno == EINTR))
1179107916Ssobomax		;
118080638Sobrien	snprintf(tmp, sizeof(tmp), "%s.0", log);
118180638Sobrien	pid = fork();
118280638Sobrien	if (pid < 0)
118380638Sobrien		err(1, "bzip2 fork");
118480638Sobrien	else if (!pid) {
118586360Sobrien		execl(_PATH_BZIP2, _PATH_BZIP2, "-f", tmp, (char *)0);
118680638Sobrien		err(1, _PATH_BZIP2);
118780638Sobrien	}
118880638Sobrien}
118980638Sobrien
119013244Sgraichen/* Return size in kilobytes of a file */
119159004Shmstatic int
119259004Shmsizefile(char *file)
119313244Sgraichen{
119459003Shm	struct stat sb;
119513244Sgraichen
119659003Shm	if (stat(file, &sb) < 0)
119759003Shm		return (-1);
119859003Shm	return (kbytes(dbtob(sb.st_blocks)));
119913244Sgraichen}
120013244Sgraichen
120113244Sgraichen/* Return the age of old log file (file.0) */
120259004Shmstatic int
120359004Shmage_old_log(char *file)
120413244Sgraichen{
120559003Shm	struct stat sb;
120659003Shm	char tmp[MAXPATHLEN + sizeof(".0") + sizeof(COMPRESS_POSTFIX) + 1];
120713244Sgraichen
120859004Shm	if (archtodir) {
120959004Shm		char *p;
121059004Shm
121159004Shm		/* build name of archive directory into tmp */
121259004Shm		if (*archdirname == '/') {	/* absolute */
121371299Sjedgar			strlcpy(tmp, archdirname, sizeof(tmp));
121459004Shm		} else {	/* relative */
121559004Shm			/* get directory part of logfile */
121671299Sjedgar			strlcpy(tmp, file, sizeof(tmp));
121759004Shm			if ((p = rindex(tmp, '/')) == NULL)
121859004Shm				tmp[0] = '\0';
121959004Shm			else
122059004Shm				*(p + 1) = '\0';
122171299Sjedgar			strlcat(tmp, archdirname, sizeof(tmp));
122259004Shm		}
122359004Shm
122471299Sjedgar		strlcat(tmp, "/", sizeof(tmp));
122559004Shm
122659004Shm		/* get filename part of logfile */
122759004Shm		if ((p = rindex(file, '/')) == NULL)
122871299Sjedgar			strlcat(tmp, file, sizeof(tmp));
122959004Shm		else
123071299Sjedgar			strlcat(tmp, p + 1, sizeof(tmp));
123159004Shm	} else {
123271299Sjedgar		(void) strlcpy(tmp, file, sizeof(tmp));
123359004Shm	}
123459004Shm
123559003Shm	if (stat(strcat(tmp, ".0"), &sb) < 0)
123659003Shm		if (stat(strcat(tmp, COMPRESS_POSTFIX), &sb) < 0)
123759003Shm			return (-1);
1238111781Sgad	return ((int)(timenow - sb.st_mtime + 1800) / 3600);
123913244Sgraichen}
124013244Sgraichen
124159004Shmstatic pid_t
124280640Sobrienget_pid(const char *pid_file)
124325443Sache{
124425443Sache	FILE *f;
124559003Shm	char line[BUFSIZ];
124625443Sache	pid_t pid = 0;
124713244Sgraichen
124859003Shm	if ((f = fopen(pid_file, "r")) == NULL)
124925443Sache		warn("can't open %s pid file to restart a daemon",
125059003Shm		    pid_file);
125125443Sache	else {
125259003Shm		if (fgets(line, BUFSIZ, f)) {
125325443Sache			pid = atol(line);
125425443Sache			if (pid < MIN_PID || pid > MAX_PID) {
125580646Sobrien				warnx("preposterous process number: %d",
125680646Sobrien				   (int)pid);
125725443Sache				pid = 0;
125825443Sache			}
125925443Sache		} else
126025443Sache			warn("can't read %s pid file to restart a daemon",
126159003Shm			    pid_file);
126259003Shm		(void) fclose(f);
126325443Sache	}
1264111392Sgad	return (pid);
126525443Sache}
126625443Sache
126713244Sgraichen/* Skip Over Blanks */
1268111820Sgadstatic char *
126959004Shmsob(char *p)
127013244Sgraichen{
127159003Shm	while (p && *p && isspace(*p))
127259003Shm		p++;
127359003Shm	return (p);
127413244Sgraichen}
127513244Sgraichen
127613244Sgraichen/* Skip Over Non-Blanks */
1277111820Sgadstatic char *
127859004Shmson(char *p)
127913244Sgraichen{
128059003Shm	while (p && *p && !isspace(*p))
128159003Shm		p++;
128259003Shm	return (p);
128313244Sgraichen}
128443071Swollman
128543071Swollman/*
128659004Shm * Parse a limited subset of ISO 8601. The specific format is as follows:
128743071Swollman *
128859004Shm * [CC[YY[MM[DD]]]][THH[MM[SS]]]	(where `T' is the literal letter)
128943071Swollman *
129059004Shm * We don't accept a timezone specification; missing fields (including timezone)
129159004Shm * are defaulted to the current date but time zero.
129243071Swollman */
129343071Swollmanstatic time_t
129493659Scjcparse8601(char *s, char *errline)
129543071Swollman{
129659003Shm	char *t;
129793659Scjc	time_t tsecs;
129859003Shm	struct tm tm, *tmp;
129959003Shm	u_long ul;
130043071Swollman
130143071Swollman	tmp = localtime(&timenow);
130243071Swollman	tm = *tmp;
130343071Swollman
130443071Swollman	tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
130543071Swollman
130643071Swollman	ul = strtoul(s, &t, 10);
130743071Swollman	if (*t != '\0' && *t != 'T')
1308111392Sgad		return (-1);
130943071Swollman
131043071Swollman	/*
131159003Shm	 * Now t points either to the end of the string (if no time was
131259003Shm	 * provided) or to the letter `T' which separates date and time in
131359003Shm	 * ISO 8601.  The pointer arithmetic is the same for either case.
131443071Swollman	 */
131543071Swollman	switch (t - s) {
131643071Swollman	case 8:
131743071Swollman		tm.tm_year = ((ul / 1000000) - 19) * 100;
131843071Swollman		ul = ul % 1000000;
131943071Swollman	case 6:
132080666Swollman		tm.tm_year -= tm.tm_year % 100;
132143071Swollman		tm.tm_year += ul / 10000;
132243071Swollman		ul = ul % 10000;
132343071Swollman	case 4:
132443071Swollman		tm.tm_mon = (ul / 100) - 1;
132543071Swollman		ul = ul % 100;
132643071Swollman	case 2:
132743071Swollman		tm.tm_mday = ul;
132843071Swollman	case 0:
132943071Swollman		break;
133043071Swollman	default:
1331111392Sgad		return (-1);
133243071Swollman	}
133343071Swollman
133443071Swollman	/* sanity check */
133543071Swollman	if (tm.tm_year < 70 || tm.tm_mon < 0 || tm.tm_mon > 12
133643071Swollman	    || tm.tm_mday < 1 || tm.tm_mday > 31)
1337111392Sgad		return (-1);
133843071Swollman
133943071Swollman	if (*t != '\0') {
134043071Swollman		s = ++t;
134143071Swollman		ul = strtoul(s, &t, 10);
134243071Swollman		if (*t != '\0' && !isspace(*t))
1343111392Sgad			return (-1);
134443071Swollman
134543071Swollman		switch (t - s) {
134643071Swollman		case 6:
134743071Swollman			tm.tm_sec = ul % 100;
134843071Swollman			ul /= 100;
134943071Swollman		case 4:
135043071Swollman			tm.tm_min = ul % 100;
135143071Swollman			ul /= 100;
135243071Swollman		case 2:
135343071Swollman			tm.tm_hour = ul;
135443071Swollman		case 0:
135543071Swollman			break;
135643071Swollman		default:
1357111392Sgad			return (-1);
135843071Swollman		}
135943071Swollman
136043071Swollman		/* sanity check */
136143071Swollman		if (tm.tm_sec < 0 || tm.tm_sec > 60 || tm.tm_min < 0
136243071Swollman		    || tm.tm_min > 59 || tm.tm_hour < 0 || tm.tm_hour > 23)
1363111392Sgad			return (-1);
136443071Swollman	}
136593659Scjc	if ((tsecs = mktime(&tm)) == -1)
136699209Smaxim		errx(1, "nonexistent time:\n%s", errline);
1367111392Sgad	return (tsecs);
136843071Swollman}
136959004Shm
137059004Shm/* physically move file */
137159004Shmstatic void
1372111779Sgadmovefile(char *from, char *to, int perm, uid_t owner_uid, gid_t group_gid)
137359004Shm{
137459004Shm	FILE *src, *dst;
137559004Shm	int c;
137659004Shm
137759004Shm	if ((src = fopen(from, "r")) == NULL)
137859004Shm		err(1, "can't fopen %s for reading", from);
137959004Shm	if ((dst = fopen(to, "w")) == NULL)
138059004Shm		err(1, "can't fopen %s for writing", to);
1381111779Sgad	if (owner_uid != (uid_t)-1 || group_gid != (gid_t)-1) {
1382111779Sgad		if (fchown(fileno(dst), owner_uid, group_gid))
1383111779Sgad			err(1, "can't fchown %s", to);
1384111779Sgad	}
138559004Shm	if (fchmod(fileno(dst), perm))
138659004Shm		err(1, "can't fchmod %s", to);
138759004Shm
138859004Shm	while ((c = getc(src)) != EOF) {
138959004Shm		if ((putc(c, dst)) == EOF)
139059004Shm			err(1, "error writing to %s", to);
139159004Shm	}
139259004Shm
139359004Shm	if (ferror(src))
139459004Shm		err(1, "error reading from %s", from);
139559004Shm	if ((fclose(src)) != 0)
139659004Shm		err(1, "can't fclose %s", to);
139759004Shm	if ((fclose(dst)) != 0)
139859004Shm		err(1, "can't fclose %s", from);
139959004Shm	if ((unlink(from)) != 0)
140059004Shm		err(1, "can't unlink %s", from);
140159004Shm}
140259004Shm
140359004Shm/* create one or more directory components of a path */
140459004Shmstatic void
140559004Shmcreatedir(char *dirpart)
140659004Shm{
1407111398Sgad	int res;
140859004Shm	char *s, *d;
140971299Sjedgar	char mkdirpath[MAXPATHLEN];
141059004Shm	struct stat st;
141159004Shm
141259004Shm	s = dirpart;
141359004Shm	d = mkdirpath;
141459004Shm
141559004Shm	for (;;) {
141659004Shm		*d++ = *s++;
1417111398Sgad		if (*s != '/' && *s != '\0')
1418111398Sgad			continue;
1419111398Sgad		*d = '\0';
1420111398Sgad		res = lstat(mkdirpath, &st);
1421111398Sgad		if (res != 0) {
1422111398Sgad			if (noaction) {
1423111398Sgad				printf("mkdir %s\n", mkdirpath);
1424111398Sgad			} else {
1425111398Sgad				res = mkdir(mkdirpath, 0755);
1426111398Sgad				if (res != 0)
1427111398Sgad					err(1, "Error on mkdir(\"%s\") for -a",
1428111398Sgad					    mkdirpath);
1429111398Sgad			}
143059004Shm		}
143159004Shm		if (*s == '\0')
143259004Shm			break;
143359004Shm	}
1434111398Sgad	if (verbose)
1435111398Sgad		printf("created directory '%s' for -a\n", dirpart);
143659004Shm}
143759004Shm
143859004Shm/*-
143959004Shm * Parse a cyclic time specification, the format is as follows:
144059004Shm *
144159004Shm *	[Dhh] or [Wd[Dhh]] or [Mdd[Dhh]]
144259004Shm *
144359004Shm * to rotate a logfile cyclic at
144459004Shm *
144559004Shm *	- every day (D) within a specific hour (hh)	(hh = 0...23)
144659004Shm *	- once a week (W) at a specific day (d)     OR	(d = 0..6, 0 = Sunday)
144759004Shm *	- once a month (M) at a specific day (d)	(d = 1..31,l|L)
144859004Shm *
144959004Shm * We don't accept a timezone specification; missing fields
145059004Shm * are defaulted to the current date but time zero.
145159004Shm */
145259004Shmstatic time_t
145393659ScjcparseDWM(char *s, char *errline)
145459004Shm{
145559004Shm	char *t;
145693659Scjc	time_t tsecs;
145759004Shm	struct tm tm, *tmp;
145880742Sobrien	long l;
145959004Shm	int nd;
146059004Shm	static int mtab[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
146159004Shm	int WMseen = 0;
146259004Shm	int Dseen = 0;
146359004Shm
146459004Shm	tmp = localtime(&timenow);
146559004Shm	tm = *tmp;
146659004Shm
146759004Shm	/* set no. of days per month */
146859004Shm
146959004Shm	nd = mtab[tm.tm_mon];
147059004Shm
147159004Shm	if (tm.tm_mon == 1) {
147259004Shm		if (((tm.tm_year + 1900) % 4 == 0) &&
147359004Shm		    ((tm.tm_year + 1900) % 100 != 0) &&
147459004Shm		    ((tm.tm_year + 1900) % 400 == 0)) {
147559004Shm			nd++;	/* leap year, 29 days in february */
147659004Shm		}
147759004Shm	}
147859004Shm	tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
147959004Shm
148059004Shm	for (;;) {
148159004Shm		switch (*s) {
148259004Shm		case 'D':
148359004Shm			if (Dseen)
1484111392Sgad				return (-1);
148559004Shm			Dseen++;
148659004Shm			s++;
148780742Sobrien			l = strtol(s, &t, 10);
148880742Sobrien			if (l < 0 || l > 23)
1489111392Sgad				return (-1);
149080742Sobrien			tm.tm_hour = l;
149159004Shm			break;
149259004Shm
149359004Shm		case 'W':
149459004Shm			if (WMseen)
1495111392Sgad				return (-1);
149659004Shm			WMseen++;
149759004Shm			s++;
149880742Sobrien			l = strtol(s, &t, 10);
149980742Sobrien			if (l < 0 || l > 6)
1500111392Sgad				return (-1);
150180742Sobrien			if (l != tm.tm_wday) {
150259004Shm				int save;
150359004Shm
150480742Sobrien				if (l < tm.tm_wday) {
150559004Shm					save = 6 - tm.tm_wday;
150680742Sobrien					save += (l + 1);
150759004Shm				} else {
150880742Sobrien					save = l - tm.tm_wday;
150959004Shm				}
151059004Shm
151159004Shm				tm.tm_mday += save;
151259004Shm
151359004Shm				if (tm.tm_mday > nd) {
151459004Shm					tm.tm_mon++;
151559004Shm					tm.tm_mday = tm.tm_mday - nd;
151659004Shm				}
151759004Shm			}
151859004Shm			break;
151959004Shm
152059004Shm		case 'M':
152159004Shm			if (WMseen)
1522111392Sgad				return (-1);
152359004Shm			WMseen++;
152459004Shm			s++;
152559004Shm			if (tolower(*s) == 'l') {
152659004Shm				tm.tm_mday = nd;
152759004Shm				s++;
152859004Shm				t = s;
152959004Shm			} else {
153080742Sobrien				l = strtol(s, &t, 10);
153180742Sobrien				if (l < 1 || l > 31)
1532111392Sgad					return (-1);
153359004Shm
153480742Sobrien				if (l > nd)
1535111392Sgad					return (-1);
153680742Sobrien				tm.tm_mday = l;
153759004Shm			}
153859004Shm			break;
153959004Shm
154059004Shm		default:
154159004Shm			return (-1);
154259004Shm			break;
154359004Shm		}
154459004Shm
154559004Shm		if (*t == '\0' || isspace(*t))
154659004Shm			break;
154759004Shm		else
154859004Shm			s = t;
154959004Shm	}
155093659Scjc	if ((tsecs = mktime(&tm)) == -1)
155199209Smaxim		errx(1, "nonexistent time:\n%s", errline);
1552111392Sgad	return (tsecs);
155359004Shm}
1554