newsyslog.c revision 119102
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
26114601Sobrien#include <sys/cdefs.h>
27114601Sobrien__FBSDID("$FreeBSD: head/usr.sbin/newsyslog/newsyslog.c 119102 2003-08-19 03:53:03Z gad $");
2813244Sgraichen
2943071Swollman#define OSF
3013244Sgraichen#ifndef COMPRESS_POSTFIX
3143071Swollman#define COMPRESS_POSTFIX ".gz"
3213244Sgraichen#endif
3380638Sobrien#ifndef	BZCOMPRESS_POSTFIX
3480638Sobrien#define	BZCOMPRESS_POSTFIX ".bz2"
3580638Sobrien#endif
3613244Sgraichen
3796001Smaxim#include <sys/param.h>
3896001Smaxim#include <sys/stat.h>
3996001Smaxim#include <sys/wait.h>
4096001Smaxim
4130160Scharnier#include <ctype.h>
4230160Scharnier#include <err.h>
4395999Smaxim#include <errno.h>
4430160Scharnier#include <fcntl.h>
45111773Sgad#include <fnmatch.h>
46106905Ssobomax#include <glob.h>
4730160Scharnier#include <grp.h>
4843071Swollman#include <paths.h>
4930160Scharnier#include <pwd.h>
5030160Scharnier#include <signal.h>
5113244Sgraichen#include <stdio.h>
5213244Sgraichen#include <stdlib.h>
5313244Sgraichen#include <string.h>
5443071Swollman#include <time.h>
5516240Salex#include <unistd.h>
5613244Sgraichen
5743071Swollman#include "pathnames.h"
5843071Swollman
59111768Sgad/*
60111768Sgad * Bit-values for the 'flags' parsed from a config-file entry.
61111768Sgad */
62111768Sgad#define CE_COMPACT	0x0001	/* Compact the achived log files with gzip. */
63111768Sgad#define CE_BZCOMPACT	0x0002	/* Compact the achived log files with bzip2. */
64111781Sgad#define CE_COMPACTWAIT	0x0004	/* wait until compressing one file finishes */
65111768Sgad				/*    before starting the next step. */
66111768Sgad#define CE_BINARY	0x0008	/* Logfile is in binary, do not add status */
67111768Sgad				/*    messages to logfile(s) when rotating. */
68111781Sgad#define CE_NOSIGNAL	0x0010	/* There is no process to signal when */
69111768Sgad				/*    trimming this file. */
70111781Sgad#define CE_TRIMAT	0x0020	/* trim file at a specific time. */
71111781Sgad#define CE_GLOB		0x0040	/* name of the log is file name pattern. */
72112003Sgad#define CE_SIGNALGROUP	0x0080	/* Signal a process-group instead of a single */
73112003Sgad				/*    process when trimming this file. */
74114137Sgad#define CE_CREATE	0x0100	/* Create the log file if it does not exist. */
7543071Swollman
76111781Sgad#define MIN_PID         5	/* Don't touch pids lower than this */
77111781Sgad#define MAX_PID		99999	/* was lower, see /usr/include/sys/proc.h */
78111781Sgad
79111781Sgad#define kbytes(size)  (((size) + 1023) >> 10)
80111781Sgad
8113244Sgraichenstruct conf_entry {
8259003Shm	char *log;		/* Name of the log */
8359003Shm	char *pid_file;		/* PID file */
84111772Sgad	char *r_reason;		/* The reason this file is being rotated */
85114137Sgad	int firstcreate;	/* Creating log for the first time (-C). */
86111772Sgad	int rotate;		/* Non-zero if this file should be rotated */
87111779Sgad	uid_t uid;		/* Owner of log */
88111779Sgad	gid_t gid;		/* Group of log */
8959003Shm	int numlogs;		/* Number of logs to keep */
9059003Shm	int size;		/* Size cutoff to trigger trimming the log */
9159003Shm	int hours;		/* Hours between log trimming */
9259003Shm	time_t trim_at;		/* Specific time to do trimming */
9359003Shm	int permissions;	/* File permissions on the log */
9480646Sobrien	int flags;		/* CE_COMPACT, CE_BZCOMPACT, CE_BINARY */
9559003Shm	int sig;		/* Signal to send */
96111388Sgad	int def_cfg;		/* Using the <default> rule for this file */
9759003Shm	struct conf_entry *next;/* Linked list pointer */
9813244Sgraichen};
9913244Sgraichen
100111388Sgad#define DEFAULT_MARKER "<default>"
101111388Sgad
10259004Shmint archtodir = 0;		/* Archive old logfiles to other directory */
103114137Sgadint createlogs;			/* Create (non-GLOB) logfiles which do not */
104114137Sgad				/*    already exist.  1=='for entries with */
105114137Sgad				/*    C flag', 2=='for all entries'. */
10659003Shmint verbose = 0;		/* Print out what's going on */
10759003Shmint needroot = 1;		/* Root privs are necessary */
10859003Shmint noaction = 0;		/* Don't do anything, just show it */
109111768Sgadint nosignal;			/* Do not send any signals */
11059003Shmint force = 0;			/* Force the trim no matter what */
111111772Sgadint rotatereq = 0;		/* -R = Always rotate the file(s) as given */
112111772Sgad				/*    on the command (this also requires   */
113111772Sgad				/*    that a list of files *are* given on  */
114111772Sgad				/*    the run command). */
115111772Sgadchar *requestor;		/* The name given on a -R request */
11659004Shmchar *archdirname;		/* Directory path to old logfiles archive */
117111773Sgadconst char *conf;		/* Configuration file to use */
11859003Shmtime_t timenow;
11959003Shm
12071299Sjedgarchar hostname[MAXHOSTNAMELEN];	/* hostname */
121108164Strhodeschar daytime[16];		/* timenow in human readable form */
12213244Sgraichen
123111773Sgadstatic struct conf_entry *get_worklist(char **files);
124111773Sgadstatic void parse_file(FILE *cf, const char *cfname, struct conf_entry **work_p,
125112020Sgad		struct conf_entry **glob_p, struct conf_entry **defconf_p);
12616240Salexstatic char *sob(char *p);
12716240Salexstatic char *son(char *p);
128119102Sgadstatic int isnumberstr(const char *);
12959003Shmstatic char *missing_field(char *p, char *errline);
13059003Shmstatic void do_entry(struct conf_entry * ent);
131112020Sgadstatic void expand_globs(struct conf_entry **work_p,
132112020Sgad		struct conf_entry **glob_p);
133112020Sgadstatic void free_clist(struct conf_entry **firstent);
134111388Sgadstatic void free_entry(struct conf_entry *ent);
135111388Sgadstatic struct conf_entry *init_entry(const char *fname,
136111388Sgad		struct conf_entry *src_entry);
137111781Sgadstatic void parse_args(int argc, char **argv);
13880640Sobrienstatic void usage(void);
139111779Sgadstatic void dotrim(const struct conf_entry *ent, char *log,
140111780Sgad		int numdays, int flags);
141111768Sgadstatic int log_trim(const char *log, const struct conf_entry *log_ent);
142107916Ssobomaxstatic void compress_log(char *log, int dowait);
143107916Ssobomaxstatic void bzcompress_log(char *log, int dowait);
14416240Salexstatic int sizefile(char *file);
14516240Salexstatic int age_old_log(char *file);
146112003Sgadstatic int send_signal(const struct conf_entry *ent);
14793659Scjcstatic time_t parse8601(char *s, char *errline);
148111779Sgadstatic void movefile(char *from, char *to, int perm, uid_t owner_uid,
149111779Sgad		gid_t group_gid);
150114137Sgadstatic void createdir(const struct conf_entry *ent, char *dirpart);
151114137Sgadstatic void createlog(const struct conf_entry *ent);
15293659Scjcstatic time_t parseDWM(char *s, char *errline);
15313244Sgraichen
154111768Sgad/*
155111768Sgad * All the following are defined to work on an 'int', in the
156111768Sgad * range 0 to 255, plus EOF.  Define wrappers which can take
157111768Sgad * values of type 'char', either signed or unsigned.
158111768Sgad */
159114762Sgad#define isdigitch(Anychar)    isdigit(((int) Anychar) & 255)
160111772Sgad#define isprintch(Anychar)    isprint(((int) Anychar) & 255)
161111768Sgad#define isspacech(Anychar)    isspace(((int) Anychar) & 255)
162111768Sgad#define tolowerch(Anychar)    tolower(((int) Anychar) & 255)
163111768Sgad
16459004Shmint
16559004Shmmain(int argc, char **argv)
16613244Sgraichen{
16759003Shm	struct conf_entry *p, *q;
16825443Sache
169111781Sgad	parse_args(argc, argv);
170111773Sgad	argc -= optind;
171111773Sgad	argv += optind;
172111773Sgad
17359003Shm	if (needroot && getuid() && geteuid())
17459003Shm		errx(1, "must have root privs");
175111773Sgad	p = q = get_worklist(argv);
17659003Shm
17759003Shm	while (p) {
178112020Sgad		do_entry(p);
17959003Shm		p = p->next;
180111388Sgad		free_entry(q);
18159003Shm		q = p;
18259003Shm	}
18395999Smaxim	while (wait(NULL) > 0 || errno == EINTR)
18495999Smaxim		;
18559003Shm	return (0);
18613244Sgraichen}
18713244Sgraichen
188111388Sgadstatic struct conf_entry *
189111388Sgadinit_entry(const char *fname, struct conf_entry *src_entry)
190111388Sgad{
191111388Sgad	struct conf_entry *tempwork;
192111388Sgad
193111388Sgad	if (verbose > 4)
194111388Sgad		printf("\t--> [creating entry for %s]\n", fname);
195111388Sgad
196111388Sgad	tempwork = malloc(sizeof(struct conf_entry));
197111388Sgad	if (tempwork == NULL)
198111388Sgad		err(1, "malloc of conf_entry for %s", fname);
199111388Sgad
200111388Sgad	tempwork->log = strdup(fname);
201111388Sgad	if (tempwork->log == NULL)
202111388Sgad		err(1, "strdup for %s", fname);
203111388Sgad
204111388Sgad	if (src_entry != NULL) {
205111388Sgad		tempwork->pid_file = NULL;
206111388Sgad		if (src_entry->pid_file)
207111388Sgad			tempwork->pid_file = strdup(src_entry->pid_file);
208111772Sgad		tempwork->r_reason = NULL;
209114137Sgad		tempwork->firstcreate = 0;
210111772Sgad		tempwork->rotate = 0;
211111388Sgad		tempwork->uid = src_entry->uid;
212111388Sgad		tempwork->gid = src_entry->gid;
213111388Sgad		tempwork->numlogs = src_entry->numlogs;
214111388Sgad		tempwork->size = src_entry->size;
215111388Sgad		tempwork->hours = src_entry->hours;
216111388Sgad		tempwork->trim_at = src_entry->trim_at;
217111388Sgad		tempwork->permissions = src_entry->permissions;
218111388Sgad		tempwork->flags = src_entry->flags;
219111388Sgad		tempwork->sig = src_entry->sig;
220111388Sgad		tempwork->def_cfg = src_entry->def_cfg;
221111388Sgad	} else {
222111388Sgad		/* Initialize as a "do-nothing" entry */
223111388Sgad		tempwork->pid_file = NULL;
224111772Sgad		tempwork->r_reason = NULL;
225114137Sgad		tempwork->firstcreate = 0;
226111772Sgad		tempwork->rotate = 0;
227111779Sgad		tempwork->uid = (uid_t)-1;
228111779Sgad		tempwork->gid = (gid_t)-1;
229111388Sgad		tempwork->numlogs = 1;
230111388Sgad		tempwork->size = -1;
231111388Sgad		tempwork->hours = -1;
232111388Sgad		tempwork->trim_at = (time_t)0;
233111388Sgad		tempwork->permissions = 0;
234111388Sgad		tempwork->flags = 0;
235111388Sgad		tempwork->sig = SIGHUP;
236111388Sgad		tempwork->def_cfg = 0;
237111388Sgad	}
238111388Sgad	tempwork->next = NULL;
239111388Sgad
240111388Sgad	return (tempwork);
241111388Sgad}
242111388Sgad
24359004Shmstatic void
244111388Sgadfree_entry(struct conf_entry *ent)
245111388Sgad{
246111388Sgad
247111388Sgad	if (ent == NULL)
248111388Sgad		return;
249111388Sgad
250111388Sgad	if (ent->log != NULL) {
251111388Sgad		if (verbose > 4)
252111388Sgad			printf("\t--> [freeing entry for %s]\n", ent->log);
253111388Sgad		free(ent->log);
254111388Sgad		ent->log = NULL;
255111388Sgad	}
256111388Sgad
257111388Sgad	if (ent->pid_file != NULL) {
258111388Sgad		free(ent->pid_file);
259111388Sgad		ent->pid_file = NULL;
260111388Sgad	}
261111388Sgad
262111772Sgad	if (ent->r_reason != NULL) {
263111772Sgad		free(ent->r_reason);
264111772Sgad		ent->r_reason = NULL;
265111772Sgad	}
266111772Sgad
267111388Sgad	free(ent);
268111388Sgad}
269111388Sgad
270111388Sgadstatic void
271112020Sgadfree_clist(struct conf_entry **firstent)
272112020Sgad{
273112020Sgad	struct conf_entry *ent, *nextent;
274112020Sgad
275112020Sgad	if (firstent == NULL)
276112020Sgad		return;			/* There is nothing to do. */
277112020Sgad
278112020Sgad	ent = *firstent;
279112020Sgad	firstent = NULL;
280112020Sgad
281112020Sgad	while (ent) {
282112020Sgad		nextent = ent->next;
283112020Sgad		free_entry(ent);
284112020Sgad		ent = nextent;
285112020Sgad	}
286112020Sgad}
287112020Sgad
288112020Sgadstatic void
28959004Shmdo_entry(struct conf_entry * ent)
29013244Sgraichen{
291111772Sgad#define REASON_MAX	80
29259003Shm	int size, modtime;
293111772Sgad	char temp_reason[REASON_MAX];
29459003Shm
29559003Shm	if (verbose) {
29659003Shm		if (ent->flags & CE_COMPACT)
29759003Shm			printf("%s <%dZ>: ", ent->log, ent->numlogs);
29880638Sobrien		else if (ent->flags & CE_BZCOMPACT)
29980638Sobrien			printf("%s <%dJ>: ", ent->log, ent->numlogs);
30059003Shm		else
30159003Shm			printf("%s <%d>: ", ent->log, ent->numlogs);
30259003Shm	}
30359003Shm	size = sizefile(ent->log);
30459003Shm	modtime = age_old_log(ent->log);
305111772Sgad	ent->rotate = 0;
306114137Sgad	ent->firstcreate = 0;
30759003Shm	if (size < 0) {
308114137Sgad		/*
309114137Sgad		 * If either the C flag or the -C option was specified,
310114137Sgad		 * and if we won't be creating the file, then have the
311114137Sgad		 * verbose message include a hint as to why the file
312114137Sgad		 * will not be created.
313114137Sgad		 */
314114137Sgad		temp_reason[0] = '\0';
315114137Sgad		if (createlogs > 1)
316114137Sgad			ent->firstcreate = 1;
317114137Sgad		else if ((ent->flags & CE_CREATE) && createlogs)
318114137Sgad			ent->firstcreate = 1;
319114137Sgad		else if (ent->flags & CE_CREATE)
320114137Sgad			strncpy(temp_reason, " (no -C option)", REASON_MAX);
321114137Sgad		else if (createlogs)
322114137Sgad			strncpy(temp_reason, " (no C flag)", REASON_MAX);
323114137Sgad
324114137Sgad		if (ent->firstcreate) {
325114137Sgad			if (verbose)
326114137Sgad				printf("does not exist -> will create.\n");
327114137Sgad			createlog(ent);
328114137Sgad		} else if (verbose) {
329114137Sgad			printf("does not exist, skipped%s.\n", temp_reason);
330114137Sgad		}
33159003Shm	} else {
332111772Sgad		if (ent->flags & CE_TRIMAT && !force && !rotatereq) {
33343071Swollman			if (timenow < ent->trim_at
33459003Shm			    || difftime(timenow, ent->trim_at) >= 60 * 60) {
33543071Swollman				if (verbose)
33643071Swollman					printf("--> will trim at %s",
33759003Shm					    ctime(&ent->trim_at));
33843071Swollman				return;
33943071Swollman			} else if (verbose && ent->hours <= 0) {
34043071Swollman				printf("--> time is up\n");
34143071Swollman			}
34243071Swollman		}
34359003Shm		if (verbose && (ent->size > 0))
34459003Shm			printf("size (Kb): %d [%d] ", size, ent->size);
34559003Shm		if (verbose && (ent->hours > 0))
34659003Shm			printf(" age (hr): %d [%d] ", modtime, ent->hours);
347111772Sgad
348111772Sgad		/*
349111772Sgad		 * Figure out if this logfile needs to be rotated.
350111772Sgad		 */
351111772Sgad		temp_reason[0] = '\0';
352111772Sgad		if (rotatereq) {
353111772Sgad			ent->rotate = 1;
354111772Sgad			snprintf(temp_reason, REASON_MAX, " due to -R from %s",
355111772Sgad			    requestor);
356111772Sgad		} else if (force) {
357111772Sgad			ent->rotate = 1;
358111772Sgad			snprintf(temp_reason, REASON_MAX, " due to -F request");
359111772Sgad		} else if ((ent->size > 0) && (size >= ent->size)) {
360111772Sgad			ent->rotate = 1;
361111772Sgad			snprintf(temp_reason, REASON_MAX, " due to size>%dK",
362111772Sgad			    ent->size);
363111772Sgad		} else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) {
364111772Sgad			ent->rotate = 1;
365111772Sgad		} else if ((ent->hours > 0) && ((modtime >= ent->hours) ||
366111772Sgad		    (modtime < 0))) {
367111772Sgad			ent->rotate = 1;
368111772Sgad		}
369111772Sgad
370111772Sgad		/*
371111772Sgad		 * If the file needs to be rotated, then rotate it.
372111772Sgad		 */
373111772Sgad		if (ent->rotate) {
374111772Sgad			if (temp_reason[0] != '\0')
375111772Sgad				ent->r_reason = strdup(temp_reason);
37659003Shm			if (verbose)
37759003Shm				printf("--> trimming log....\n");
37859003Shm			if (noaction && !verbose) {
37959003Shm				if (ent->flags & CE_COMPACT)
38059003Shm					printf("%s <%dZ>: trimming\n",
38159003Shm					    ent->log, ent->numlogs);
38280638Sobrien				else if (ent->flags & CE_BZCOMPACT)
38380638Sobrien					printf("%s <%dJ>: trimming\n",
38480638Sobrien					    ent->log, ent->numlogs);
38559003Shm				else
38659003Shm					printf("%s <%d>: trimming\n",
38759003Shm					    ent->log, ent->numlogs);
38859003Shm			}
389111780Sgad			dotrim(ent, ent->log, ent->numlogs, ent->flags);
39059003Shm		} else {
39159003Shm			if (verbose)
39259003Shm				printf("--> skipping\n");
39359003Shm		}
39459003Shm	}
395111772Sgad#undef REASON_MAX
39613244Sgraichen}
39713244Sgraichen
398112003Sgad/* Send a signal to the pid specified by pidfile */
399112003Sgadstatic int
400112003Sgadsend_signal(const struct conf_entry *ent)
401112003Sgad{
402112003Sgad	pid_t target_pid;
403112003Sgad	int did_notify;
404112003Sgad	FILE *f;
405112003Sgad	long minok, maxok, rval;
406112003Sgad	const char *target_name;
407112003Sgad	char *endp, *linep, line[BUFSIZ];
408112003Sgad
409112003Sgad	did_notify = 0;
410112003Sgad	f = fopen(ent->pid_file, "r");
411112003Sgad	if (f == NULL) {
412112003Sgad		warn("can't open pid file: %s", ent->pid_file);
413112003Sgad		return (did_notify);
414112003Sgad		/* NOTREACHED */
415112003Sgad	}
416112003Sgad
417112003Sgad	if (fgets(line, BUFSIZ, f) == NULL) {
418112003Sgad		/*
419112003Sgad		 * XXX - If the pid file is empty, is that really a
420112003Sgad		 *	problem?  Wouldn't that mean that the process
421112003Sgad		 *	has shut down?  In that case there would be no
422112003Sgad		 *	problem with compressing the rotated log file.
423112003Sgad		 */
424112003Sgad		if (feof(f))
425112003Sgad			warnx("pid file is empty: %s",  ent->pid_file);
426112003Sgad		else
427112003Sgad			warn("can't read from pid file: %s", ent->pid_file);
428112003Sgad		(void) fclose(f);
429112003Sgad		return (did_notify);
430112003Sgad		/* NOTREACHED */
431112003Sgad	}
432112003Sgad	(void) fclose(f);
433112003Sgad
434112003Sgad	target_name = "daemon";
435112003Sgad	minok = MIN_PID;
436112003Sgad	maxok = MAX_PID;
437112003Sgad	if (ent->flags & CE_SIGNALGROUP) {
438112003Sgad		/*
439112003Sgad		 * If we are expected to signal a process-group when
440112003Sgad		 * rotating this logfile, then the value read in should
441112003Sgad		 * be the negative of a valid process ID.
442112003Sgad		 */
443112003Sgad		target_name = "process-group";
444112003Sgad		minok = -MAX_PID;
445112003Sgad		maxok = -MIN_PID;
446112003Sgad	}
447112003Sgad
448112003Sgad	errno = 0;
449112003Sgad	linep = line;
450112003Sgad	while (*linep == ' ')
451112003Sgad		linep++;
452112003Sgad	rval = strtol(linep, &endp, 10);
453112003Sgad	if (*endp != '\0' && !isspacech(*endp)) {
454112003Sgad		warnx("pid file does not start with a valid number: %s",
455112003Sgad		    ent->pid_file);
456112003Sgad		rval = 0;
457112003Sgad	} else if (rval < minok || rval > maxok) {
458112003Sgad		warnx("bad value '%ld' for process number in %s",
459112003Sgad		    rval, ent->pid_file);
460112003Sgad		if (verbose)
461112003Sgad			warnx("\t(expecting value between %ld and %ld)",
462112003Sgad			    minok, maxok);
463112003Sgad		rval = 0;
464112003Sgad	}
465112003Sgad	if (rval == 0) {
466112003Sgad		return (did_notify);
467112003Sgad		/* NOTREACHED */
468112003Sgad	}
469112003Sgad
470112003Sgad	target_pid = rval;
471112003Sgad
472112003Sgad	if (noaction) {
473112003Sgad		did_notify = 1;
474112003Sgad		printf("\tkill -%d %d\n", ent->sig, (int) target_pid);
475112003Sgad	} else if (kill(target_pid, ent->sig)) {
476112003Sgad		/*
477112003Sgad		 * XXX - Iff the error was "no such process", should that
478112003Sgad		 *	really be an error for us?  Perhaps the process
479112003Sgad		 *	is already gone, in which case there would be no
480112003Sgad		 *	problem with compressing the rotated log file.
481112003Sgad		 */
482112003Sgad		warn("can't notify %s, pid %d", target_name,
483112003Sgad		    (int) target_pid);
484112003Sgad	} else {
485112003Sgad		did_notify = 1;
486112003Sgad		if (verbose)
487112003Sgad			printf("%s pid %d notified\n", target_name,
488112003Sgad			    (int) target_pid);
489112003Sgad	}
490112003Sgad
491112003Sgad	return (did_notify);
492112003Sgad}
493112003Sgad
49459004Shmstatic void
495111781Sgadparse_args(int argc, char **argv)
49613244Sgraichen{
497111781Sgad	int ch;
49859003Shm	char *p;
49913244Sgraichen
500111781Sgad	timenow = time(NULL);
501108164Strhodes	(void)strncpy(daytime, ctime(&timenow) + 4, 15);
50259003Shm	daytime[15] = '\0';
50313244Sgraichen
50459003Shm	/* Let's get our hostname */
505111781Sgad	(void)gethostname(hostname, sizeof(hostname));
50613244Sgraichen
50713244Sgraichen	/* Truncate domain */
508111781Sgad	if ((p = strchr(hostname, '.')) != NULL)
50913244Sgraichen		*p = '\0';
510111768Sgad
511111768Sgad	/* Parse command line options. */
512114137Sgad	while ((ch = getopt(argc, argv, "a:f:nrsvCFR:")) != -1)
513111781Sgad		switch (ch) {
51459004Shm		case 'a':
51559004Shm			archtodir++;
51659004Shm			archdirname = optarg;
51759004Shm			break;
518111768Sgad		case 'f':
519111768Sgad			conf = optarg;
520111768Sgad			break;
521111768Sgad		case 'n':
522111768Sgad			noaction++;
523111768Sgad			break;
52459003Shm		case 'r':
52559003Shm			needroot = 0;
52659003Shm			break;
527111768Sgad		case 's':
528111768Sgad			nosignal = 1;
529111768Sgad			break;
53059003Shm		case 'v':
53159003Shm			verbose++;
53259003Shm			break;
533114137Sgad		case 'C':
534114137Sgad			/* Useful for things like rc.diskless... */
535114137Sgad			createlogs++;
536114137Sgad			break;
53734584Spst		case 'F':
53834584Spst			force++;
53934584Spst			break;
540111772Sgad		case 'R':
541111772Sgad			rotatereq++;
542111772Sgad			requestor = strdup(optarg);
543111772Sgad			break;
544111781Sgad		case 'm':	/* Used by OpenBSD for "monitor mode" */
54559003Shm		default:
54659003Shm			usage();
547111768Sgad			/* NOTREACHED */
54859003Shm		}
549111772Sgad
550111772Sgad	if (rotatereq) {
551111772Sgad		if (optind == argc) {
552111772Sgad			warnx("At least one filename must be given when -R is specified.");
553111772Sgad			usage();
554111772Sgad			/* NOTREACHED */
555111772Sgad		}
556111772Sgad		/* Make sure "requestor" value is safe for a syslog message. */
557111772Sgad		for (p = requestor; *p != '\0'; p++) {
558111772Sgad			if (!isprintch(*p) && (*p != '\t'))
559111772Sgad				*p = '.';
560111772Sgad		}
561111772Sgad	}
56243071Swollman}
56313244Sgraichen
56459004Shmstatic void
56559004Shmusage(void)
56613244Sgraichen{
56780646Sobrien
56880646Sobrien	fprintf(stderr,
569114137Sgad	    "usage: newsyslog [-CFnrsv] [-a directory] [-f config-file]\n"
570111772Sgad	    "                 [ [-R requestor] filename ... ]\n");
57159003Shm	exit(1);
57213244Sgraichen}
57313244Sgraichen
57459004Shm/*
575111773Sgad * Parse a configuration file and return a linked list of all the logs
576111773Sgad * which should be processed.
57713244Sgraichen */
57859003Shmstatic struct conf_entry *
579111773Sgadget_worklist(char **files)
58013244Sgraichen{
58159003Shm	FILE *f;
582111773Sgad	const char *fname;
583111773Sgad	char **given;
584111773Sgad	struct conf_entry *defconf, *dupent, *ent, *firstnew;
585112020Sgad	struct conf_entry *globlist, *lastnew, *worklist;
586112020Sgad	int gmatch, fnres;
587111773Sgad
588112020Sgad	defconf = globlist = worklist = NULL;
589111773Sgad
590111773Sgad	fname = conf;
591111773Sgad	if (fname == NULL)
592111773Sgad		fname = _PATH_CONF;
593111773Sgad
594111773Sgad	if (strcmp(fname, "-") != 0)
595111773Sgad		f = fopen(fname, "r");
596111773Sgad	else {
597111773Sgad		f = stdin;
598111773Sgad		fname = "<stdin>";
599111773Sgad	}
600111773Sgad	if (!f)
601111773Sgad		err(1, "%s", conf);
602111773Sgad
603112020Sgad	parse_file(f, fname, &worklist, &globlist, &defconf);
604111773Sgad	(void) fclose(f);
605111773Sgad
606111773Sgad	/*
607111773Sgad	 * All config-file information has been read in and turned into
608112020Sgad	 * a worklist and a globlist.  If there were no specific files
609112020Sgad	 * given on the run command, then the only thing left to do is to
610112020Sgad	 * call a routine which finds all files matched by the globlist
611112020Sgad	 * and adds them to the worklist.  Then return the worklist.
612111773Sgad	 */
613111773Sgad	if (*files == NULL) {
614112020Sgad		expand_globs(&worklist, &globlist);
615112020Sgad		free_clist(&globlist);
616111773Sgad		if (defconf != NULL)
617111773Sgad			free_entry(defconf);
618111773Sgad		return (worklist);
619111773Sgad		/* NOTREACHED */
620111773Sgad	}
621111773Sgad
622111773Sgad	/*
623111773Sgad	 * If newsyslog was given a specific list of files to process,
624111773Sgad	 * it may be that some of those files were not listed in any
625111773Sgad	 * config file.  Those unlisted files should get the default
626111773Sgad	 * rotation action.  First, create the default-rotation action
627111773Sgad	 * if none was found in a system config file.
628111773Sgad	 */
629111773Sgad	if (defconf == NULL) {
630111773Sgad		defconf = init_entry(DEFAULT_MARKER, NULL);
631111773Sgad		defconf->numlogs = 3;
632111773Sgad		defconf->size = 50;
633111773Sgad		defconf->permissions = S_IRUSR|S_IWUSR;
634111773Sgad	}
635111773Sgad
636111773Sgad	/*
637111773Sgad	 * If newsyslog was run with a list of specific filenames,
638111773Sgad	 * then create a new worklist which has only those files in
639111773Sgad	 * it, picking up the rotation-rules for those files from
640111773Sgad	 * the original worklist.
641111773Sgad	 *
642111773Sgad	 * XXX - Note that this will copy multiple rules for a single
643111773Sgad	 *	logfile, if multiple entries are an exact match for
644111773Sgad	 *	that file.  That matches the historic behavior, but do
645111773Sgad	 *	we want to continue to allow it?  If so, it should
646111773Sgad	 *	probably be handled more intelligently.
647111773Sgad	 */
648112020Sgad	firstnew = lastnew = NULL;
649111773Sgad	for (given = files; *given; ++given) {
650111773Sgad		/*
651111773Sgad		 * First try to find exact-matches for this given file.
652111773Sgad		 */
653112020Sgad		gmatch = 0;
654111773Sgad		for (ent = worklist; ent; ent = ent->next) {
655111773Sgad			if (strcmp(ent->log, *given) == 0) {
656111773Sgad				gmatch++;
657111773Sgad				dupent = init_entry(*given, ent);
658111773Sgad				if (!firstnew)
659111773Sgad					firstnew = dupent;
660111773Sgad				else
661112020Sgad					lastnew->next = dupent;
662112020Sgad				lastnew = dupent;
663111773Sgad			}
664111773Sgad		}
665111773Sgad		if (gmatch) {
666111773Sgad			if (verbose > 2)
667111773Sgad				printf("\t+ Matched entry %s\n", *given);
668111773Sgad			continue;
669111773Sgad		}
670111773Sgad
671111773Sgad		/*
672111773Sgad		 * There was no exact-match for this given file, so look
673111773Sgad		 * for a "glob" entry which does match.
674111773Sgad		 */
675112020Sgad		gmatch = 0;
676112020Sgad		if (verbose > 2 && globlist != NULL)
677112020Sgad			printf("\t+ Checking globs for %s\n", *given);
678112020Sgad		for (ent = globlist; ent; ent = ent->next) {
679112020Sgad			fnres = fnmatch(ent->log, *given, FNM_PATHNAME);
680112020Sgad			if (verbose > 2)
681112020Sgad				printf("\t+    = %d for pattern %s\n", fnres,
682112020Sgad				    ent->log);
683112020Sgad			if (fnres == 0) {
684111773Sgad				gmatch++;
685111773Sgad				dupent = init_entry(*given, ent);
686111773Sgad				if (!firstnew)
687111773Sgad					firstnew = dupent;
688111773Sgad				else
689112020Sgad					lastnew->next = dupent;
690112020Sgad				lastnew = dupent;
691112020Sgad				/* This new entry is not a glob! */
692111773Sgad				dupent->flags &= ~CE_GLOB;
693111773Sgad				/* Only allow a match to one glob-entry */
694111773Sgad				break;
695111773Sgad			}
696111773Sgad		}
697111773Sgad		if (gmatch) {
698111773Sgad			if (verbose > 2)
699111773Sgad				printf("\t+ Matched %s via %s\n", *given,
700111773Sgad				    ent->log);
701111773Sgad			continue;
702111773Sgad		}
703111773Sgad
704111773Sgad		/*
705111773Sgad		 * This given file was not found in any config file, so
706111773Sgad		 * add a worklist item based on the default entry.
707111773Sgad		 */
708111773Sgad		if (verbose > 2)
709111773Sgad			printf("\t+ No entry matched %s  (will use %s)\n",
710111773Sgad			    *given, DEFAULT_MARKER);
711111773Sgad		dupent = init_entry(*given, defconf);
712111773Sgad		if (!firstnew)
713111773Sgad			firstnew = dupent;
714111773Sgad		else
715112020Sgad			lastnew->next = dupent;
716111773Sgad		/* Mark that it was *not* found in a config file */
717111773Sgad		dupent->def_cfg = 1;
718112020Sgad		lastnew = dupent;
719111773Sgad	}
720111773Sgad
721111773Sgad	/*
722112020Sgad	 * Free all the entries in the original work list, the list of
723112020Sgad	 * glob entries, and the default entry.
724111773Sgad	 */
725112020Sgad	free_clist(&worklist);
726112020Sgad	free_clist(&globlist);
727112020Sgad	free_entry(defconf);
728111773Sgad
729112020Sgad	/* And finally, return a worklist which matches the given files. */
730112013Sgad	return (firstnew);
731111773Sgad}
732111773Sgad
733111773Sgad/*
734112020Sgad * Expand the list of entries with filename patterns, and add all files
735112020Sgad * which match those glob-entries onto the worklist.
736112020Sgad */
737112020Sgadstatic void
738112020Sgadexpand_globs(struct conf_entry **work_p, struct conf_entry **glob_p)
739112020Sgad{
740112020Sgad	int gmatch, gres, i;
741112020Sgad	char *mfname;
742112020Sgad	struct conf_entry *dupent, *ent, *firstmatch, *globent;
743112020Sgad	struct conf_entry *lastmatch;
744112020Sgad	glob_t pglob;
745112020Sgad	struct stat st_fm;
746112020Sgad
747112020Sgad	if ((glob_p == NULL) || (*glob_p == NULL))
748112020Sgad		return;			/* There is nothing to do. */
749112020Sgad
750112020Sgad	/*
751112020Sgad	 * The worklist contains all fully-specified (non-GLOB) names.
752112020Sgad	 *
753112020Sgad	 * Now expand the list of filename-pattern (GLOB) entries into
754112020Sgad	 * a second list, which (by definition) will only match files
755112020Sgad	 * that already exist.  Do not add a glob-related entry for any
756112020Sgad	 * file which already exists in the fully-specified list.
757112020Sgad	 */
758112020Sgad	firstmatch = lastmatch = NULL;
759112020Sgad	for (globent = *glob_p; globent; globent = globent->next) {
760112020Sgad
761112020Sgad		gres = glob(globent->log, GLOB_NOCHECK, NULL, &pglob);
762112020Sgad		if (gres != 0) {
763112020Sgad			warn("cannot expand pattern (%d): %s", gres,
764112020Sgad			    globent->log);
765112020Sgad			continue;
766112020Sgad		}
767112020Sgad
768112020Sgad		if (verbose > 2)
769112020Sgad			printf("\t+ Expanding pattern %s\n", globent->log);
770112020Sgad		for (i = 0; i < pglob.gl_matchc; i++) {
771112020Sgad			mfname = pglob.gl_pathv[i];
772112020Sgad
773112020Sgad			/* See if this file already has a specific entry. */
774112020Sgad			gmatch = 0;
775112020Sgad			for (ent = *work_p; ent; ent = ent->next) {
776112020Sgad				if (strcmp(mfname, ent->log) == 0) {
777112020Sgad					gmatch++;
778112020Sgad					break;
779112020Sgad				}
780112020Sgad			}
781112020Sgad			if (gmatch)
782112020Sgad				continue;
783112020Sgad
784112020Sgad			/* Make sure the named matched is a file. */
785112020Sgad			gres = lstat(mfname, &st_fm);
786112020Sgad			if (gres != 0) {
787112020Sgad				/* Error on a file that glob() matched?!? */
788112020Sgad				warn("Skipping %s - lstat() error", mfname);
789112020Sgad				continue;
790112020Sgad			}
791112020Sgad			if (!S_ISREG(st_fm.st_mode)) {
792112020Sgad				/* We only rotate files! */
793112020Sgad				if (verbose > 2)
794112020Sgad					printf("\t+  . skipping %s (!file)\n",
795112020Sgad					    mfname);
796112020Sgad				continue;
797112020Sgad			}
798112020Sgad
799112020Sgad			if (verbose > 2)
800112020Sgad				printf("\t+  . add file %s\n", mfname);
801112020Sgad			dupent = init_entry(mfname, globent);
802112020Sgad			if (!firstmatch)
803112020Sgad				firstmatch = dupent;
804112020Sgad			else
805112020Sgad				lastmatch->next = dupent;
806112020Sgad			lastmatch = dupent;
807112020Sgad			/* This new entry is not a glob! */
808112020Sgad			dupent->flags &= ~CE_GLOB;
809112020Sgad		}
810112020Sgad		globfree(&pglob);
811112020Sgad		if (verbose > 2)
812112020Sgad			printf("\t+ Done with pattern %s\n", globent->log);
813112020Sgad	}
814112020Sgad
815112020Sgad	/* Add the list of matched files to the end of the worklist. */
816112020Sgad	if (!*work_p)
817112020Sgad		*work_p = firstmatch;
818112020Sgad	else {
819112020Sgad		ent = *work_p;
820112020Sgad		while (ent->next)
821112020Sgad			ent = ent->next;
822112020Sgad		ent->next = firstmatch;
823112020Sgad	}
824112020Sgad
825112020Sgad}
826112020Sgad
827112020Sgad/*
828111773Sgad * Parse a configuration file and update a linked list of all the logs to
829111773Sgad * process.
830111773Sgad */
831111773Sgadstatic void
832111773Sgadparse_file(FILE *cf, const char *cfname, struct conf_entry **work_p,
833112020Sgad    struct conf_entry **glob_p, struct conf_entry **defconf_p)
834111773Sgad{
83559003Shm	char line[BUFSIZ], *parse, *q;
836107737Ssobomax	char *cp, *errline, *group;
837112020Sgad	struct conf_entry *lastglob, *lastwork, *working;
838111781Sgad	struct passwd *pwd;
83959003Shm	struct group *grp;
840112020Sgad	int eol, special;
84113244Sgraichen
842111773Sgad	/*
843111773Sgad	 * XXX - for now, assume that only one config file will be read,
844111773Sgad	 *	ie, this routine is only called one time.
845111773Sgad	 */
846112020Sgad	lastglob = lastwork = NULL;
84780646Sobrien
848111773Sgad	while (fgets(line, BUFSIZ, cf)) {
849107737Ssobomax		if ((line[0] == '\n') || (line[0] == '#') ||
850107737Ssobomax		    (strlen(line) == 0))
85159003Shm			continue;
85259003Shm		errline = strdup(line);
853107737Ssobomax		for (cp = line + 1; *cp != '\0'; cp++) {
854107737Ssobomax			if (*cp != '#')
855107737Ssobomax				continue;
856107737Ssobomax			if (*(cp - 1) == '\\') {
857107737Ssobomax				strcpy(cp - 1, cp);
858107737Ssobomax				cp--;
859107737Ssobomax				continue;
860107737Ssobomax			}
861107737Ssobomax			*cp = '\0';
862107737Ssobomax			break;
863107737Ssobomax		}
86460373Sdes
86560373Sdes		q = parse = missing_field(sob(line), errline);
86660373Sdes		parse = son(line);
86760373Sdes		if (!*parse)
86880646Sobrien			errx(1, "malformed line (missing fields):\n%s",
86980646Sobrien			    errline);
87060373Sdes		*parse = '\0';
87160373Sdes
872112020Sgad		special = 0;
873111388Sgad		working = init_entry(q, NULL);
874111388Sgad		if (strcasecmp(DEFAULT_MARKER, q) == 0) {
875112020Sgad			special = 1;
876111773Sgad			if (defconf_p == NULL) {
877111773Sgad				warnx("Ignoring entry for %s in %s!", q,
878111773Sgad				    cfname);
879111773Sgad				free_entry(working);
880111773Sgad				continue;
881111773Sgad			} else if (*defconf_p != NULL) {
882111388Sgad				warnx("Ignoring duplicate entry for %s!", q);
883111388Sgad				free_entry(working);
884111388Sgad				continue;
885111388Sgad			}
886111773Sgad			*defconf_p = working;
88759003Shm		}
88813244Sgraichen
88959003Shm		q = parse = missing_field(sob(++parse), errline);
89059003Shm		parse = son(parse);
89125518Sbrian		if (!*parse)
89280646Sobrien			errx(1, "malformed line (missing fields):\n%s",
89380646Sobrien			    errline);
89459003Shm		*parse = '\0';
89559003Shm		if ((group = strchr(q, ':')) != NULL ||
89659003Shm		    (group = strrchr(q, '.')) != NULL) {
89759003Shm			*group++ = '\0';
89859003Shm			if (*q) {
899119102Sgad				if (!(isnumberstr(q))) {
900111781Sgad					if ((pwd = getpwnam(q)) == NULL)
90159003Shm						errx(1,
90280646Sobrien				     "error in config file; unknown user:\n%s",
90359003Shm						    errline);
904111781Sgad					working->uid = pwd->pw_uid;
90559003Shm				} else
90659003Shm					working->uid = atoi(q);
90759003Shm			} else
908111779Sgad				working->uid = (uid_t)-1;
90913244Sgraichen
91059003Shm			q = group;
91159003Shm			if (*q) {
912119102Sgad				if (!(isnumberstr(q))) {
91359003Shm					if ((grp = getgrnam(q)) == NULL)
91459003Shm						errx(1,
91580646Sobrien				    "error in config file; unknown group:\n%s",
91659003Shm						    errline);
91759003Shm					working->gid = grp->gr_gid;
91859003Shm				} else
91959003Shm					working->gid = atoi(q);
92059003Shm			} else
921111779Sgad				working->gid = (gid_t)-1;
92213244Sgraichen
92359003Shm			q = parse = missing_field(sob(++parse), errline);
92459003Shm			parse = son(parse);
92559003Shm			if (!*parse)
92680646Sobrien				errx(1, "malformed line (missing fields):\n%s",
92780646Sobrien				    errline);
92859003Shm			*parse = '\0';
929111779Sgad		} else {
930111779Sgad			working->uid = (uid_t)-1;
931111779Sgad			working->gid = (gid_t)-1;
932111779Sgad		}
93359003Shm
93459003Shm		if (!sscanf(q, "%o", &working->permissions))
93559003Shm			errx(1, "error in config file; bad permissions:\n%s",
93659003Shm			    errline);
93759003Shm
93859003Shm		q = parse = missing_field(sob(++parse), errline);
93959003Shm		parse = son(parse);
94025518Sbrian		if (!*parse)
94180646Sobrien			errx(1, "malformed line (missing fields):\n%s",
94280646Sobrien			    errline);
94359003Shm		*parse = '\0';
944111400Sgad		if (!sscanf(q, "%d", &working->numlogs) || working->numlogs < 0)
945111400Sgad			errx(1, "error in config file; bad value for count of logs to save:\n%s",
94659003Shm			    errline);
94713244Sgraichen
94859003Shm		q = parse = missing_field(sob(++parse), errline);
94959003Shm		parse = son(parse);
95025518Sbrian		if (!*parse)
95180646Sobrien			errx(1, "malformed line (missing fields):\n%s",
95280646Sobrien			    errline);
95359003Shm		*parse = '\0';
954114762Sgad		if (isdigitch(*q))
95559003Shm			working->size = atoi(q);
956114762Sgad		else if (strcmp(q,"*") == 0)
95759003Shm			working->size = -1;
958114762Sgad		else {
959114762Sgad			warnx("Invalid value of '%s' for 'size' in line:\n%s",
960114762Sgad			    q, errline);
961114762Sgad			working->size = -1;
962114762Sgad		}
96359003Shm
96459003Shm		working->flags = 0;
96559003Shm		q = parse = missing_field(sob(++parse), errline);
96659003Shm		parse = son(parse);
96725518Sbrian		eol = !*parse;
96859003Shm		*parse = '\0';
96943071Swollman		{
97059003Shm			char *ep;
97159003Shm			u_long ul;
97213244Sgraichen
97343071Swollman			ul = strtoul(q, &ep, 10);
97443071Swollman			if (ep == q)
97543071Swollman				working->hours = 0;
97643071Swollman			else if (*ep == '*')
97743071Swollman				working->hours = -1;
97843071Swollman			else if (ul > INT_MAX)
97943071Swollman				errx(1, "interval is too large:\n%s", errline);
98043071Swollman			else
98143071Swollman				working->hours = ul;
98243071Swollman
98380646Sobrien			if (*ep != '\0' && *ep != '@' && *ep != '*' &&
98480646Sobrien			    *ep != '$')
98543071Swollman				errx(1, "malformed interval/at:\n%s", errline);
98643071Swollman			if (*ep == '@') {
98793659Scjc				if ((working->trim_at = parse8601(ep + 1, errline))
98859003Shm				    == (time_t) - 1)
98943071Swollman					errx(1, "malformed at:\n%s", errline);
99043071Swollman				working->flags |= CE_TRIMAT;
99159004Shm			} else if (*ep == '$') {
99293659Scjc				if ((working->trim_at = parseDWM(ep + 1, errline))
99359004Shm				    == (time_t) - 1)
99459004Shm					errx(1, "malformed at:\n%s", errline);
99559004Shm				working->flags |= CE_TRIMAT;
99643071Swollman			}
99743071Swollman		}
99843071Swollman
99925518Sbrian		if (eol)
100059003Shm			q = NULL;
100125518Sbrian		else {
100259003Shm			q = parse = sob(++parse);	/* Optional field */
100359003Shm			parse = son(parse);
100459003Shm			if (!*parse)
100559003Shm				eol = 1;
100659003Shm			*parse = '\0';
100725518Sbrian		}
100825443Sache
1009111768Sgad		for (; q && *q && !isspacech(*q); q++) {
1010111768Sgad			switch (tolowerch(*q)) {
1011111768Sgad			case 'b':
101259003Shm				working->flags |= CE_BINARY;
1013111768Sgad				break;
1014114137Sgad			case 'c':
1015111768Sgad				/*
1016114137Sgad				 * XXX - 	Ick! Ugly! Remove ASAP!
1017114137Sgad				 * We want `c' and `C' for "create".  But we
1018114137Sgad				 * will temporarily treat `c' as `g', because
1019114137Sgad				 * FreeBSD releases <= 4.8 have a typo of
1020114137Sgad				 * checking  ('G' || 'c')  for CE_GLOB.
1021111768Sgad				 */
1022114137Sgad				if (*q == 'c') {
1023114137Sgad					warnx("Assuming 'g' for 'c' in flags for line:\n%s",
1024114137Sgad					    errline);
1025114137Sgad					warnx("The 'c' flag will eventually mean 'CREATE'");
1026114137Sgad					working->flags |= CE_GLOB;
1027114137Sgad					break;
1028114137Sgad				}
1029114137Sgad				working->flags |= CE_CREATE;
1030114137Sgad				break;
1031111768Sgad			case 'g':
1032106905Ssobomax				working->flags |= CE_GLOB;
1033111768Sgad				break;
1034111768Sgad			case 'j':
1035111768Sgad				working->flags |= CE_BZCOMPACT;
1036111768Sgad				break;
1037111768Sgad			case 'n':
1038111768Sgad				working->flags |= CE_NOSIGNAL;
1039111768Sgad				break;
1040112003Sgad			case 'u':
1041112003Sgad				working->flags |= CE_SIGNALGROUP;
1042112003Sgad				break;
1043111768Sgad			case 'w':
1044107916Ssobomax				working->flags |= CE_COMPACTWAIT;
1045111768Sgad				break;
1046111768Sgad			case 'z':
1047111768Sgad				working->flags |= CE_COMPACT;
1048111768Sgad				break;
1049111768Sgad			case '-':
1050111768Sgad				break;
1051111781Sgad			case 'f':	/* Used by OpenBSD for "CE_FOLLOW" */
1052111781Sgad			case 'm':	/* Used by OpenBSD for "CE_MONITOR" */
1053111781Sgad			case 'p':	/* Used by NetBSD  for "CE_PLAIN0" */
1054111768Sgad			default:
105580646Sobrien				errx(1, "illegal flag in config file -- %c",
105680646Sobrien				    *q);
1057111768Sgad			}
105859003Shm		}
105959003Shm
106025518Sbrian		if (eol)
106159003Shm			q = NULL;
106225518Sbrian		else {
106359003Shm			q = parse = sob(++parse);	/* Optional field */
106459003Shm			parse = son(parse);
106559003Shm			if (!*parse)
106659003Shm				eol = 1;
106759003Shm			*parse = '\0';
106825518Sbrian		}
106925443Sache
107025443Sache		working->pid_file = NULL;
107125443Sache		if (q && *q) {
107225443Sache			if (*q == '/')
107325443Sache				working->pid_file = strdup(q);
107436817Sache			else if (isdigit(*q))
107536817Sache				goto got_sig;
107659003Shm			else
107780646Sobrien				errx(1,
107880646Sobrien			"illegal pid file or signal number in config file:\n%s",
107980646Sobrien				    errline);
108025443Sache		}
108136817Sache		if (eol)
108259003Shm			q = NULL;
108336817Sache		else {
108459003Shm			q = parse = sob(++parse);	/* Optional field */
108559003Shm			*(parse = son(parse)) = '\0';
108636817Sache		}
108736817Sache
108836817Sache		working->sig = SIGHUP;
108936817Sache		if (q && *q) {
109036817Sache			if (isdigit(*q)) {
109159003Shm		got_sig:
109236817Sache				working->sig = atoi(q);
109336817Sache			} else {
109459003Shm		err_sig:
109580646Sobrien				errx(1,
109680646Sobrien				    "illegal signal number in config file:\n%s",
109780646Sobrien				    errline);
109836817Sache			}
109936817Sache			if (working->sig < 1 || working->sig >= NSIG)
110036817Sache				goto err_sig;
110136817Sache		}
1102111768Sgad
1103111768Sgad		/*
1104111768Sgad		 * Finish figuring out what pid-file to use (if any) in
1105111768Sgad		 * later processing if this logfile needs to be rotated.
1106111768Sgad		 */
1107111768Sgad		if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) {
1108111768Sgad			/*
1109111768Sgad			 * This config-entry specified 'n' for nosignal,
1110111768Sgad			 * see if it also specified an explicit pid_file.
1111111768Sgad			 * This would be a pretty pointless combination.
1112111768Sgad			 */
1113111768Sgad			if (working->pid_file != NULL) {
1114111768Sgad				warnx("Ignoring '%s' because flag 'n' was specified in line:\n%s",
1115111768Sgad				    working->pid_file, errline);
1116111768Sgad				free(working->pid_file);
1117111768Sgad				working->pid_file = NULL;
1118111768Sgad			}
1119111768Sgad		} else if (working->pid_file == NULL) {
1120111768Sgad			/*
1121111768Sgad			 * This entry did not specify the 'n' flag, which
1122111768Sgad			 * means it should signal syslogd unless it had
1123112003Sgad			 * specified some other pid-file (and obviously the
1124112003Sgad			 * syslog pid-file will not be for a process-group).
1125112003Sgad			 * Also, we should only try to notify syslog if we
1126112003Sgad			 * are root.
1127111768Sgad			 */
1128112003Sgad			if (working->flags & CE_SIGNALGROUP) {
1129112003Sgad				warnx("Ignoring flag 'U' in line:\n%s",
1130112003Sgad				    errline);
1131112003Sgad				working->flags &= ~CE_SIGNALGROUP;
1132112003Sgad			}
1133111768Sgad			if (needroot)
1134111768Sgad				working->pid_file = strdup(_PATH_SYSLOGPID);
1135111768Sgad		}
1136111768Sgad
1137112020Sgad		/*
1138112020Sgad		 * Add this entry to the appropriate list of entries, unless
1139112020Sgad		 * it was some kind of special entry (eg: <default>).
1140112020Sgad		 */
1141112020Sgad		if (special) {
1142112020Sgad			;			/* Do not add to any list */
1143112020Sgad		} else if (working->flags & CE_GLOB) {
1144112020Sgad			if (!*glob_p)
1145112020Sgad				*glob_p = working;
1146112020Sgad			else
1147112020Sgad				lastglob->next = working;
1148112020Sgad			lastglob = working;
1149112020Sgad		} else {
1150112020Sgad			if (!*work_p)
1151112020Sgad				*work_p = working;
1152112020Sgad			else
1153112020Sgad				lastwork->next = working;
1154112020Sgad			lastwork = working;
1155112020Sgad		}
1156112020Sgad
115759003Shm		free(errline);
1158111768Sgad		errline = NULL;
115959003Shm	}
116013244Sgraichen}
116113244Sgraichen
116259003Shmstatic char *
116359004Shmmissing_field(char *p, char *errline)
116413244Sgraichen{
116580646Sobrien
116659003Shm	if (!p || !*p)
116759003Shm		errx(1, "missing field in config file:\n%s", errline);
116859003Shm	return (p);
116913244Sgraichen}
117013244Sgraichen
117159004Shmstatic void
1172111780Sgaddotrim(const struct conf_entry *ent, char *log, int numdays, int flags)
117313244Sgraichen{
117471299Sjedgar	char dirpart[MAXPATHLEN], namepart[MAXPATHLEN];
117571299Sjedgar	char file1[MAXPATHLEN], file2[MAXPATHLEN];
117671299Sjedgar	char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN];
117780638Sobrien	char jfile1[MAXPATHLEN];
117894352Ssheldonh	char tfile[MAXPATHLEN];
117959003Shm	int notified, need_notification, fd, _numdays;
118059003Shm	struct stat st;
118113244Sgraichen
118259004Shm	if (archtodir) {
118359004Shm		char *p;
118413244Sgraichen
118559004Shm		/* build complete name of archive directory into dirpart */
118659004Shm		if (*archdirname == '/') {	/* absolute */
118771299Sjedgar			strlcpy(dirpart, archdirname, sizeof(dirpart));
118859004Shm		} else {	/* relative */
118959004Shm			/* get directory part of logfile */
119071299Sjedgar			strlcpy(dirpart, log, sizeof(dirpart));
119159004Shm			if ((p = rindex(dirpart, '/')) == NULL)
119259004Shm				dirpart[0] = '\0';
119359004Shm			else
119459004Shm				*(p + 1) = '\0';
119571299Sjedgar			strlcat(dirpart, archdirname, sizeof(dirpart));
119659004Shm		}
119759004Shm
119859004Shm		/* check if archive directory exists, if not, create it */
119959004Shm		if (lstat(dirpart, &st))
1200114137Sgad			createdir(ent, dirpart);
120159004Shm
120259004Shm		/* get filename part of logfile */
120359004Shm		if ((p = rindex(log, '/')) == NULL)
120471299Sjedgar			strlcpy(namepart, log, sizeof(namepart));
120559004Shm		else
120671299Sjedgar			strlcpy(namepart, p + 1, sizeof(namepart));
120759004Shm
120859004Shm		/* name of oldest log */
120980646Sobrien		(void) snprintf(file1, sizeof(file1), "%s/%s.%d", dirpart,
121080646Sobrien		    namepart, numdays);
121171299Sjedgar		(void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
121271299Sjedgar		    COMPRESS_POSTFIX);
121380638Sobrien		snprintf(jfile1, sizeof(jfile1), "%s%s", file1,
121480638Sobrien		    BZCOMPRESS_POSTFIX);
121559004Shm	} else {
121659004Shm		/* name of oldest log */
121771299Sjedgar		(void) snprintf(file1, sizeof(file1), "%s.%d", log, numdays);
121871299Sjedgar		(void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
121971299Sjedgar		    COMPRESS_POSTFIX);
122080638Sobrien		snprintf(jfile1, sizeof(jfile1), "%s%s", file1,
122180638Sobrien		    BZCOMPRESS_POSTFIX);
122259004Shm	}
122359004Shm
122459003Shm	if (noaction) {
1225111967Sgad		printf("\trm -f %s\n", file1);
1226111967Sgad		printf("\trm -f %s\n", zfile1);
1227111967Sgad		printf("\trm -f %s\n", jfile1);
122859003Shm	} else {
122959003Shm		(void) unlink(file1);
123059003Shm		(void) unlink(zfile1);
123180638Sobrien		(void) unlink(jfile1);
123259003Shm	}
123313244Sgraichen
123459003Shm	/* Move down log files */
123518188Sjkh	_numdays = numdays;	/* preserve */
123659003Shm	while (numdays--) {
123759004Shm
123871299Sjedgar		(void) strlcpy(file2, file1, sizeof(file2));
123959004Shm
124059004Shm		if (archtodir)
124180646Sobrien			(void) snprintf(file1, sizeof(file1), "%s/%s.%d",
124280646Sobrien			    dirpart, namepart, numdays);
124359004Shm		else
124480646Sobrien			(void) snprintf(file1, sizeof(file1), "%s.%d", log,
124580646Sobrien			    numdays);
124659004Shm
124771299Sjedgar		(void) strlcpy(zfile1, file1, sizeof(zfile1));
124871299Sjedgar		(void) strlcpy(zfile2, file2, sizeof(zfile2));
124959003Shm		if (lstat(file1, &st)) {
125080646Sobrien			(void) strlcat(zfile1, COMPRESS_POSTFIX,
125180646Sobrien			    sizeof(zfile1));
125280646Sobrien			(void) strlcat(zfile2, COMPRESS_POSTFIX,
125380646Sobrien			    sizeof(zfile2));
125480638Sobrien			if (lstat(zfile1, &st)) {
125580638Sobrien				strlcpy(zfile1, file1, sizeof(zfile1));
125680638Sobrien				strlcpy(zfile2, file2, sizeof(zfile2));
125780638Sobrien				strlcat(zfile1, BZCOMPRESS_POSTFIX,
125880638Sobrien				    sizeof(zfile1));
125980638Sobrien				strlcat(zfile2, BZCOMPRESS_POSTFIX,
126080638Sobrien				    sizeof(zfile2));
126180638Sobrien				if (lstat(zfile1, &st))
126280638Sobrien					continue;
126380638Sobrien			}
126459003Shm		}
126559003Shm		if (noaction) {
1266111967Sgad			printf("\tmv %s %s\n", zfile1, zfile2);
1267111967Sgad			printf("\tchmod %o %s\n", ent->permissions, zfile2);
1268111779Sgad			if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
1269111967Sgad				printf("\tchown %u:%u %s\n",
1270111779Sgad				    ent->uid, ent->gid, zfile2);
127159003Shm		} else {
127259003Shm			(void) rename(zfile1, zfile2);
1273111780Sgad			if (chmod(zfile2, ent->permissions))
1274111780Sgad				warn("can't chmod %s", file2);
1275111779Sgad			if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
1276111779Sgad				if (chown(zfile2, ent->uid, ent->gid))
1277111779Sgad					warn("can't chown %s", zfile2);
127859003Shm		}
127959003Shm	}
1280111388Sgad	if (!noaction && !(flags & CE_BINARY)) {
1281111388Sgad		/* Report the trimming to the old log */
1282111779Sgad		(void) log_trim(log, ent);
1283111388Sgad	}
128413244Sgraichen
128518188Sjkh	if (!_numdays) {
128618075Sjkh		if (noaction)
1287111967Sgad			printf("\trm %s\n", log);
128818075Sjkh		else
128959003Shm			(void) unlink(log);
129059003Shm	} else {
129118075Sjkh		if (noaction)
1292111967Sgad			printf("\tmv %s to %s\n", log, file1);
129359004Shm		else {
129459004Shm			if (archtodir)
1295111780Sgad				movefile(log, file1, ent->permissions, ent->uid,
1296111779Sgad				    ent->gid);
129759004Shm			else
129859004Shm				(void) rename(log, file1);
129959004Shm		}
130018075Sjkh	}
130118075Sjkh
1302111781Sgad	/* Now move the new log file into place */
1303114137Sgad	/* XXX - We should replace the above 'rename' with 'link(log, file1)'
1304114137Sgad	 *	then replace the following with 'createfile(ent)' */
1305111967Sgad	strlcpy(tfile, log, sizeof(tfile));
1306111967Sgad	strlcat(tfile, ".XXXXXX", sizeof(tfile));
1307111967Sgad	if (noaction) {
1308111781Sgad		printf("Start new log...\n");
1309111967Sgad		printf("\tmktemp %s\n", tfile);
1310111967Sgad	} else {
131194352Ssheldonh		mkstemp(tfile);
1312111780Sgad		fd = creat(tfile, ent->permissions);
131359003Shm		if (fd < 0)
131459003Shm			err(1, "can't start new log");
1315111779Sgad		if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
1316111779Sgad			if (fchown(fd, ent->uid, ent->gid))
1317111779Sgad			    err(1, "can't chown new log file");
131859003Shm		(void) close(fd);
1319111388Sgad		if (!(flags & CE_BINARY)) {
1320111388Sgad			/* Add status message to new log file */
1321111779Sgad			if (log_trim(tfile, ent))
132259003Shm				err(1, "can't add status message to log");
1323111388Sgad		}
132459003Shm	}
1325111967Sgad	if (noaction) {
1326111967Sgad		printf("\tchmod %o %s\n", ent->permissions, tfile);
1327111967Sgad		printf("\tmv %s %s\n", tfile, log);
1328111967Sgad	} else {
1329111780Sgad		(void) chmod(tfile, ent->permissions);
133094352Ssheldonh		if (rename(tfile, log) < 0) {
133194352Ssheldonh			err(1, "can't start new log");
133294352Ssheldonh			(void) unlink(tfile);
133394352Ssheldonh		}
133494352Ssheldonh	}
133525443Sache
1336111966Sgad	/*
1337111966Sgad	 * Find out if there is a process to signal.  If nosignal (-s) was
1338111966Sgad	 * specified, then do not signal any process.  Note that nosignal
1339111966Sgad	 * will trigger a warning message if the rotated logfile needs to
1340111966Sgad	 * be compressed, *unless* -R was specified.  This is because there
1341111966Sgad	 * presumably still are process(es) writing to the old logfile, but
1342111966Sgad	 * we assume that a -sR request comes from a process which writes
1343111966Sgad	 * to the logfile, and as such, that process has already made sure
1344111966Sgad	 * that the logfile is not presently in use.
1345111966Sgad	 */
134625443Sache	need_notification = notified = 0;
1347111779Sgad	if (ent->pid_file != NULL) {
134825443Sache		need_notification = 1;
1349111966Sgad		if (!nosignal)
1350112003Sgad			notified = send_signal(ent);	/* the normal case! */
1351111966Sgad		else if (rotatereq)
1352111966Sgad			need_notification = 0;
135325443Sache	}
1354112003Sgad
135580638Sobrien	if ((flags & CE_COMPACT) || (flags & CE_BZCOMPACT)) {
135625443Sache		if (need_notification && !notified)
135780646Sobrien			warnx(
1358112003Sgad			    "log %s.0 not compressed because daemon(s) not notified",
135980646Sobrien			    log);
136025443Sache		else if (noaction)
1361111967Sgad			if (flags & CE_COMPACT)
1362111967Sgad				printf("\tgzip %s.0\n", log);
1363111967Sgad			else
1364111967Sgad				printf("\tbzip2 %s.0\n", log);
136525443Sache		else {
136625443Sache			if (notified) {
136725443Sache				if (verbose)
1368112003Sgad					printf("small pause to allow daemon(s) to close log\n");
136931460Sache				sleep(10);
137025443Sache			}
137159004Shm			if (archtodir) {
137280646Sobrien				(void) snprintf(file1, sizeof(file1), "%s/%s",
137380646Sobrien				    dirpart, namepart);
137480638Sobrien				if (flags & CE_COMPACT)
1375107916Ssobomax					compress_log(file1,
1376107916Ssobomax					    flags & CE_COMPACTWAIT);
137780638Sobrien				else if (flags & CE_BZCOMPACT)
1378107916Ssobomax					bzcompress_log(file1,
1379107916Ssobomax					    flags & CE_COMPACTWAIT);
138059004Shm			} else {
138180638Sobrien				if (flags & CE_COMPACT)
1382107916Ssobomax					compress_log(log,
1383107916Ssobomax					    flags & CE_COMPACTWAIT);
138480638Sobrien				else if (flags & CE_BZCOMPACT)
1385107916Ssobomax					bzcompress_log(log,
1386107916Ssobomax					    flags & CE_COMPACTWAIT);
138759004Shm			}
138825443Sache		}
138959003Shm	}
139013244Sgraichen}
139113244Sgraichen
139213244Sgraichen/* Log the fact that the logs were turned over */
139359004Shmstatic int
1394111768Sgadlog_trim(const char *log, const struct conf_entry *log_ent)
139513244Sgraichen{
139659003Shm	FILE *f;
1397111388Sgad	const char *xtra;
139859003Shm
139959003Shm	if ((f = fopen(log, "a")) == NULL)
140059003Shm		return (-1);
1401111388Sgad	xtra = "";
1402111768Sgad	if (log_ent->def_cfg)
1403111388Sgad		xtra = " using <default> rule";
1404114137Sgad	if (log_ent->firstcreate)
1405114137Sgad		fprintf(f, "%s %s newsyslog[%d]: logfile first created%s\n",
1406114137Sgad		    daytime, hostname, (int) getpid(), xtra);
1407114137Sgad	else if (log_ent->r_reason != NULL)
1408111772Sgad		fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s%s\n",
1409111772Sgad		    daytime, hostname, (int) getpid(), log_ent->r_reason, xtra);
1410111772Sgad	else
1411111772Sgad		fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s\n",
1412111772Sgad		    daytime, hostname, (int) getpid(), xtra);
141359003Shm	if (fclose(f) == EOF)
141459003Shm		err(1, "log_trim: fclose:");
141559003Shm	return (0);
141613244Sgraichen}
141713244Sgraichen
141859004Shm/* Fork of gzip to compress the old log file */
141959004Shmstatic void
1420107916Ssobomaxcompress_log(char *log, int dowait)
142113244Sgraichen{
142259003Shm	pid_t pid;
142371299Sjedgar	char tmp[MAXPATHLEN];
142459003Shm
1425107916Ssobomax	while (dowait && (wait(NULL) > 0 || errno == EINTR))
1426107916Ssobomax		;
142771299Sjedgar	(void) snprintf(tmp, sizeof(tmp), "%s.0", log);
142825443Sache	pid = fork();
142959003Shm	if (pid < 0)
143080638Sobrien		err(1, "gzip fork");
143159003Shm	else if (!pid) {
143279452Sbrian		(void) execl(_PATH_GZIP, _PATH_GZIP, "-f", tmp, (char *)0);
143343071Swollman		err(1, _PATH_GZIP);
143459003Shm	}
143513244Sgraichen}
143613244Sgraichen
143780638Sobrien/* Fork of bzip2 to compress the old log file */
143880638Sobrienstatic void
1439107916Ssobomaxbzcompress_log(char *log, int dowait)
144080638Sobrien{
144180638Sobrien	pid_t pid;
144280638Sobrien	char tmp[MAXPATHLEN];
144380638Sobrien
1444107916Ssobomax	while (dowait && (wait(NULL) > 0 || errno == EINTR))
1445107916Ssobomax		;
144680638Sobrien	snprintf(tmp, sizeof(tmp), "%s.0", log);
144780638Sobrien	pid = fork();
144880638Sobrien	if (pid < 0)
144980638Sobrien		err(1, "bzip2 fork");
145080638Sobrien	else if (!pid) {
145186360Sobrien		execl(_PATH_BZIP2, _PATH_BZIP2, "-f", tmp, (char *)0);
145280638Sobrien		err(1, _PATH_BZIP2);
145380638Sobrien	}
145480638Sobrien}
145580638Sobrien
145613244Sgraichen/* Return size in kilobytes of a file */
145759004Shmstatic int
145859004Shmsizefile(char *file)
145913244Sgraichen{
146059003Shm	struct stat sb;
146113244Sgraichen
146259003Shm	if (stat(file, &sb) < 0)
146359003Shm		return (-1);
146459003Shm	return (kbytes(dbtob(sb.st_blocks)));
146513244Sgraichen}
146613244Sgraichen
146713244Sgraichen/* Return the age of old log file (file.0) */
146859004Shmstatic int
146959004Shmage_old_log(char *file)
147013244Sgraichen{
147159003Shm	struct stat sb;
1472114764Sgad	char *endp;
1473114764Sgad	char tmp[MAXPATHLEN + sizeof(".0") + sizeof(COMPRESS_POSTFIX) +
1474114764Sgad		sizeof(BZCOMPRESS_POSTFIX) + 1];
147513244Sgraichen
147659004Shm	if (archtodir) {
147759004Shm		char *p;
147859004Shm
147959004Shm		/* build name of archive directory into tmp */
148059004Shm		if (*archdirname == '/') {	/* absolute */
148171299Sjedgar			strlcpy(tmp, archdirname, sizeof(tmp));
148259004Shm		} else {	/* relative */
148359004Shm			/* get directory part of logfile */
148471299Sjedgar			strlcpy(tmp, file, sizeof(tmp));
148559004Shm			if ((p = rindex(tmp, '/')) == NULL)
148659004Shm				tmp[0] = '\0';
148759004Shm			else
148859004Shm				*(p + 1) = '\0';
148971299Sjedgar			strlcat(tmp, archdirname, sizeof(tmp));
149059004Shm		}
149159004Shm
149271299Sjedgar		strlcat(tmp, "/", sizeof(tmp));
149359004Shm
149459004Shm		/* get filename part of logfile */
149559004Shm		if ((p = rindex(file, '/')) == NULL)
149671299Sjedgar			strlcat(tmp, file, sizeof(tmp));
149759004Shm		else
149871299Sjedgar			strlcat(tmp, p + 1, sizeof(tmp));
149959004Shm	} else {
150071299Sjedgar		(void) strlcpy(tmp, file, sizeof(tmp));
150159004Shm	}
150259004Shm
1503114764Sgad	strlcat(tmp, ".0", sizeof(tmp));
1504114764Sgad	if (stat(tmp, &sb) < 0) {
1505114764Sgad		/*
1506114764Sgad		 * A plain '.0' file does not exist.  Try again, first
1507114764Sgad		 * with the added suffix of '.gz', then with an added
1508114764Sgad		 * suffix of '.bz2' instead of '.gz'.
1509114764Sgad		 */
1510114764Sgad		endp = strchr(tmp, '\0');
1511114764Sgad		strlcat(tmp, COMPRESS_POSTFIX, sizeof(tmp));
1512114764Sgad		if (stat(tmp, &sb) < 0) {
1513114764Sgad			*endp = '\0';		/* Remove .gz */
1514114764Sgad			strlcat(tmp, BZCOMPRESS_POSTFIX, sizeof(tmp));
1515114764Sgad			if (stat(tmp, &sb) < 0)
1516114764Sgad				return (-1);
1517114764Sgad		}
1518114764Sgad	}
1519111781Sgad	return ((int)(timenow - sb.st_mtime + 1800) / 3600);
152013244Sgraichen}
152113244Sgraichen
152213244Sgraichen/* Skip Over Blanks */
1523111820Sgadstatic char *
152459004Shmsob(char *p)
152513244Sgraichen{
152659003Shm	while (p && *p && isspace(*p))
152759003Shm		p++;
152859003Shm	return (p);
152913244Sgraichen}
153013244Sgraichen
153113244Sgraichen/* Skip Over Non-Blanks */
1532111820Sgadstatic char *
153359004Shmson(char *p)
153413244Sgraichen{
153559003Shm	while (p && *p && !isspace(*p))
153659003Shm		p++;
153759003Shm	return (p);
153813244Sgraichen}
153943071Swollman
1540119102Sgad/* Check if string is actually a number */
1541119102Sgadstatic int
1542119102Sgadisnumberstr(const char *string)
1543119102Sgad{
1544119102Sgad	while (*string) {
1545119102Sgad		if (!isdigitch(*string++))
1546119102Sgad			return (0);
1547119102Sgad	}
1548119102Sgad	return (1);
1549119102Sgad}
1550119102Sgad
155143071Swollman/*
155259004Shm * Parse a limited subset of ISO 8601. The specific format is as follows:
155343071Swollman *
155459004Shm * [CC[YY[MM[DD]]]][THH[MM[SS]]]	(where `T' is the literal letter)
155543071Swollman *
155659004Shm * We don't accept a timezone specification; missing fields (including timezone)
155759004Shm * are defaulted to the current date but time zero.
155843071Swollman */
155943071Swollmanstatic time_t
156093659Scjcparse8601(char *s, char *errline)
156143071Swollman{
156259003Shm	char *t;
156393659Scjc	time_t tsecs;
156459003Shm	struct tm tm, *tmp;
156559003Shm	u_long ul;
156643071Swollman
156743071Swollman	tmp = localtime(&timenow);
156843071Swollman	tm = *tmp;
156943071Swollman
157043071Swollman	tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
157143071Swollman
157243071Swollman	ul = strtoul(s, &t, 10);
157343071Swollman	if (*t != '\0' && *t != 'T')
1574111392Sgad		return (-1);
157543071Swollman
157643071Swollman	/*
157759003Shm	 * Now t points either to the end of the string (if no time was
157859003Shm	 * provided) or to the letter `T' which separates date and time in
157959003Shm	 * ISO 8601.  The pointer arithmetic is the same for either case.
158043071Swollman	 */
158143071Swollman	switch (t - s) {
158243071Swollman	case 8:
158343071Swollman		tm.tm_year = ((ul / 1000000) - 19) * 100;
158443071Swollman		ul = ul % 1000000;
158543071Swollman	case 6:
158680666Swollman		tm.tm_year -= tm.tm_year % 100;
158743071Swollman		tm.tm_year += ul / 10000;
158843071Swollman		ul = ul % 10000;
158943071Swollman	case 4:
159043071Swollman		tm.tm_mon = (ul / 100) - 1;
159143071Swollman		ul = ul % 100;
159243071Swollman	case 2:
159343071Swollman		tm.tm_mday = ul;
159443071Swollman	case 0:
159543071Swollman		break;
159643071Swollman	default:
1597111392Sgad		return (-1);
159843071Swollman	}
159943071Swollman
160043071Swollman	/* sanity check */
160143071Swollman	if (tm.tm_year < 70 || tm.tm_mon < 0 || tm.tm_mon > 12
160243071Swollman	    || tm.tm_mday < 1 || tm.tm_mday > 31)
1603111392Sgad		return (-1);
160443071Swollman
160543071Swollman	if (*t != '\0') {
160643071Swollman		s = ++t;
160743071Swollman		ul = strtoul(s, &t, 10);
160843071Swollman		if (*t != '\0' && !isspace(*t))
1609111392Sgad			return (-1);
161043071Swollman
161143071Swollman		switch (t - s) {
161243071Swollman		case 6:
161343071Swollman			tm.tm_sec = ul % 100;
161443071Swollman			ul /= 100;
161543071Swollman		case 4:
161643071Swollman			tm.tm_min = ul % 100;
161743071Swollman			ul /= 100;
161843071Swollman		case 2:
161943071Swollman			tm.tm_hour = ul;
162043071Swollman		case 0:
162143071Swollman			break;
162243071Swollman		default:
1623111392Sgad			return (-1);
162443071Swollman		}
162543071Swollman
162643071Swollman		/* sanity check */
162743071Swollman		if (tm.tm_sec < 0 || tm.tm_sec > 60 || tm.tm_min < 0
162843071Swollman		    || tm.tm_min > 59 || tm.tm_hour < 0 || tm.tm_hour > 23)
1629111392Sgad			return (-1);
163043071Swollman	}
163193659Scjc	if ((tsecs = mktime(&tm)) == -1)
163299209Smaxim		errx(1, "nonexistent time:\n%s", errline);
1633111392Sgad	return (tsecs);
163443071Swollman}
163559004Shm
163659004Shm/* physically move file */
163759004Shmstatic void
1638111779Sgadmovefile(char *from, char *to, int perm, uid_t owner_uid, gid_t group_gid)
163959004Shm{
164059004Shm	FILE *src, *dst;
164159004Shm	int c;
164259004Shm
164359004Shm	if ((src = fopen(from, "r")) == NULL)
164459004Shm		err(1, "can't fopen %s for reading", from);
164559004Shm	if ((dst = fopen(to, "w")) == NULL)
164659004Shm		err(1, "can't fopen %s for writing", to);
1647111779Sgad	if (owner_uid != (uid_t)-1 || group_gid != (gid_t)-1) {
1648111779Sgad		if (fchown(fileno(dst), owner_uid, group_gid))
1649111779Sgad			err(1, "can't fchown %s", to);
1650111779Sgad	}
165159004Shm	if (fchmod(fileno(dst), perm))
165259004Shm		err(1, "can't fchmod %s", to);
165359004Shm
165459004Shm	while ((c = getc(src)) != EOF) {
165559004Shm		if ((putc(c, dst)) == EOF)
165659004Shm			err(1, "error writing to %s", to);
165759004Shm	}
165859004Shm
165959004Shm	if (ferror(src))
166059004Shm		err(1, "error reading from %s", from);
166159004Shm	if ((fclose(src)) != 0)
166259004Shm		err(1, "can't fclose %s", to);
166359004Shm	if ((fclose(dst)) != 0)
166459004Shm		err(1, "can't fclose %s", from);
166559004Shm	if ((unlink(from)) != 0)
166659004Shm		err(1, "can't unlink %s", from);
166759004Shm}
166859004Shm
166959004Shm/* create one or more directory components of a path */
167059004Shmstatic void
1671114137Sgadcreatedir(const struct conf_entry *ent, char *dirpart)
167259004Shm{
1673111398Sgad	int res;
167459004Shm	char *s, *d;
167571299Sjedgar	char mkdirpath[MAXPATHLEN];
167659004Shm	struct stat st;
167759004Shm
167859004Shm	s = dirpart;
167959004Shm	d = mkdirpath;
168059004Shm
168159004Shm	for (;;) {
168259004Shm		*d++ = *s++;
1683111398Sgad		if (*s != '/' && *s != '\0')
1684111398Sgad			continue;
1685111398Sgad		*d = '\0';
1686111398Sgad		res = lstat(mkdirpath, &st);
1687111398Sgad		if (res != 0) {
1688111398Sgad			if (noaction) {
1689111967Sgad				printf("\tmkdir %s\n", mkdirpath);
1690111398Sgad			} else {
1691111398Sgad				res = mkdir(mkdirpath, 0755);
1692111398Sgad				if (res != 0)
1693111398Sgad					err(1, "Error on mkdir(\"%s\") for -a",
1694111398Sgad					    mkdirpath);
1695111398Sgad			}
169659004Shm		}
169759004Shm		if (*s == '\0')
169859004Shm			break;
169959004Shm	}
1700114137Sgad	if (verbose) {
1701114137Sgad		if (ent->firstcreate)
1702114137Sgad			printf("Created directory '%s' for new %s\n",
1703114137Sgad			    dirpart, ent->log);
1704114137Sgad		else
1705114137Sgad			printf("Created directory '%s' for -a\n", dirpart);
1706114137Sgad	}
170759004Shm}
170859004Shm
1709114137Sgad/*
1710114137Sgad * Create a new log file, destroying any currently-existing version
1711114137Sgad * of the log file in the process.  If the caller wants a backup copy
1712114137Sgad * of the file to exist, they should call 'link(logfile,logbackup)'
1713114137Sgad * before calling this routine.
1714114137Sgad */
1715114137Sgadvoid
1716114137Sgadcreatelog(const struct conf_entry *ent)
1717114137Sgad{
1718114137Sgad	int fd, failed;
1719114137Sgad	struct stat st;
1720114137Sgad	char *realfile, *slash, tempfile[MAXPATHLEN];
1721114137Sgad
1722114137Sgad	fd = -1;
1723114137Sgad	realfile = ent->log;
1724114137Sgad
1725114137Sgad	/*
1726114137Sgad	 * If this log file is being created for the first time (-C option),
1727114137Sgad	 * then it may also be true that the parent directory does not exist
1728114137Sgad	 * yet.  Check, and create that directory if it is missing.
1729114137Sgad	 */
1730114137Sgad	if (ent->firstcreate) {
1731114137Sgad		strlcpy(tempfile, realfile, sizeof(tempfile));
1732114137Sgad		slash = strrchr(tempfile, '/');
1733114137Sgad		if (slash != NULL) {
1734114137Sgad			*slash = '\0';
1735114137Sgad			failed = lstat(tempfile, &st);
1736114137Sgad			if (failed && errno != ENOENT)
1737114137Sgad				err(1, "Error on lstat(%s)", tempfile);
1738114137Sgad			if (failed)
1739114137Sgad				createdir(ent, tempfile);
1740114137Sgad			else if (!S_ISDIR(st.st_mode))
1741114137Sgad				errx(1, "%s exists but is not a directory",
1742114137Sgad				    tempfile);
1743114137Sgad		}
1744114137Sgad	}
1745114137Sgad
1746114137Sgad	/*
1747114137Sgad	 * First create an unused filename, so it can be chown'ed and
1748114137Sgad	 * chmod'ed before it is moved into the real location.  mkstemp
1749114137Sgad	 * will create the file mode=600 & owned by us.  Note that all
1750114137Sgad	 * temp files will have a suffix of '.z<something>'.
1751114137Sgad	 */
1752114137Sgad	strlcpy(tempfile, realfile, sizeof(tempfile));
1753114137Sgad	strlcat(tempfile, ".zXXXXXX", sizeof(tempfile));
1754114137Sgad	if (noaction)
1755114137Sgad		printf("\tmktemp %s\n", tempfile);
1756114137Sgad	else {
1757114137Sgad		fd = mkstemp(tempfile);
1758114137Sgad		if (fd < 0)
1759114137Sgad			err(1, "can't mkstemp logfile %s", tempfile);
1760114137Sgad
1761114137Sgad		/*
1762114137Sgad		 * Add status message to what will become the new log file.
1763114137Sgad		 */
1764114137Sgad		if (!(ent->flags & CE_BINARY)) {
1765114137Sgad			if (log_trim(tempfile, ent))
1766114137Sgad				err(1, "can't add status message to log");
1767114137Sgad		}
1768114137Sgad	}
1769114137Sgad
1770114137Sgad	/* Change the owner/group, if we are supposed to */
1771114137Sgad	if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
1772114137Sgad		if (noaction)
1773114137Sgad			printf("\tchown %u:%u %s\n", ent->uid, ent->gid,
1774114137Sgad			    tempfile);
1775114137Sgad		else {
1776114137Sgad			failed = fchown(fd, ent->uid, ent->gid);
1777114137Sgad			if (failed)
1778114137Sgad				err(1, "can't fchown temp file %s", tempfile);
1779114137Sgad		}
1780114137Sgad	}
1781114137Sgad
1782114137Sgad	/*
1783114137Sgad	 * Note that if the real logfile still exists, and if the call
1784114137Sgad	 * to rename() fails, then "neither the old file nor the new
1785114137Sgad	 * file shall be changed or created" (to quote the standard).
1786114137Sgad	 * If the call succeeds, then the file will be replaced without
1787114137Sgad	 * any window where some other process might find that the file
1788114137Sgad	 * did not exist.
1789114137Sgad	 * XXX - ? It may be that for some error conditions, we could
1790114137Sgad	 *	retry by first removing the realfile and then renaming.
1791114137Sgad	 */
1792114137Sgad	if (noaction) {
1793114137Sgad		printf("\tchmod %o %s\n", ent->permissions, tempfile);
1794114137Sgad		printf("\tmv %s %s\n", tempfile, realfile);
1795114137Sgad	} else {
1796114137Sgad		failed = fchmod(fd, ent->permissions);
1797114137Sgad		if (failed)
1798114137Sgad			err(1, "can't fchmod temp file '%s'", tempfile);
1799114137Sgad		failed = rename(tempfile, realfile);
1800114137Sgad		if (failed)
1801114137Sgad			err(1, "can't mv %s to %s", tempfile, realfile);
1802114137Sgad	}
1803114137Sgad
1804114137Sgad	if (fd >= 0)
1805114137Sgad		close(fd);
1806114137Sgad}
1807114137Sgad
180859004Shm/*-
180959004Shm * Parse a cyclic time specification, the format is as follows:
181059004Shm *
181159004Shm *	[Dhh] or [Wd[Dhh]] or [Mdd[Dhh]]
181259004Shm *
181359004Shm * to rotate a logfile cyclic at
181459004Shm *
181559004Shm *	- every day (D) within a specific hour (hh)	(hh = 0...23)
181659004Shm *	- once a week (W) at a specific day (d)     OR	(d = 0..6, 0 = Sunday)
181759004Shm *	- once a month (M) at a specific day (d)	(d = 1..31,l|L)
181859004Shm *
181959004Shm * We don't accept a timezone specification; missing fields
182059004Shm * are defaulted to the current date but time zero.
182159004Shm */
182259004Shmstatic time_t
182393659ScjcparseDWM(char *s, char *errline)
182459004Shm{
182559004Shm	char *t;
182693659Scjc	time_t tsecs;
182759004Shm	struct tm tm, *tmp;
182880742Sobrien	long l;
182959004Shm	int nd;
183059004Shm	static int mtab[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
183159004Shm	int WMseen = 0;
183259004Shm	int Dseen = 0;
183359004Shm
183459004Shm	tmp = localtime(&timenow);
183559004Shm	tm = *tmp;
183659004Shm
183759004Shm	/* set no. of days per month */
183859004Shm
183959004Shm	nd = mtab[tm.tm_mon];
184059004Shm
184159004Shm	if (tm.tm_mon == 1) {
184259004Shm		if (((tm.tm_year + 1900) % 4 == 0) &&
184359004Shm		    ((tm.tm_year + 1900) % 100 != 0) &&
184459004Shm		    ((tm.tm_year + 1900) % 400 == 0)) {
184559004Shm			nd++;	/* leap year, 29 days in february */
184659004Shm		}
184759004Shm	}
184859004Shm	tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
184959004Shm
185059004Shm	for (;;) {
185159004Shm		switch (*s) {
185259004Shm		case 'D':
185359004Shm			if (Dseen)
1854111392Sgad				return (-1);
185559004Shm			Dseen++;
185659004Shm			s++;
185780742Sobrien			l = strtol(s, &t, 10);
185880742Sobrien			if (l < 0 || l > 23)
1859111392Sgad				return (-1);
186080742Sobrien			tm.tm_hour = l;
186159004Shm			break;
186259004Shm
186359004Shm		case 'W':
186459004Shm			if (WMseen)
1865111392Sgad				return (-1);
186659004Shm			WMseen++;
186759004Shm			s++;
186880742Sobrien			l = strtol(s, &t, 10);
186980742Sobrien			if (l < 0 || l > 6)
1870111392Sgad				return (-1);
187180742Sobrien			if (l != tm.tm_wday) {
187259004Shm				int save;
187359004Shm
187480742Sobrien				if (l < tm.tm_wday) {
187559004Shm					save = 6 - tm.tm_wday;
187680742Sobrien					save += (l + 1);
187759004Shm				} else {
187880742Sobrien					save = l - tm.tm_wday;
187959004Shm				}
188059004Shm
188159004Shm				tm.tm_mday += save;
188259004Shm
188359004Shm				if (tm.tm_mday > nd) {
188459004Shm					tm.tm_mon++;
188559004Shm					tm.tm_mday = tm.tm_mday - nd;
188659004Shm				}
188759004Shm			}
188859004Shm			break;
188959004Shm
189059004Shm		case 'M':
189159004Shm			if (WMseen)
1892111392Sgad				return (-1);
189359004Shm			WMseen++;
189459004Shm			s++;
189559004Shm			if (tolower(*s) == 'l') {
189659004Shm				tm.tm_mday = nd;
189759004Shm				s++;
189859004Shm				t = s;
189959004Shm			} else {
190080742Sobrien				l = strtol(s, &t, 10);
190180742Sobrien				if (l < 1 || l > 31)
1902111392Sgad					return (-1);
190359004Shm
190480742Sobrien				if (l > nd)
1905111392Sgad					return (-1);
190680742Sobrien				tm.tm_mday = l;
190759004Shm			}
190859004Shm			break;
190959004Shm
191059004Shm		default:
191159004Shm			return (-1);
191259004Shm			break;
191359004Shm		}
191459004Shm
191559004Shm		if (*t == '\0' || isspace(*t))
191659004Shm			break;
191759004Shm		else
191859004Shm			s = t;
191959004Shm	}
192093659Scjc	if ((tsecs = mktime(&tm)) == -1)
192199209Smaxim		errx(1, "nonexistent time:\n%s", errline);
1922111392Sgad	return (tsecs);
192359004Shm}
1924