newsyslog.c revision 129975
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 129975 2004-06-02 00:14:28Z 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"
58119998Sgad#include "extern.h"
5943071Swollman
60111768Sgad/*
61111768Sgad * Bit-values for the 'flags' parsed from a config-file entry.
62111768Sgad */
63111768Sgad#define CE_COMPACT	0x0001	/* Compact the achived log files with gzip. */
64111768Sgad#define CE_BZCOMPACT	0x0002	/* Compact the achived log files with bzip2. */
65111781Sgad#define CE_COMPACTWAIT	0x0004	/* wait until compressing one file finishes */
66111768Sgad				/*    before starting the next step. */
67111768Sgad#define CE_BINARY	0x0008	/* Logfile is in binary, do not add status */
68111768Sgad				/*    messages to logfile(s) when rotating. */
69111781Sgad#define CE_NOSIGNAL	0x0010	/* There is no process to signal when */
70111768Sgad				/*    trimming this file. */
71111781Sgad#define CE_TRIMAT	0x0020	/* trim file at a specific time. */
72111781Sgad#define CE_GLOB		0x0040	/* name of the log is file name pattern. */
73112003Sgad#define CE_SIGNALGROUP	0x0080	/* Signal a process-group instead of a single */
74112003Sgad				/*    process when trimming this file. */
75114137Sgad#define CE_CREATE	0x0100	/* Create the log file if it does not exist. */
7643071Swollman
77111781Sgad#define MIN_PID         5	/* Don't touch pids lower than this */
78111781Sgad#define MAX_PID		99999	/* was lower, see /usr/include/sys/proc.h */
79111781Sgad
80111781Sgad#define kbytes(size)  (((size) + 1023) >> 10)
81111781Sgad
8213244Sgraichenstruct conf_entry {
8359003Shm	char *log;		/* Name of the log */
8459003Shm	char *pid_file;		/* PID file */
85111772Sgad	char *r_reason;		/* The reason this file is being rotated */
86114137Sgad	int firstcreate;	/* Creating log for the first time (-C). */
87111772Sgad	int rotate;		/* Non-zero if this file should be rotated */
88111779Sgad	uid_t uid;		/* Owner of log */
89111779Sgad	gid_t gid;		/* Group of log */
9059003Shm	int numlogs;		/* Number of logs to keep */
9159003Shm	int size;		/* Size cutoff to trigger trimming the log */
9259003Shm	int hours;		/* Hours between log trimming */
93120361Sgad	struct ptime_data *trim_at;	/* Specific time to do trimming */
9459003Shm	int permissions;	/* File permissions on the log */
9580646Sobrien	int flags;		/* CE_COMPACT, CE_BZCOMPACT, CE_BINARY */
9659003Shm	int sig;		/* Signal to send */
97111388Sgad	int def_cfg;		/* Using the <default> rule for this file */
9859003Shm	struct conf_entry *next;/* Linked list pointer */
9913244Sgraichen};
10013244Sgraichen
101111388Sgad#define DEFAULT_MARKER "<default>"
102111388Sgad
103120361Sgadint dbg_at_times;		/* -D Show details of 'trim_at' code */
104120361Sgad
10559004Shmint archtodir = 0;		/* Archive old logfiles to other directory */
106114137Sgadint createlogs;			/* Create (non-GLOB) logfiles which do not */
107114137Sgad				/*    already exist.  1=='for entries with */
108114137Sgad				/*    C flag', 2=='for all entries'. */
10959003Shmint verbose = 0;		/* Print out what's going on */
11059003Shmint needroot = 1;		/* Root privs are necessary */
11159003Shmint noaction = 0;		/* Don't do anything, just show it */
112111768Sgadint nosignal;			/* Do not send any signals */
11359003Shmint force = 0;			/* Force the trim no matter what */
114111772Sgadint rotatereq = 0;		/* -R = Always rotate the file(s) as given */
115111772Sgad				/*    on the command (this also requires   */
116111772Sgad				/*    that a list of files *are* given on  */
117111772Sgad				/*    the run command). */
118111772Sgadchar *requestor;		/* The name given on a -R request */
11959004Shmchar *archdirname;		/* Directory path to old logfiles archive */
120111773Sgadconst char *conf;		/* Configuration file to use */
12159003Shm
122120361Sgadstruct ptime_data *dbg_timenow;	/* A "timenow" value set via -D option */
123120361Sgadstruct ptime_data *timenow;	/* The time to use for checking at-fields */
124120361Sgad
12571299Sjedgarchar hostname[MAXHOSTNAMELEN];	/* hostname */
126120361Sgadchar daytime[16];		/* The current time in human readable form,
127120361Sgad				 * used for rotation-tracking messages. */
12813244Sgraichen
129111773Sgadstatic struct conf_entry *get_worklist(char **files);
130111773Sgadstatic void parse_file(FILE *cf, const char *cfname, struct conf_entry **work_p,
131112020Sgad		struct conf_entry **glob_p, struct conf_entry **defconf_p);
13216240Salexstatic char *sob(char *p);
13316240Salexstatic char *son(char *p);
134119102Sgadstatic int isnumberstr(const char *);
13559003Shmstatic char *missing_field(char *p, char *errline);
13659003Shmstatic void do_entry(struct conf_entry * ent);
137112020Sgadstatic void expand_globs(struct conf_entry **work_p,
138112020Sgad		struct conf_entry **glob_p);
139112020Sgadstatic void free_clist(struct conf_entry **firstent);
140111388Sgadstatic void free_entry(struct conf_entry *ent);
141111388Sgadstatic struct conf_entry *init_entry(const char *fname,
142111388Sgad		struct conf_entry *src_entry);
143111781Sgadstatic void parse_args(int argc, char **argv);
144119904Sgadstatic int parse_doption(const char *doption);
14580640Sobrienstatic void usage(void);
146119927Sgadstatic void dotrim(const struct conf_entry *ent);
147119926Sgadstatic int log_trim(const char *logname, const struct conf_entry *log_ent);
148119926Sgadstatic void compress_log(char *logname, int dowait);
149119926Sgadstatic void bzcompress_log(char *logname, int dowait);
15016240Salexstatic int sizefile(char *file);
15116240Salexstatic int age_old_log(char *file);
152112003Sgadstatic int send_signal(const struct conf_entry *ent);
153129974Sgadstatic void movefile(char *from, char *to);
154114137Sgadstatic void createdir(const struct conf_entry *ent, char *dirpart);
155114137Sgadstatic void createlog(const struct conf_entry *ent);
15613244Sgraichen
157111768Sgad/*
158129975Sgad * All the following take a parameter of 'int', but expect values in the
159129975Sgad * range of unsigned char.  Define wrappers which take values of type 'char',
160129975Sgad * whether signed or unsigned, and ensure they end up in the right range.
161111768Sgad */
162129975Sgad#define	isdigitch(Anychar) isdigit((u_char)(Anychar))
163129975Sgad#define	isprintch(Anychar) isprint((u_char)(Anychar))
164129975Sgad#define	isspacech(Anychar) isspace((u_char)(Anychar))
165129975Sgad#define	tolowerch(Anychar) tolower((u_char)(Anychar))
166111768Sgad
16759004Shmint
16859004Shmmain(int argc, char **argv)
16913244Sgraichen{
17059003Shm	struct conf_entry *p, *q;
17125443Sache
172111781Sgad	parse_args(argc, argv);
173111773Sgad	argc -= optind;
174111773Sgad	argv += optind;
175111773Sgad
17659003Shm	if (needroot && getuid() && geteuid())
17759003Shm		errx(1, "must have root privs");
178111773Sgad	p = q = get_worklist(argv);
17959003Shm
18059003Shm	while (p) {
181112020Sgad		do_entry(p);
18259003Shm		p = p->next;
183111388Sgad		free_entry(q);
18459003Shm		q = p;
18559003Shm	}
18695999Smaxim	while (wait(NULL) > 0 || errno == EINTR)
18795999Smaxim		;
18859003Shm	return (0);
18913244Sgraichen}
19013244Sgraichen
191111388Sgadstatic struct conf_entry *
192111388Sgadinit_entry(const char *fname, struct conf_entry *src_entry)
193111388Sgad{
194111388Sgad	struct conf_entry *tempwork;
195111388Sgad
196111388Sgad	if (verbose > 4)
197111388Sgad		printf("\t--> [creating entry for %s]\n", fname);
198111388Sgad
199111388Sgad	tempwork = malloc(sizeof(struct conf_entry));
200111388Sgad	if (tempwork == NULL)
201111388Sgad		err(1, "malloc of conf_entry for %s", fname);
202111388Sgad
203111388Sgad	tempwork->log = strdup(fname);
204111388Sgad	if (tempwork->log == NULL)
205111388Sgad		err(1, "strdup for %s", fname);
206111388Sgad
207111388Sgad	if (src_entry != NULL) {
208111388Sgad		tempwork->pid_file = NULL;
209111388Sgad		if (src_entry->pid_file)
210111388Sgad			tempwork->pid_file = strdup(src_entry->pid_file);
211111772Sgad		tempwork->r_reason = NULL;
212114137Sgad		tempwork->firstcreate = 0;
213111772Sgad		tempwork->rotate = 0;
214111388Sgad		tempwork->uid = src_entry->uid;
215111388Sgad		tempwork->gid = src_entry->gid;
216111388Sgad		tempwork->numlogs = src_entry->numlogs;
217111388Sgad		tempwork->size = src_entry->size;
218111388Sgad		tempwork->hours = src_entry->hours;
219120361Sgad		tempwork->trim_at = NULL;
220120361Sgad		if (src_entry->trim_at != NULL)
221120361Sgad			tempwork->trim_at = ptime_init(src_entry->trim_at);
222111388Sgad		tempwork->permissions = src_entry->permissions;
223111388Sgad		tempwork->flags = src_entry->flags;
224111388Sgad		tempwork->sig = src_entry->sig;
225111388Sgad		tempwork->def_cfg = src_entry->def_cfg;
226111388Sgad	} else {
227111388Sgad		/* Initialize as a "do-nothing" entry */
228111388Sgad		tempwork->pid_file = NULL;
229111772Sgad		tempwork->r_reason = NULL;
230114137Sgad		tempwork->firstcreate = 0;
231111772Sgad		tempwork->rotate = 0;
232111779Sgad		tempwork->uid = (uid_t)-1;
233111779Sgad		tempwork->gid = (gid_t)-1;
234111388Sgad		tempwork->numlogs = 1;
235111388Sgad		tempwork->size = -1;
236111388Sgad		tempwork->hours = -1;
237120361Sgad		tempwork->trim_at = NULL;
238111388Sgad		tempwork->permissions = 0;
239111388Sgad		tempwork->flags = 0;
240111388Sgad		tempwork->sig = SIGHUP;
241111388Sgad		tempwork->def_cfg = 0;
242111388Sgad	}
243111388Sgad	tempwork->next = NULL;
244111388Sgad
245111388Sgad	return (tempwork);
246111388Sgad}
247111388Sgad
24859004Shmstatic void
249111388Sgadfree_entry(struct conf_entry *ent)
250111388Sgad{
251111388Sgad
252111388Sgad	if (ent == NULL)
253111388Sgad		return;
254111388Sgad
255111388Sgad	if (ent->log != NULL) {
256111388Sgad		if (verbose > 4)
257111388Sgad			printf("\t--> [freeing entry for %s]\n", ent->log);
258111388Sgad		free(ent->log);
259111388Sgad		ent->log = NULL;
260111388Sgad	}
261111388Sgad
262111388Sgad	if (ent->pid_file != NULL) {
263111388Sgad		free(ent->pid_file);
264111388Sgad		ent->pid_file = NULL;
265111388Sgad	}
266111388Sgad
267111772Sgad	if (ent->r_reason != NULL) {
268111772Sgad		free(ent->r_reason);
269111772Sgad		ent->r_reason = NULL;
270111772Sgad	}
271111772Sgad
272120361Sgad	if (ent->trim_at != NULL) {
273120361Sgad		ptime_free(ent->trim_at);
274120361Sgad		ent->trim_at = NULL;
275120361Sgad	}
276120361Sgad
277111388Sgad	free(ent);
278111388Sgad}
279111388Sgad
280111388Sgadstatic void
281112020Sgadfree_clist(struct conf_entry **firstent)
282112020Sgad{
283112020Sgad	struct conf_entry *ent, *nextent;
284112020Sgad
285112020Sgad	if (firstent == NULL)
286112020Sgad		return;			/* There is nothing to do. */
287112020Sgad
288112020Sgad	ent = *firstent;
289112020Sgad	firstent = NULL;
290112020Sgad
291112020Sgad	while (ent) {
292112020Sgad		nextent = ent->next;
293112020Sgad		free_entry(ent);
294112020Sgad		ent = nextent;
295112020Sgad	}
296112020Sgad}
297112020Sgad
298112020Sgadstatic void
29959004Shmdo_entry(struct conf_entry * ent)
30013244Sgraichen{
301111772Sgad#define REASON_MAX	80
30259003Shm	int size, modtime;
303120361Sgad	double diffsecs;
304111772Sgad	char temp_reason[REASON_MAX];
30559003Shm
30659003Shm	if (verbose) {
30759003Shm		if (ent->flags & CE_COMPACT)
30859003Shm			printf("%s <%dZ>: ", ent->log, ent->numlogs);
30980638Sobrien		else if (ent->flags & CE_BZCOMPACT)
31080638Sobrien			printf("%s <%dJ>: ", ent->log, ent->numlogs);
31159003Shm		else
31259003Shm			printf("%s <%d>: ", ent->log, ent->numlogs);
31359003Shm	}
31459003Shm	size = sizefile(ent->log);
31559003Shm	modtime = age_old_log(ent->log);
316111772Sgad	ent->rotate = 0;
317114137Sgad	ent->firstcreate = 0;
31859003Shm	if (size < 0) {
319114137Sgad		/*
320114137Sgad		 * If either the C flag or the -C option was specified,
321114137Sgad		 * and if we won't be creating the file, then have the
322114137Sgad		 * verbose message include a hint as to why the file
323114137Sgad		 * will not be created.
324114137Sgad		 */
325114137Sgad		temp_reason[0] = '\0';
326114137Sgad		if (createlogs > 1)
327114137Sgad			ent->firstcreate = 1;
328114137Sgad		else if ((ent->flags & CE_CREATE) && createlogs)
329114137Sgad			ent->firstcreate = 1;
330114137Sgad		else if (ent->flags & CE_CREATE)
331114137Sgad			strncpy(temp_reason, " (no -C option)", REASON_MAX);
332114137Sgad		else if (createlogs)
333114137Sgad			strncpy(temp_reason, " (no C flag)", REASON_MAX);
334114137Sgad
335114137Sgad		if (ent->firstcreate) {
336114137Sgad			if (verbose)
337114137Sgad				printf("does not exist -> will create.\n");
338114137Sgad			createlog(ent);
339114137Sgad		} else if (verbose) {
340114137Sgad			printf("does not exist, skipped%s.\n", temp_reason);
341114137Sgad		}
34259003Shm	} else {
343111772Sgad		if (ent->flags & CE_TRIMAT && !force && !rotatereq) {
344120361Sgad			diffsecs = ptimeget_diff(timenow, ent->trim_at);
345120361Sgad			if (diffsecs < 0.0) {
346120361Sgad				/* trim_at is some time in the future. */
347120361Sgad				if (verbose) {
348120361Sgad					ptime_adjust4dst(ent->trim_at,
349120361Sgad					    timenow);
35043071Swollman					printf("--> will trim at %s",
351120361Sgad					    ptimeget_ctime(ent->trim_at));
352120361Sgad				}
35343071Swollman				return;
354120361Sgad			} else if (diffsecs >= 3600.0) {
355120361Sgad				/*
356120361Sgad				 * trim_at is more than an hour in the past,
357120361Sgad				 * so find the next valid trim_at time, and
358120361Sgad				 * tell the user what that will be.
359120361Sgad				 */
360120361Sgad				if (verbose && dbg_at_times)
361120361Sgad					printf("\n\t--> prev trim at %s\t",
362120361Sgad					    ptimeget_ctime(ent->trim_at));
363120361Sgad				if (verbose) {
364120361Sgad					ptimeset_nxtime(ent->trim_at);
365120361Sgad					printf("--> will trim at %s",
366120361Sgad					    ptimeget_ctime(ent->trim_at));
367120361Sgad				}
368120361Sgad				return;
369120361Sgad			} else if (verbose && noaction && dbg_at_times) {
370120361Sgad				/*
371120361Sgad				 * If we are just debugging at-times, then
372120361Sgad				 * a detailed message is helpful.  Also
373120361Sgad				 * skip "doing" any commands, since they
374120361Sgad				 * would all be turned off by no-action.
375120361Sgad				 */
376120361Sgad				printf("\n\t--> timematch at %s",
377120361Sgad				    ptimeget_ctime(ent->trim_at));
378120361Sgad				return;
37943071Swollman			} else if (verbose && ent->hours <= 0) {
38043071Swollman				printf("--> time is up\n");
38143071Swollman			}
38243071Swollman		}
38359003Shm		if (verbose && (ent->size > 0))
38459003Shm			printf("size (Kb): %d [%d] ", size, ent->size);
38559003Shm		if (verbose && (ent->hours > 0))
38659003Shm			printf(" age (hr): %d [%d] ", modtime, ent->hours);
387111772Sgad
388111772Sgad		/*
389111772Sgad		 * Figure out if this logfile needs to be rotated.
390111772Sgad		 */
391111772Sgad		temp_reason[0] = '\0';
392111772Sgad		if (rotatereq) {
393111772Sgad			ent->rotate = 1;
394111772Sgad			snprintf(temp_reason, REASON_MAX, " due to -R from %s",
395111772Sgad			    requestor);
396111772Sgad		} else if (force) {
397111772Sgad			ent->rotate = 1;
398111772Sgad			snprintf(temp_reason, REASON_MAX, " due to -F request");
399111772Sgad		} else if ((ent->size > 0) && (size >= ent->size)) {
400111772Sgad			ent->rotate = 1;
401111772Sgad			snprintf(temp_reason, REASON_MAX, " due to size>%dK",
402111772Sgad			    ent->size);
403111772Sgad		} else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) {
404111772Sgad			ent->rotate = 1;
405111772Sgad		} else if ((ent->hours > 0) && ((modtime >= ent->hours) ||
406111772Sgad		    (modtime < 0))) {
407111772Sgad			ent->rotate = 1;
408111772Sgad		}
409111772Sgad
410111772Sgad		/*
411111772Sgad		 * If the file needs to be rotated, then rotate it.
412111772Sgad		 */
413111772Sgad		if (ent->rotate) {
414111772Sgad			if (temp_reason[0] != '\0')
415111772Sgad				ent->r_reason = strdup(temp_reason);
41659003Shm			if (verbose)
41759003Shm				printf("--> trimming log....\n");
41859003Shm			if (noaction && !verbose) {
41959003Shm				if (ent->flags & CE_COMPACT)
42059003Shm					printf("%s <%dZ>: trimming\n",
42159003Shm					    ent->log, ent->numlogs);
42280638Sobrien				else if (ent->flags & CE_BZCOMPACT)
42380638Sobrien					printf("%s <%dJ>: trimming\n",
42480638Sobrien					    ent->log, ent->numlogs);
42559003Shm				else
42659003Shm					printf("%s <%d>: trimming\n",
42759003Shm					    ent->log, ent->numlogs);
42859003Shm			}
429119927Sgad			dotrim(ent);
43059003Shm		} else {
43159003Shm			if (verbose)
43259003Shm				printf("--> skipping\n");
43359003Shm		}
43459003Shm	}
435111772Sgad#undef REASON_MAX
43613244Sgraichen}
43713244Sgraichen
438112003Sgad/* Send a signal to the pid specified by pidfile */
439112003Sgadstatic int
440112003Sgadsend_signal(const struct conf_entry *ent)
441112003Sgad{
442112003Sgad	pid_t target_pid;
443112003Sgad	int did_notify;
444112003Sgad	FILE *f;
445112003Sgad	long minok, maxok, rval;
446112003Sgad	const char *target_name;
447112003Sgad	char *endp, *linep, line[BUFSIZ];
448112003Sgad
449112003Sgad	did_notify = 0;
450112003Sgad	f = fopen(ent->pid_file, "r");
451112003Sgad	if (f == NULL) {
452112003Sgad		warn("can't open pid file: %s", ent->pid_file);
453112003Sgad		return (did_notify);
454112003Sgad		/* NOTREACHED */
455112003Sgad	}
456112003Sgad
457112003Sgad	if (fgets(line, BUFSIZ, f) == NULL) {
458112003Sgad		/*
459112003Sgad		 * XXX - If the pid file is empty, is that really a
460112003Sgad		 *	problem?  Wouldn't that mean that the process
461112003Sgad		 *	has shut down?  In that case there would be no
462112003Sgad		 *	problem with compressing the rotated log file.
463112003Sgad		 */
464112003Sgad		if (feof(f))
465112003Sgad			warnx("pid file is empty: %s",  ent->pid_file);
466112003Sgad		else
467112003Sgad			warn("can't read from pid file: %s", ent->pid_file);
468112003Sgad		(void) fclose(f);
469112003Sgad		return (did_notify);
470112003Sgad		/* NOTREACHED */
471112003Sgad	}
472112003Sgad	(void) fclose(f);
473112003Sgad
474112003Sgad	target_name = "daemon";
475112003Sgad	minok = MIN_PID;
476112003Sgad	maxok = MAX_PID;
477112003Sgad	if (ent->flags & CE_SIGNALGROUP) {
478112003Sgad		/*
479112003Sgad		 * If we are expected to signal a process-group when
480112003Sgad		 * rotating this logfile, then the value read in should
481112003Sgad		 * be the negative of a valid process ID.
482112003Sgad		 */
483112003Sgad		target_name = "process-group";
484112003Sgad		minok = -MAX_PID;
485112003Sgad		maxok = -MIN_PID;
486112003Sgad	}
487112003Sgad
488112003Sgad	errno = 0;
489112003Sgad	linep = line;
490112003Sgad	while (*linep == ' ')
491112003Sgad		linep++;
492112003Sgad	rval = strtol(linep, &endp, 10);
493112003Sgad	if (*endp != '\0' && !isspacech(*endp)) {
494112003Sgad		warnx("pid file does not start with a valid number: %s",
495112003Sgad		    ent->pid_file);
496112003Sgad		rval = 0;
497112003Sgad	} else if (rval < minok || rval > maxok) {
498112003Sgad		warnx("bad value '%ld' for process number in %s",
499112003Sgad		    rval, ent->pid_file);
500112003Sgad		if (verbose)
501112003Sgad			warnx("\t(expecting value between %ld and %ld)",
502112003Sgad			    minok, maxok);
503112003Sgad		rval = 0;
504112003Sgad	}
505112003Sgad	if (rval == 0) {
506112003Sgad		return (did_notify);
507112003Sgad		/* NOTREACHED */
508112003Sgad	}
509112003Sgad
510112003Sgad	target_pid = rval;
511112003Sgad
512112003Sgad	if (noaction) {
513112003Sgad		did_notify = 1;
514112003Sgad		printf("\tkill -%d %d\n", ent->sig, (int) target_pid);
515112003Sgad	} else if (kill(target_pid, ent->sig)) {
516112003Sgad		/*
517112003Sgad		 * XXX - Iff the error was "no such process", should that
518112003Sgad		 *	really be an error for us?  Perhaps the process
519112003Sgad		 *	is already gone, in which case there would be no
520112003Sgad		 *	problem with compressing the rotated log file.
521112003Sgad		 */
522112003Sgad		warn("can't notify %s, pid %d", target_name,
523112003Sgad		    (int) target_pid);
524112003Sgad	} else {
525112003Sgad		did_notify = 1;
526112003Sgad		if (verbose)
527112003Sgad			printf("%s pid %d notified\n", target_name,
528112003Sgad			    (int) target_pid);
529112003Sgad	}
530112003Sgad
531112003Sgad	return (did_notify);
532112003Sgad}
533112003Sgad
53459004Shmstatic void
535111781Sgadparse_args(int argc, char **argv)
53613244Sgraichen{
537111781Sgad	int ch;
53859003Shm	char *p;
53913244Sgraichen
540120361Sgad	timenow = ptime_init(NULL);
541120361Sgad	ptimeset_time(timenow, time(NULL));
542120361Sgad	(void)strncpy(daytime, ptimeget_ctime(timenow) + 4, 15);
54359003Shm	daytime[15] = '\0';
54413244Sgraichen
54559003Shm	/* Let's get our hostname */
546111781Sgad	(void)gethostname(hostname, sizeof(hostname));
54713244Sgraichen
54813244Sgraichen	/* Truncate domain */
549111781Sgad	if ((p = strchr(hostname, '.')) != NULL)
55013244Sgraichen		*p = '\0';
551111768Sgad
552111768Sgad	/* Parse command line options. */
553119904Sgad	while ((ch = getopt(argc, argv, "a:f:nrsvCD:FR:")) != -1)
554111781Sgad		switch (ch) {
55559004Shm		case 'a':
55659004Shm			archtodir++;
55759004Shm			archdirname = optarg;
55859004Shm			break;
559111768Sgad		case 'f':
560111768Sgad			conf = optarg;
561111768Sgad			break;
562111768Sgad		case 'n':
563111768Sgad			noaction++;
564111768Sgad			break;
56559003Shm		case 'r':
56659003Shm			needroot = 0;
56759003Shm			break;
568111768Sgad		case 's':
569111768Sgad			nosignal = 1;
570111768Sgad			break;
57159003Shm		case 'v':
57259003Shm			verbose++;
57359003Shm			break;
574114137Sgad		case 'C':
575114137Sgad			/* Useful for things like rc.diskless... */
576114137Sgad			createlogs++;
577114137Sgad			break;
578119904Sgad		case 'D':
579119904Sgad			/*
580119904Sgad			 * Set some debugging option.  The specific option
581119904Sgad			 * depends on the value of optarg.  These options
582119904Sgad			 * may come and go without notice or documentation.
583119904Sgad			 */
584119904Sgad			if (parse_doption(optarg))
585119904Sgad				break;
586119904Sgad			usage();
587119904Sgad			/* NOTREACHED */
58834584Spst		case 'F':
58934584Spst			force++;
59034584Spst			break;
591111772Sgad		case 'R':
592111772Sgad			rotatereq++;
593111772Sgad			requestor = strdup(optarg);
594111772Sgad			break;
595111781Sgad		case 'm':	/* Used by OpenBSD for "monitor mode" */
59659003Shm		default:
59759003Shm			usage();
598111768Sgad			/* NOTREACHED */
59959003Shm		}
600111772Sgad
601111772Sgad	if (rotatereq) {
602111772Sgad		if (optind == argc) {
603111772Sgad			warnx("At least one filename must be given when -R is specified.");
604111772Sgad			usage();
605111772Sgad			/* NOTREACHED */
606111772Sgad		}
607111772Sgad		/* Make sure "requestor" value is safe for a syslog message. */
608111772Sgad		for (p = requestor; *p != '\0'; p++) {
609111772Sgad			if (!isprintch(*p) && (*p != '\t'))
610111772Sgad				*p = '.';
611111772Sgad		}
612111772Sgad	}
613119904Sgad
614119904Sgad	if (dbg_timenow) {
615119904Sgad		/*
616119904Sgad		 * Note that the 'daytime' variable is not changed.
617119904Sgad		 * That is only used in messages that track when a
618119904Sgad		 * logfile is rotated, and if a file *is* rotated,
619119904Sgad		 * then it will still rotated at the "real now" time.
620119904Sgad		 */
621120361Sgad		ptime_free(timenow);
622119904Sgad		timenow = dbg_timenow;
623119904Sgad		fprintf(stderr, "Debug: Running as if TimeNow is %s",
624120361Sgad		    ptimeget_ctime(dbg_timenow));
625119904Sgad	}
626119904Sgad
62743071Swollman}
62813244Sgraichen
629120361Sgad/*
630120361Sgad * These debugging options are mainly meant for developer use, such
631120361Sgad * as writing regression-tests.  They would not be needed by users
632120361Sgad * during normal operation of newsyslog...
633120361Sgad */
634119904Sgadstatic int
635119904Sgadparse_doption(const char *doption)
636119904Sgad{
637119904Sgad	const char TN[] = "TN=";
638120361Sgad	int res;
639119904Sgad
640119904Sgad	if (strncmp(doption, TN, sizeof(TN) - 1) == 0) {
641119904Sgad		/*
642120361Sgad		 * The "TimeNow" debugging option.  This might be off
643120361Sgad		 * by an hour when crossing a timezone change.
644119904Sgad		 */
645120361Sgad		dbg_timenow = ptime_init(NULL);
646120361Sgad		res = ptime_relparse(dbg_timenow, PTM_PARSE_ISO8601,
647120361Sgad		    time(NULL), doption + sizeof(TN) - 1);
648120361Sgad		if (res == -2) {
649120361Sgad			warnx("Non-existent time specified on -D %s", doption);
650120361Sgad			return (0);			/* failure */
651120361Sgad		} else if (res < 0) {
652119904Sgad			warnx("Malformed time given on -D %s", doption);
653119904Sgad			return (0);			/* failure */
654119904Sgad		}
655119904Sgad		return (1);			/* successfully parsed */
656119904Sgad
657119904Sgad	}
658119904Sgad
659120361Sgad	if (strcmp(doption, "ats") == 0) {
660120361Sgad		dbg_at_times++;
661120361Sgad		return (1);			/* successfully parsed */
662120361Sgad	}
663120361Sgad
664119904Sgad	warnx("Unknown -D (debug) option: %s", doption);
665119904Sgad	return (0);				/* failure */
666119904Sgad}
667119904Sgad
66859004Shmstatic void
66959004Shmusage(void)
67013244Sgraichen{
67180646Sobrien
67280646Sobrien	fprintf(stderr,
673114137Sgad	    "usage: newsyslog [-CFnrsv] [-a directory] [-f config-file]\n"
674111772Sgad	    "                 [ [-R requestor] filename ... ]\n");
67559003Shm	exit(1);
67613244Sgraichen}
67713244Sgraichen
67859004Shm/*
679111773Sgad * Parse a configuration file and return a linked list of all the logs
680111773Sgad * which should be processed.
68113244Sgraichen */
68259003Shmstatic struct conf_entry *
683111773Sgadget_worklist(char **files)
68413244Sgraichen{
68559003Shm	FILE *f;
686111773Sgad	const char *fname;
687111773Sgad	char **given;
688111773Sgad	struct conf_entry *defconf, *dupent, *ent, *firstnew;
689112020Sgad	struct conf_entry *globlist, *lastnew, *worklist;
690112020Sgad	int gmatch, fnres;
691111773Sgad
692112020Sgad	defconf = globlist = worklist = NULL;
693111773Sgad
694111773Sgad	fname = conf;
695111773Sgad	if (fname == NULL)
696111773Sgad		fname = _PATH_CONF;
697111773Sgad
698111773Sgad	if (strcmp(fname, "-") != 0)
699111773Sgad		f = fopen(fname, "r");
700111773Sgad	else {
701111773Sgad		f = stdin;
702111773Sgad		fname = "<stdin>";
703111773Sgad	}
704111773Sgad	if (!f)
705111773Sgad		err(1, "%s", conf);
706111773Sgad
707112020Sgad	parse_file(f, fname, &worklist, &globlist, &defconf);
708111773Sgad	(void) fclose(f);
709111773Sgad
710111773Sgad	/*
711111773Sgad	 * All config-file information has been read in and turned into
712112020Sgad	 * a worklist and a globlist.  If there were no specific files
713112020Sgad	 * given on the run command, then the only thing left to do is to
714112020Sgad	 * call a routine which finds all files matched by the globlist
715112020Sgad	 * and adds them to the worklist.  Then return the worklist.
716111773Sgad	 */
717111773Sgad	if (*files == NULL) {
718112020Sgad		expand_globs(&worklist, &globlist);
719112020Sgad		free_clist(&globlist);
720111773Sgad		if (defconf != NULL)
721111773Sgad			free_entry(defconf);
722111773Sgad		return (worklist);
723111773Sgad		/* NOTREACHED */
724111773Sgad	}
725111773Sgad
726111773Sgad	/*
727111773Sgad	 * If newsyslog was given a specific list of files to process,
728111773Sgad	 * it may be that some of those files were not listed in any
729111773Sgad	 * config file.  Those unlisted files should get the default
730111773Sgad	 * rotation action.  First, create the default-rotation action
731111773Sgad	 * if none was found in a system config file.
732111773Sgad	 */
733111773Sgad	if (defconf == NULL) {
734111773Sgad		defconf = init_entry(DEFAULT_MARKER, NULL);
735111773Sgad		defconf->numlogs = 3;
736111773Sgad		defconf->size = 50;
737111773Sgad		defconf->permissions = S_IRUSR|S_IWUSR;
738111773Sgad	}
739111773Sgad
740111773Sgad	/*
741111773Sgad	 * If newsyslog was run with a list of specific filenames,
742111773Sgad	 * then create a new worklist which has only those files in
743111773Sgad	 * it, picking up the rotation-rules for those files from
744111773Sgad	 * the original worklist.
745111773Sgad	 *
746111773Sgad	 * XXX - Note that this will copy multiple rules for a single
747111773Sgad	 *	logfile, if multiple entries are an exact match for
748111773Sgad	 *	that file.  That matches the historic behavior, but do
749111773Sgad	 *	we want to continue to allow it?  If so, it should
750111773Sgad	 *	probably be handled more intelligently.
751111773Sgad	 */
752112020Sgad	firstnew = lastnew = NULL;
753111773Sgad	for (given = files; *given; ++given) {
754111773Sgad		/*
755111773Sgad		 * First try to find exact-matches for this given file.
756111773Sgad		 */
757112020Sgad		gmatch = 0;
758111773Sgad		for (ent = worklist; ent; ent = ent->next) {
759111773Sgad			if (strcmp(ent->log, *given) == 0) {
760111773Sgad				gmatch++;
761111773Sgad				dupent = init_entry(*given, ent);
762111773Sgad				if (!firstnew)
763111773Sgad					firstnew = dupent;
764111773Sgad				else
765112020Sgad					lastnew->next = dupent;
766112020Sgad				lastnew = dupent;
767111773Sgad			}
768111773Sgad		}
769111773Sgad		if (gmatch) {
770111773Sgad			if (verbose > 2)
771111773Sgad				printf("\t+ Matched entry %s\n", *given);
772111773Sgad			continue;
773111773Sgad		}
774111773Sgad
775111773Sgad		/*
776111773Sgad		 * There was no exact-match for this given file, so look
777111773Sgad		 * for a "glob" entry which does match.
778111773Sgad		 */
779112020Sgad		gmatch = 0;
780112020Sgad		if (verbose > 2 && globlist != NULL)
781112020Sgad			printf("\t+ Checking globs for %s\n", *given);
782112020Sgad		for (ent = globlist; ent; ent = ent->next) {
783112020Sgad			fnres = fnmatch(ent->log, *given, FNM_PATHNAME);
784112020Sgad			if (verbose > 2)
785112020Sgad				printf("\t+    = %d for pattern %s\n", fnres,
786112020Sgad				    ent->log);
787112020Sgad			if (fnres == 0) {
788111773Sgad				gmatch++;
789111773Sgad				dupent = init_entry(*given, ent);
790111773Sgad				if (!firstnew)
791111773Sgad					firstnew = dupent;
792111773Sgad				else
793112020Sgad					lastnew->next = dupent;
794112020Sgad				lastnew = dupent;
795112020Sgad				/* This new entry is not a glob! */
796111773Sgad				dupent->flags &= ~CE_GLOB;
797111773Sgad				/* Only allow a match to one glob-entry */
798111773Sgad				break;
799111773Sgad			}
800111773Sgad		}
801111773Sgad		if (gmatch) {
802111773Sgad			if (verbose > 2)
803111773Sgad				printf("\t+ Matched %s via %s\n", *given,
804111773Sgad				    ent->log);
805111773Sgad			continue;
806111773Sgad		}
807111773Sgad
808111773Sgad		/*
809111773Sgad		 * This given file was not found in any config file, so
810111773Sgad		 * add a worklist item based on the default entry.
811111773Sgad		 */
812111773Sgad		if (verbose > 2)
813111773Sgad			printf("\t+ No entry matched %s  (will use %s)\n",
814111773Sgad			    *given, DEFAULT_MARKER);
815111773Sgad		dupent = init_entry(*given, defconf);
816111773Sgad		if (!firstnew)
817111773Sgad			firstnew = dupent;
818111773Sgad		else
819112020Sgad			lastnew->next = dupent;
820111773Sgad		/* Mark that it was *not* found in a config file */
821111773Sgad		dupent->def_cfg = 1;
822112020Sgad		lastnew = dupent;
823111773Sgad	}
824111773Sgad
825111773Sgad	/*
826112020Sgad	 * Free all the entries in the original work list, the list of
827112020Sgad	 * glob entries, and the default entry.
828111773Sgad	 */
829112020Sgad	free_clist(&worklist);
830112020Sgad	free_clist(&globlist);
831112020Sgad	free_entry(defconf);
832111773Sgad
833112020Sgad	/* And finally, return a worklist which matches the given files. */
834112013Sgad	return (firstnew);
835111773Sgad}
836111773Sgad
837111773Sgad/*
838112020Sgad * Expand the list of entries with filename patterns, and add all files
839112020Sgad * which match those glob-entries onto the worklist.
840112020Sgad */
841112020Sgadstatic void
842112020Sgadexpand_globs(struct conf_entry **work_p, struct conf_entry **glob_p)
843112020Sgad{
844112020Sgad	int gmatch, gres, i;
845112020Sgad	char *mfname;
846112020Sgad	struct conf_entry *dupent, *ent, *firstmatch, *globent;
847112020Sgad	struct conf_entry *lastmatch;
848112020Sgad	glob_t pglob;
849112020Sgad	struct stat st_fm;
850112020Sgad
851112020Sgad	if ((glob_p == NULL) || (*glob_p == NULL))
852112020Sgad		return;			/* There is nothing to do. */
853112020Sgad
854112020Sgad	/*
855112020Sgad	 * The worklist contains all fully-specified (non-GLOB) names.
856112020Sgad	 *
857112020Sgad	 * Now expand the list of filename-pattern (GLOB) entries into
858112020Sgad	 * a second list, which (by definition) will only match files
859112020Sgad	 * that already exist.  Do not add a glob-related entry for any
860112020Sgad	 * file which already exists in the fully-specified list.
861112020Sgad	 */
862112020Sgad	firstmatch = lastmatch = NULL;
863112020Sgad	for (globent = *glob_p; globent; globent = globent->next) {
864112020Sgad
865112020Sgad		gres = glob(globent->log, GLOB_NOCHECK, NULL, &pglob);
866112020Sgad		if (gres != 0) {
867112020Sgad			warn("cannot expand pattern (%d): %s", gres,
868112020Sgad			    globent->log);
869112020Sgad			continue;
870112020Sgad		}
871112020Sgad
872112020Sgad		if (verbose > 2)
873112020Sgad			printf("\t+ Expanding pattern %s\n", globent->log);
874112020Sgad		for (i = 0; i < pglob.gl_matchc; i++) {
875112020Sgad			mfname = pglob.gl_pathv[i];
876112020Sgad
877112020Sgad			/* See if this file already has a specific entry. */
878112020Sgad			gmatch = 0;
879112020Sgad			for (ent = *work_p; ent; ent = ent->next) {
880112020Sgad				if (strcmp(mfname, ent->log) == 0) {
881112020Sgad					gmatch++;
882112020Sgad					break;
883112020Sgad				}
884112020Sgad			}
885112020Sgad			if (gmatch)
886112020Sgad				continue;
887112020Sgad
888112020Sgad			/* Make sure the named matched is a file. */
889112020Sgad			gres = lstat(mfname, &st_fm);
890112020Sgad			if (gres != 0) {
891112020Sgad				/* Error on a file that glob() matched?!? */
892112020Sgad				warn("Skipping %s - lstat() error", mfname);
893112020Sgad				continue;
894112020Sgad			}
895112020Sgad			if (!S_ISREG(st_fm.st_mode)) {
896112020Sgad				/* We only rotate files! */
897112020Sgad				if (verbose > 2)
898112020Sgad					printf("\t+  . skipping %s (!file)\n",
899112020Sgad					    mfname);
900112020Sgad				continue;
901112020Sgad			}
902112020Sgad
903112020Sgad			if (verbose > 2)
904112020Sgad				printf("\t+  . add file %s\n", mfname);
905112020Sgad			dupent = init_entry(mfname, globent);
906112020Sgad			if (!firstmatch)
907112020Sgad				firstmatch = dupent;
908112020Sgad			else
909112020Sgad				lastmatch->next = dupent;
910112020Sgad			lastmatch = dupent;
911112020Sgad			/* This new entry is not a glob! */
912112020Sgad			dupent->flags &= ~CE_GLOB;
913112020Sgad		}
914112020Sgad		globfree(&pglob);
915112020Sgad		if (verbose > 2)
916112020Sgad			printf("\t+ Done with pattern %s\n", globent->log);
917112020Sgad	}
918112020Sgad
919112020Sgad	/* Add the list of matched files to the end of the worklist. */
920112020Sgad	if (!*work_p)
921112020Sgad		*work_p = firstmatch;
922112020Sgad	else {
923112020Sgad		ent = *work_p;
924112020Sgad		while (ent->next)
925112020Sgad			ent = ent->next;
926112020Sgad		ent->next = firstmatch;
927112020Sgad	}
928112020Sgad
929112020Sgad}
930112020Sgad
931112020Sgad/*
932111773Sgad * Parse a configuration file and update a linked list of all the logs to
933111773Sgad * process.
934111773Sgad */
935111773Sgadstatic void
936111773Sgadparse_file(FILE *cf, const char *cfname, struct conf_entry **work_p,
937112020Sgad    struct conf_entry **glob_p, struct conf_entry **defconf_p)
938111773Sgad{
93959003Shm	char line[BUFSIZ], *parse, *q;
940107737Ssobomax	char *cp, *errline, *group;
941112020Sgad	struct conf_entry *lastglob, *lastwork, *working;
942111781Sgad	struct passwd *pwd;
94359003Shm	struct group *grp;
944120361Sgad	int eol, ptm_opts, res, special;
94513244Sgraichen
946111773Sgad	/*
947111773Sgad	 * XXX - for now, assume that only one config file will be read,
948111773Sgad	 *	ie, this routine is only called one time.
949111773Sgad	 */
950112020Sgad	lastglob = lastwork = NULL;
95180646Sobrien
952111773Sgad	while (fgets(line, BUFSIZ, cf)) {
953107737Ssobomax		if ((line[0] == '\n') || (line[0] == '#') ||
954107737Ssobomax		    (strlen(line) == 0))
95559003Shm			continue;
95659003Shm		errline = strdup(line);
957107737Ssobomax		for (cp = line + 1; *cp != '\0'; cp++) {
958107737Ssobomax			if (*cp != '#')
959107737Ssobomax				continue;
960107737Ssobomax			if (*(cp - 1) == '\\') {
961107737Ssobomax				strcpy(cp - 1, cp);
962107737Ssobomax				cp--;
963107737Ssobomax				continue;
964107737Ssobomax			}
965107737Ssobomax			*cp = '\0';
966107737Ssobomax			break;
967107737Ssobomax		}
96860373Sdes
96960373Sdes		q = parse = missing_field(sob(line), errline);
97060373Sdes		parse = son(line);
97160373Sdes		if (!*parse)
97280646Sobrien			errx(1, "malformed line (missing fields):\n%s",
97380646Sobrien			    errline);
97460373Sdes		*parse = '\0';
97560373Sdes
976112020Sgad		special = 0;
977111388Sgad		working = init_entry(q, NULL);
978111388Sgad		if (strcasecmp(DEFAULT_MARKER, q) == 0) {
979112020Sgad			special = 1;
980111773Sgad			if (defconf_p == NULL) {
981111773Sgad				warnx("Ignoring entry for %s in %s!", q,
982111773Sgad				    cfname);
983111773Sgad				free_entry(working);
984111773Sgad				continue;
985111773Sgad			} else if (*defconf_p != NULL) {
986111388Sgad				warnx("Ignoring duplicate entry for %s!", q);
987111388Sgad				free_entry(working);
988111388Sgad				continue;
989111388Sgad			}
990111773Sgad			*defconf_p = working;
99159003Shm		}
99213244Sgraichen
99359003Shm		q = parse = missing_field(sob(++parse), errline);
99459003Shm		parse = son(parse);
99525518Sbrian		if (!*parse)
99680646Sobrien			errx(1, "malformed line (missing fields):\n%s",
99780646Sobrien			    errline);
99859003Shm		*parse = '\0';
99959003Shm		if ((group = strchr(q, ':')) != NULL ||
100059003Shm		    (group = strrchr(q, '.')) != NULL) {
100159003Shm			*group++ = '\0';
100259003Shm			if (*q) {
1003119102Sgad				if (!(isnumberstr(q))) {
1004111781Sgad					if ((pwd = getpwnam(q)) == NULL)
100559003Shm						errx(1,
100680646Sobrien				     "error in config file; unknown user:\n%s",
100759003Shm						    errline);
1008111781Sgad					working->uid = pwd->pw_uid;
100959003Shm				} else
101059003Shm					working->uid = atoi(q);
101159003Shm			} else
1012111779Sgad				working->uid = (uid_t)-1;
101313244Sgraichen
101459003Shm			q = group;
101559003Shm			if (*q) {
1016119102Sgad				if (!(isnumberstr(q))) {
101759003Shm					if ((grp = getgrnam(q)) == NULL)
101859003Shm						errx(1,
101980646Sobrien				    "error in config file; unknown group:\n%s",
102059003Shm						    errline);
102159003Shm					working->gid = grp->gr_gid;
102259003Shm				} else
102359003Shm					working->gid = atoi(q);
102459003Shm			} else
1025111779Sgad				working->gid = (gid_t)-1;
102613244Sgraichen
102759003Shm			q = parse = missing_field(sob(++parse), errline);
102859003Shm			parse = son(parse);
102959003Shm			if (!*parse)
103080646Sobrien				errx(1, "malformed line (missing fields):\n%s",
103180646Sobrien				    errline);
103259003Shm			*parse = '\0';
1033111779Sgad		} else {
1034111779Sgad			working->uid = (uid_t)-1;
1035111779Sgad			working->gid = (gid_t)-1;
1036111779Sgad		}
103759003Shm
103859003Shm		if (!sscanf(q, "%o", &working->permissions))
103959003Shm			errx(1, "error in config file; bad permissions:\n%s",
104059003Shm			    errline);
104159003Shm
104259003Shm		q = parse = missing_field(sob(++parse), errline);
104359003Shm		parse = son(parse);
104425518Sbrian		if (!*parse)
104580646Sobrien			errx(1, "malformed line (missing fields):\n%s",
104680646Sobrien			    errline);
104759003Shm		*parse = '\0';
1048111400Sgad		if (!sscanf(q, "%d", &working->numlogs) || working->numlogs < 0)
1049111400Sgad			errx(1, "error in config file; bad value for count of logs to save:\n%s",
105059003Shm			    errline);
105113244Sgraichen
105259003Shm		q = parse = missing_field(sob(++parse), errline);
105359003Shm		parse = son(parse);
105425518Sbrian		if (!*parse)
105580646Sobrien			errx(1, "malformed line (missing fields):\n%s",
105680646Sobrien			    errline);
105759003Shm		*parse = '\0';
1058114762Sgad		if (isdigitch(*q))
105959003Shm			working->size = atoi(q);
1060114762Sgad		else if (strcmp(q,"*") == 0)
106159003Shm			working->size = -1;
1062114762Sgad		else {
1063114762Sgad			warnx("Invalid value of '%s' for 'size' in line:\n%s",
1064114762Sgad			    q, errline);
1065114762Sgad			working->size = -1;
1066114762Sgad		}
106759003Shm
106859003Shm		working->flags = 0;
106959003Shm		q = parse = missing_field(sob(++parse), errline);
107059003Shm		parse = son(parse);
107125518Sbrian		eol = !*parse;
107259003Shm		*parse = '\0';
107343071Swollman		{
107459003Shm			char *ep;
107559003Shm			u_long ul;
107613244Sgraichen
107743071Swollman			ul = strtoul(q, &ep, 10);
107843071Swollman			if (ep == q)
107943071Swollman				working->hours = 0;
108043071Swollman			else if (*ep == '*')
108143071Swollman				working->hours = -1;
108243071Swollman			else if (ul > INT_MAX)
108343071Swollman				errx(1, "interval is too large:\n%s", errline);
108443071Swollman			else
108543071Swollman				working->hours = ul;
108643071Swollman
1087120361Sgad			if (*ep == '\0' || strcmp(ep, "*") == 0)
1088120361Sgad				goto no_trimat;
1089120361Sgad			if (*ep != '@' && *ep != '$')
109043071Swollman				errx(1, "malformed interval/at:\n%s", errline);
1091120361Sgad
1092120361Sgad			working->flags |= CE_TRIMAT;
1093120361Sgad			working->trim_at = ptime_init(NULL);
1094120361Sgad			ptm_opts = PTM_PARSE_ISO8601;
1095120361Sgad			if (*ep == '$')
1096120361Sgad				ptm_opts = PTM_PARSE_DWM;
1097120361Sgad			ptm_opts |= PTM_PARSE_MATCHDOM;
1098120361Sgad			res = ptime_relparse(working->trim_at, ptm_opts,
1099120361Sgad			    ptimeget_secs(timenow), ep + 1);
1100120361Sgad			if (res == -2)
1101120361Sgad				errx(1, "nonexistent time for 'at' value:\n%s",
1102120361Sgad				    errline);
1103120361Sgad			else if (res < 0)
1104120361Sgad				errx(1, "malformed 'at' value:\n%s", errline);
110543071Swollman		}
1106120361Sgadno_trimat:
110743071Swollman
110825518Sbrian		if (eol)
110959003Shm			q = NULL;
111025518Sbrian		else {
111159003Shm			q = parse = sob(++parse);	/* Optional field */
111259003Shm			parse = son(parse);
111359003Shm			if (!*parse)
111459003Shm				eol = 1;
111559003Shm			*parse = '\0';
111625518Sbrian		}
111725443Sache
1118111768Sgad		for (; q && *q && !isspacech(*q); q++) {
1119111768Sgad			switch (tolowerch(*q)) {
1120111768Sgad			case 'b':
112159003Shm				working->flags |= CE_BINARY;
1122111768Sgad				break;
1123114137Sgad			case 'c':
1124111768Sgad				/*
1125114137Sgad				 * XXX - 	Ick! Ugly! Remove ASAP!
1126114137Sgad				 * We want `c' and `C' for "create".  But we
1127114137Sgad				 * will temporarily treat `c' as `g', because
1128114137Sgad				 * FreeBSD releases <= 4.8 have a typo of
1129114137Sgad				 * checking  ('G' || 'c')  for CE_GLOB.
1130111768Sgad				 */
1131114137Sgad				if (*q == 'c') {
1132114137Sgad					warnx("Assuming 'g' for 'c' in flags for line:\n%s",
1133114137Sgad					    errline);
1134114137Sgad					warnx("The 'c' flag will eventually mean 'CREATE'");
1135114137Sgad					working->flags |= CE_GLOB;
1136114137Sgad					break;
1137114137Sgad				}
1138114137Sgad				working->flags |= CE_CREATE;
1139114137Sgad				break;
1140111768Sgad			case 'g':
1141106905Ssobomax				working->flags |= CE_GLOB;
1142111768Sgad				break;
1143111768Sgad			case 'j':
1144111768Sgad				working->flags |= CE_BZCOMPACT;
1145111768Sgad				break;
1146111768Sgad			case 'n':
1147111768Sgad				working->flags |= CE_NOSIGNAL;
1148111768Sgad				break;
1149112003Sgad			case 'u':
1150112003Sgad				working->flags |= CE_SIGNALGROUP;
1151112003Sgad				break;
1152111768Sgad			case 'w':
1153107916Ssobomax				working->flags |= CE_COMPACTWAIT;
1154111768Sgad				break;
1155111768Sgad			case 'z':
1156111768Sgad				working->flags |= CE_COMPACT;
1157111768Sgad				break;
1158111768Sgad			case '-':
1159111768Sgad				break;
1160111781Sgad			case 'f':	/* Used by OpenBSD for "CE_FOLLOW" */
1161111781Sgad			case 'm':	/* Used by OpenBSD for "CE_MONITOR" */
1162111781Sgad			case 'p':	/* Used by NetBSD  for "CE_PLAIN0" */
1163111768Sgad			default:
116480646Sobrien				errx(1, "illegal flag in config file -- %c",
116580646Sobrien				    *q);
1166111768Sgad			}
116759003Shm		}
116859003Shm
116925518Sbrian		if (eol)
117059003Shm			q = NULL;
117125518Sbrian		else {
117259003Shm			q = parse = sob(++parse);	/* Optional field */
117359003Shm			parse = son(parse);
117459003Shm			if (!*parse)
117559003Shm				eol = 1;
117659003Shm			*parse = '\0';
117725518Sbrian		}
117825443Sache
117925443Sache		working->pid_file = NULL;
118025443Sache		if (q && *q) {
118125443Sache			if (*q == '/')
118225443Sache				working->pid_file = strdup(q);
118336817Sache			else if (isdigit(*q))
118436817Sache				goto got_sig;
118559003Shm			else
118680646Sobrien				errx(1,
118780646Sobrien			"illegal pid file or signal number in config file:\n%s",
118880646Sobrien				    errline);
118925443Sache		}
119036817Sache		if (eol)
119159003Shm			q = NULL;
119236817Sache		else {
119359003Shm			q = parse = sob(++parse);	/* Optional field */
119459003Shm			*(parse = son(parse)) = '\0';
119536817Sache		}
119636817Sache
119736817Sache		working->sig = SIGHUP;
119836817Sache		if (q && *q) {
119936817Sache			if (isdigit(*q)) {
120059003Shm		got_sig:
120136817Sache				working->sig = atoi(q);
120236817Sache			} else {
120359003Shm		err_sig:
120480646Sobrien				errx(1,
120580646Sobrien				    "illegal signal number in config file:\n%s",
120680646Sobrien				    errline);
120736817Sache			}
120836817Sache			if (working->sig < 1 || working->sig >= NSIG)
120936817Sache				goto err_sig;
121036817Sache		}
1211111768Sgad
1212111768Sgad		/*
1213111768Sgad		 * Finish figuring out what pid-file to use (if any) in
1214111768Sgad		 * later processing if this logfile needs to be rotated.
1215111768Sgad		 */
1216111768Sgad		if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) {
1217111768Sgad			/*
1218111768Sgad			 * This config-entry specified 'n' for nosignal,
1219111768Sgad			 * see if it also specified an explicit pid_file.
1220111768Sgad			 * This would be a pretty pointless combination.
1221111768Sgad			 */
1222111768Sgad			if (working->pid_file != NULL) {
1223111768Sgad				warnx("Ignoring '%s' because flag 'n' was specified in line:\n%s",
1224111768Sgad				    working->pid_file, errline);
1225111768Sgad				free(working->pid_file);
1226111768Sgad				working->pid_file = NULL;
1227111768Sgad			}
1228111768Sgad		} else if (working->pid_file == NULL) {
1229111768Sgad			/*
1230111768Sgad			 * This entry did not specify the 'n' flag, which
1231111768Sgad			 * means it should signal syslogd unless it had
1232112003Sgad			 * specified some other pid-file (and obviously the
1233112003Sgad			 * syslog pid-file will not be for a process-group).
1234112003Sgad			 * Also, we should only try to notify syslog if we
1235112003Sgad			 * are root.
1236111768Sgad			 */
1237112003Sgad			if (working->flags & CE_SIGNALGROUP) {
1238112003Sgad				warnx("Ignoring flag 'U' in line:\n%s",
1239112003Sgad				    errline);
1240112003Sgad				working->flags &= ~CE_SIGNALGROUP;
1241112003Sgad			}
1242111768Sgad			if (needroot)
1243111768Sgad				working->pid_file = strdup(_PATH_SYSLOGPID);
1244111768Sgad		}
1245111768Sgad
1246112020Sgad		/*
1247112020Sgad		 * Add this entry to the appropriate list of entries, unless
1248112020Sgad		 * it was some kind of special entry (eg: <default>).
1249112020Sgad		 */
1250112020Sgad		if (special) {
1251112020Sgad			;			/* Do not add to any list */
1252112020Sgad		} else if (working->flags & CE_GLOB) {
1253112020Sgad			if (!*glob_p)
1254112020Sgad				*glob_p = working;
1255112020Sgad			else
1256112020Sgad				lastglob->next = working;
1257112020Sgad			lastglob = working;
1258112020Sgad		} else {
1259112020Sgad			if (!*work_p)
1260112020Sgad				*work_p = working;
1261112020Sgad			else
1262112020Sgad				lastwork->next = working;
1263112020Sgad			lastwork = working;
1264112020Sgad		}
1265112020Sgad
126659003Shm		free(errline);
1267111768Sgad		errline = NULL;
126859003Shm	}
126913244Sgraichen}
127013244Sgraichen
127159003Shmstatic char *
127259004Shmmissing_field(char *p, char *errline)
127313244Sgraichen{
127480646Sobrien
127559003Shm	if (!p || !*p)
127659003Shm		errx(1, "missing field in config file:\n%s", errline);
127759003Shm	return (p);
127813244Sgraichen}
127913244Sgraichen
128059004Shmstatic void
1281119927Sgaddotrim(const struct conf_entry *ent)
128213244Sgraichen{
128371299Sjedgar	char dirpart[MAXPATHLEN], namepart[MAXPATHLEN];
128471299Sjedgar	char file1[MAXPATHLEN], file2[MAXPATHLEN];
128571299Sjedgar	char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN];
128680638Sobrien	char jfile1[MAXPATHLEN];
128794352Ssheldonh	char tfile[MAXPATHLEN];
1288119927Sgad	int flags, notified, need_notification, fd, numlogs_c;
128959003Shm	struct stat st;
129013244Sgraichen
1291119927Sgad	flags = ent->flags;
1292119927Sgad
129359004Shm	if (archtodir) {
129459004Shm		char *p;
129513244Sgraichen
129659004Shm		/* build complete name of archive directory into dirpart */
129759004Shm		if (*archdirname == '/') {	/* absolute */
129871299Sjedgar			strlcpy(dirpart, archdirname, sizeof(dirpart));
129959004Shm		} else {	/* relative */
130059004Shm			/* get directory part of logfile */
1301119927Sgad			strlcpy(dirpart, ent->log, sizeof(dirpart));
130259004Shm			if ((p = rindex(dirpart, '/')) == NULL)
130359004Shm				dirpart[0] = '\0';
130459004Shm			else
130559004Shm				*(p + 1) = '\0';
130671299Sjedgar			strlcat(dirpart, archdirname, sizeof(dirpart));
130759004Shm		}
130859004Shm
130959004Shm		/* check if archive directory exists, if not, create it */
131059004Shm		if (lstat(dirpart, &st))
1311114137Sgad			createdir(ent, dirpart);
131259004Shm
131359004Shm		/* get filename part of logfile */
1314119927Sgad		if ((p = rindex(ent->log, '/')) == NULL)
1315119927Sgad			strlcpy(namepart, ent->log, sizeof(namepart));
131659004Shm		else
131771299Sjedgar			strlcpy(namepart, p + 1, sizeof(namepart));
131859004Shm
131959004Shm		/* name of oldest log */
132080646Sobrien		(void) snprintf(file1, sizeof(file1), "%s/%s.%d", dirpart,
1321119927Sgad		    namepart, ent->numlogs);
132271299Sjedgar		(void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
132371299Sjedgar		    COMPRESS_POSTFIX);
132480638Sobrien		snprintf(jfile1, sizeof(jfile1), "%s%s", file1,
132580638Sobrien		    BZCOMPRESS_POSTFIX);
132659004Shm	} else {
132759004Shm		/* name of oldest log */
1328119927Sgad		(void) snprintf(file1, sizeof(file1), "%s.%d", ent->log,
1329119927Sgad		    ent->numlogs);
133071299Sjedgar		(void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
133171299Sjedgar		    COMPRESS_POSTFIX);
133280638Sobrien		snprintf(jfile1, sizeof(jfile1), "%s%s", file1,
133380638Sobrien		    BZCOMPRESS_POSTFIX);
133459004Shm	}
133559004Shm
133659003Shm	if (noaction) {
1337111967Sgad		printf("\trm -f %s\n", file1);
1338111967Sgad		printf("\trm -f %s\n", zfile1);
1339111967Sgad		printf("\trm -f %s\n", jfile1);
134059003Shm	} else {
134159003Shm		(void) unlink(file1);
134259003Shm		(void) unlink(zfile1);
134380638Sobrien		(void) unlink(jfile1);
134459003Shm	}
134513244Sgraichen
134659003Shm	/* Move down log files */
1347119927Sgad	numlogs_c = ent->numlogs;		/* copy for countdown */
1348119927Sgad	while (numlogs_c--) {
134959004Shm
135071299Sjedgar		(void) strlcpy(file2, file1, sizeof(file2));
135159004Shm
135259004Shm		if (archtodir)
135380646Sobrien			(void) snprintf(file1, sizeof(file1), "%s/%s.%d",
1354119927Sgad			    dirpart, namepart, numlogs_c);
135559004Shm		else
1356119927Sgad			(void) snprintf(file1, sizeof(file1), "%s.%d",
1357119927Sgad			    ent->log, numlogs_c);
135859004Shm
135971299Sjedgar		(void) strlcpy(zfile1, file1, sizeof(zfile1));
136071299Sjedgar		(void) strlcpy(zfile2, file2, sizeof(zfile2));
136159003Shm		if (lstat(file1, &st)) {
136280646Sobrien			(void) strlcat(zfile1, COMPRESS_POSTFIX,
136380646Sobrien			    sizeof(zfile1));
136480646Sobrien			(void) strlcat(zfile2, COMPRESS_POSTFIX,
136580646Sobrien			    sizeof(zfile2));
136680638Sobrien			if (lstat(zfile1, &st)) {
136780638Sobrien				strlcpy(zfile1, file1, sizeof(zfile1));
136880638Sobrien				strlcpy(zfile2, file2, sizeof(zfile2));
136980638Sobrien				strlcat(zfile1, BZCOMPRESS_POSTFIX,
137080638Sobrien				    sizeof(zfile1));
137180638Sobrien				strlcat(zfile2, BZCOMPRESS_POSTFIX,
137280638Sobrien				    sizeof(zfile2));
137380638Sobrien				if (lstat(zfile1, &st))
137480638Sobrien					continue;
137580638Sobrien			}
137659003Shm		}
137759003Shm		if (noaction) {
1378111967Sgad			printf("\tmv %s %s\n", zfile1, zfile2);
1379111967Sgad			printf("\tchmod %o %s\n", ent->permissions, zfile2);
1380111779Sgad			if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
1381111967Sgad				printf("\tchown %u:%u %s\n",
1382111779Sgad				    ent->uid, ent->gid, zfile2);
138359003Shm		} else {
138459003Shm			(void) rename(zfile1, zfile2);
1385111780Sgad			if (chmod(zfile2, ent->permissions))
1386111780Sgad				warn("can't chmod %s", file2);
1387111779Sgad			if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
1388111779Sgad				if (chown(zfile2, ent->uid, ent->gid))
1389111779Sgad					warn("can't chown %s", zfile2);
139059003Shm		}
139159003Shm	}
1392111388Sgad	if (!noaction && !(flags & CE_BINARY)) {
1393111388Sgad		/* Report the trimming to the old log */
1394119927Sgad		(void) log_trim(ent->log, ent);
1395111388Sgad	}
139613244Sgraichen
1397119927Sgad	if (ent->numlogs == 0) {
139818075Sjkh		if (noaction)
1399119927Sgad			printf("\trm %s\n", ent->log);
140018075Sjkh		else
1401119927Sgad			(void) unlink(ent->log);
140259003Shm	} else {
1403129974Sgad		if (noaction) {
1404119927Sgad			printf("\tmv %s to %s\n", ent->log, file1);
1405129974Sgad			printf("\tchmod %o %s\n", ent->permissions, file1);
1406129974Sgad			if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
1407129974Sgad				printf("\tchown %u:%u %s\n", ent->uid,
1408129974Sgad				    ent->gid, file1);
1409129974Sgad 		} else {
141059004Shm			if (archtodir)
1411129974Sgad				movefile(ent->log, file1);
141259004Shm			else
1413119927Sgad				(void) rename(ent->log, file1);
1414129974Sgad			if (chmod(file1, ent->permissions))
1415129974Sgad				warn("can't chmod %s", file1);
1416129974Sgad			if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
1417129974Sgad				if (chown(file1, ent->uid, ent->gid))
1418129974Sgad					warn("can't chown %s", file1);
141959004Shm		}
142018075Sjkh	}
142118075Sjkh
1422111781Sgad	/* Now move the new log file into place */
1423119927Sgad	/* XXX - We should replace the above 'rename' with
1424119927Sgad	*	'link(ent->log, file1)' and then replace
1425119927Sgad	 *	the following with 'createfile(ent)' */
1426119927Sgad	strlcpy(tfile, ent->log, sizeof(tfile));
1427111967Sgad	strlcat(tfile, ".XXXXXX", sizeof(tfile));
1428111967Sgad	if (noaction) {
1429111781Sgad		printf("Start new log...\n");
1430111967Sgad		printf("\tmktemp %s\n", tfile);
1431111967Sgad	} else {
143294352Ssheldonh		mkstemp(tfile);
1433111780Sgad		fd = creat(tfile, ent->permissions);
143459003Shm		if (fd < 0)
143559003Shm			err(1, "can't start new log");
1436111779Sgad		if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
1437111779Sgad			if (fchown(fd, ent->uid, ent->gid))
1438111779Sgad			    err(1, "can't chown new log file");
143959003Shm		(void) close(fd);
1440111388Sgad		if (!(flags & CE_BINARY)) {
1441111388Sgad			/* Add status message to new log file */
1442111779Sgad			if (log_trim(tfile, ent))
144359003Shm				err(1, "can't add status message to log");
1444111388Sgad		}
144559003Shm	}
1446111967Sgad	if (noaction) {
1447111967Sgad		printf("\tchmod %o %s\n", ent->permissions, tfile);
1448119927Sgad		printf("\tmv %s %s\n", tfile, ent->log);
1449111967Sgad	} else {
1450111780Sgad		(void) chmod(tfile, ent->permissions);
1451119927Sgad		if (rename(tfile, ent->log) < 0) {
145294352Ssheldonh			err(1, "can't start new log");
145394352Ssheldonh			(void) unlink(tfile);
145494352Ssheldonh		}
145594352Ssheldonh	}
145625443Sache
1457111966Sgad	/*
1458111966Sgad	 * Find out if there is a process to signal.  If nosignal (-s) was
1459111966Sgad	 * specified, then do not signal any process.  Note that nosignal
1460111966Sgad	 * will trigger a warning message if the rotated logfile needs to
1461111966Sgad	 * be compressed, *unless* -R was specified.  This is because there
1462111966Sgad	 * presumably still are process(es) writing to the old logfile, but
1463111966Sgad	 * we assume that a -sR request comes from a process which writes
1464111966Sgad	 * to the logfile, and as such, that process has already made sure
1465111966Sgad	 * that the logfile is not presently in use.
1466111966Sgad	 */
146725443Sache	need_notification = notified = 0;
1468111779Sgad	if (ent->pid_file != NULL) {
146925443Sache		need_notification = 1;
1470111966Sgad		if (!nosignal)
1471112003Sgad			notified = send_signal(ent);	/* the normal case! */
1472111966Sgad		else if (rotatereq)
1473111966Sgad			need_notification = 0;
147425443Sache	}
1475112003Sgad
147680638Sobrien	if ((flags & CE_COMPACT) || (flags & CE_BZCOMPACT)) {
147725443Sache		if (need_notification && !notified)
147880646Sobrien			warnx(
1479112003Sgad			    "log %s.0 not compressed because daemon(s) not notified",
1480119927Sgad			    ent->log);
148125443Sache		else if (noaction)
1482111967Sgad			if (flags & CE_COMPACT)
1483119927Sgad				printf("\tgzip %s.0\n", ent->log);
1484111967Sgad			else
1485119927Sgad				printf("\tbzip2 %s.0\n", ent->log);
148625443Sache		else {
148725443Sache			if (notified) {
148825443Sache				if (verbose)
1489112003Sgad					printf("small pause to allow daemon(s) to close log\n");
149031460Sache				sleep(10);
149125443Sache			}
149259004Shm			if (archtodir) {
149380646Sobrien				(void) snprintf(file1, sizeof(file1), "%s/%s",
149480646Sobrien				    dirpart, namepart);
149580638Sobrien				if (flags & CE_COMPACT)
1496107916Ssobomax					compress_log(file1,
1497107916Ssobomax					    flags & CE_COMPACTWAIT);
149880638Sobrien				else if (flags & CE_BZCOMPACT)
1499107916Ssobomax					bzcompress_log(file1,
1500107916Ssobomax					    flags & CE_COMPACTWAIT);
150159004Shm			} else {
150280638Sobrien				if (flags & CE_COMPACT)
1503119927Sgad					compress_log(ent->log,
1504107916Ssobomax					    flags & CE_COMPACTWAIT);
150580638Sobrien				else if (flags & CE_BZCOMPACT)
1506119927Sgad					bzcompress_log(ent->log,
1507107916Ssobomax					    flags & CE_COMPACTWAIT);
150859004Shm			}
150925443Sache		}
151059003Shm	}
151113244Sgraichen}
151213244Sgraichen
151313244Sgraichen/* Log the fact that the logs were turned over */
151459004Shmstatic int
1515119926Sgadlog_trim(const char *logname, const struct conf_entry *log_ent)
151613244Sgraichen{
151759003Shm	FILE *f;
1518111388Sgad	const char *xtra;
151959003Shm
1520119926Sgad	if ((f = fopen(logname, "a")) == NULL)
152159003Shm		return (-1);
1522111388Sgad	xtra = "";
1523111768Sgad	if (log_ent->def_cfg)
1524111388Sgad		xtra = " using <default> rule";
1525114137Sgad	if (log_ent->firstcreate)
1526114137Sgad		fprintf(f, "%s %s newsyslog[%d]: logfile first created%s\n",
1527114137Sgad		    daytime, hostname, (int) getpid(), xtra);
1528114137Sgad	else if (log_ent->r_reason != NULL)
1529111772Sgad		fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s%s\n",
1530111772Sgad		    daytime, hostname, (int) getpid(), log_ent->r_reason, xtra);
1531111772Sgad	else
1532111772Sgad		fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s\n",
1533111772Sgad		    daytime, hostname, (int) getpid(), xtra);
153459003Shm	if (fclose(f) == EOF)
1535127858Scharnier		err(1, "log_trim: fclose");
153659003Shm	return (0);
153713244Sgraichen}
153813244Sgraichen
153959004Shm/* Fork of gzip to compress the old log file */
154059004Shmstatic void
1541119926Sgadcompress_log(char *logname, int dowait)
154213244Sgraichen{
154359003Shm	pid_t pid;
154471299Sjedgar	char tmp[MAXPATHLEN];
154559003Shm
1546107916Ssobomax	while (dowait && (wait(NULL) > 0 || errno == EINTR))
1547107916Ssobomax		;
1548119926Sgad	(void) snprintf(tmp, sizeof(tmp), "%s.0", logname);
154925443Sache	pid = fork();
155059003Shm	if (pid < 0)
155180638Sobrien		err(1, "gzip fork");
155259003Shm	else if (!pid) {
155379452Sbrian		(void) execl(_PATH_GZIP, _PATH_GZIP, "-f", tmp, (char *)0);
155443071Swollman		err(1, _PATH_GZIP);
155559003Shm	}
155613244Sgraichen}
155713244Sgraichen
155880638Sobrien/* Fork of bzip2 to compress the old log file */
155980638Sobrienstatic void
1560119926Sgadbzcompress_log(char *logname, int dowait)
156180638Sobrien{
156280638Sobrien	pid_t pid;
156380638Sobrien	char tmp[MAXPATHLEN];
156480638Sobrien
1565107916Ssobomax	while (dowait && (wait(NULL) > 0 || errno == EINTR))
1566107916Ssobomax		;
1567119926Sgad	snprintf(tmp, sizeof(tmp), "%s.0", logname);
156880638Sobrien	pid = fork();
156980638Sobrien	if (pid < 0)
157080638Sobrien		err(1, "bzip2 fork");
157180638Sobrien	else if (!pid) {
157286360Sobrien		execl(_PATH_BZIP2, _PATH_BZIP2, "-f", tmp, (char *)0);
157380638Sobrien		err(1, _PATH_BZIP2);
157480638Sobrien	}
157580638Sobrien}
157680638Sobrien
157713244Sgraichen/* Return size in kilobytes of a file */
157859004Shmstatic int
157959004Shmsizefile(char *file)
158013244Sgraichen{
158159003Shm	struct stat sb;
158213244Sgraichen
158359003Shm	if (stat(file, &sb) < 0)
158459003Shm		return (-1);
158559003Shm	return (kbytes(dbtob(sb.st_blocks)));
158613244Sgraichen}
158713244Sgraichen
158813244Sgraichen/* Return the age of old log file (file.0) */
158959004Shmstatic int
159059004Shmage_old_log(char *file)
159113244Sgraichen{
159259003Shm	struct stat sb;
1593114764Sgad	char *endp;
1594114764Sgad	char tmp[MAXPATHLEN + sizeof(".0") + sizeof(COMPRESS_POSTFIX) +
1595114764Sgad		sizeof(BZCOMPRESS_POSTFIX) + 1];
159613244Sgraichen
159759004Shm	if (archtodir) {
159859004Shm		char *p;
159959004Shm
160059004Shm		/* build name of archive directory into tmp */
160159004Shm		if (*archdirname == '/') {	/* absolute */
160271299Sjedgar			strlcpy(tmp, archdirname, sizeof(tmp));
160359004Shm		} else {	/* relative */
160459004Shm			/* get directory part of logfile */
160571299Sjedgar			strlcpy(tmp, file, sizeof(tmp));
160659004Shm			if ((p = rindex(tmp, '/')) == NULL)
160759004Shm				tmp[0] = '\0';
160859004Shm			else
160959004Shm				*(p + 1) = '\0';
161071299Sjedgar			strlcat(tmp, archdirname, sizeof(tmp));
161159004Shm		}
161259004Shm
161371299Sjedgar		strlcat(tmp, "/", sizeof(tmp));
161459004Shm
161559004Shm		/* get filename part of logfile */
161659004Shm		if ((p = rindex(file, '/')) == NULL)
161771299Sjedgar			strlcat(tmp, file, sizeof(tmp));
161859004Shm		else
161971299Sjedgar			strlcat(tmp, p + 1, sizeof(tmp));
162059004Shm	} else {
162171299Sjedgar		(void) strlcpy(tmp, file, sizeof(tmp));
162259004Shm	}
162359004Shm
1624114764Sgad	strlcat(tmp, ".0", sizeof(tmp));
1625114764Sgad	if (stat(tmp, &sb) < 0) {
1626114764Sgad		/*
1627114764Sgad		 * A plain '.0' file does not exist.  Try again, first
1628114764Sgad		 * with the added suffix of '.gz', then with an added
1629114764Sgad		 * suffix of '.bz2' instead of '.gz'.
1630114764Sgad		 */
1631114764Sgad		endp = strchr(tmp, '\0');
1632114764Sgad		strlcat(tmp, COMPRESS_POSTFIX, sizeof(tmp));
1633114764Sgad		if (stat(tmp, &sb) < 0) {
1634114764Sgad			*endp = '\0';		/* Remove .gz */
1635114764Sgad			strlcat(tmp, BZCOMPRESS_POSTFIX, sizeof(tmp));
1636114764Sgad			if (stat(tmp, &sb) < 0)
1637114764Sgad				return (-1);
1638114764Sgad		}
1639114764Sgad	}
1640120361Sgad	return ((int)(ptimeget_secs(timenow) - sb.st_mtime + 1800) / 3600);
164113244Sgraichen}
164213244Sgraichen
164313244Sgraichen/* Skip Over Blanks */
1644111820Sgadstatic char *
164559004Shmsob(char *p)
164613244Sgraichen{
164759003Shm	while (p && *p && isspace(*p))
164859003Shm		p++;
164959003Shm	return (p);
165013244Sgraichen}
165113244Sgraichen
165213244Sgraichen/* Skip Over Non-Blanks */
1653111820Sgadstatic char *
165459004Shmson(char *p)
165513244Sgraichen{
165659003Shm	while (p && *p && !isspace(*p))
165759003Shm		p++;
165859003Shm	return (p);
165913244Sgraichen}
166043071Swollman
1661119102Sgad/* Check if string is actually a number */
1662119102Sgadstatic int
1663119102Sgadisnumberstr(const char *string)
1664119102Sgad{
1665119102Sgad	while (*string) {
1666119102Sgad		if (!isdigitch(*string++))
1667119102Sgad			return (0);
1668119102Sgad	}
1669119102Sgad	return (1);
1670119102Sgad}
1671119102Sgad
167259004Shm/* physically move file */
167359004Shmstatic void
1674129974Sgadmovefile(char *from, char *to)
167559004Shm{
167659004Shm	FILE *src, *dst;
167759004Shm	int c;
167859004Shm
167959004Shm	if ((src = fopen(from, "r")) == NULL)
168059004Shm		err(1, "can't fopen %s for reading", from);
168159004Shm	if ((dst = fopen(to, "w")) == NULL)
168259004Shm		err(1, "can't fopen %s for writing", to);
168359004Shm
168459004Shm	while ((c = getc(src)) != EOF) {
168559004Shm		if ((putc(c, dst)) == EOF)
168659004Shm			err(1, "error writing to %s", to);
168759004Shm	}
168859004Shm
168959004Shm	if (ferror(src))
169059004Shm		err(1, "error reading from %s", from);
169159004Shm	if ((fclose(src)) != 0)
169259004Shm		err(1, "can't fclose %s", to);
169359004Shm	if ((fclose(dst)) != 0)
169459004Shm		err(1, "can't fclose %s", from);
169559004Shm	if ((unlink(from)) != 0)
169659004Shm		err(1, "can't unlink %s", from);
169759004Shm}
169859004Shm
169959004Shm/* create one or more directory components of a path */
170059004Shmstatic void
1701114137Sgadcreatedir(const struct conf_entry *ent, char *dirpart)
170259004Shm{
1703111398Sgad	int res;
170459004Shm	char *s, *d;
170571299Sjedgar	char mkdirpath[MAXPATHLEN];
170659004Shm	struct stat st;
170759004Shm
170859004Shm	s = dirpart;
170959004Shm	d = mkdirpath;
171059004Shm
171159004Shm	for (;;) {
171259004Shm		*d++ = *s++;
1713111398Sgad		if (*s != '/' && *s != '\0')
1714111398Sgad			continue;
1715111398Sgad		*d = '\0';
1716111398Sgad		res = lstat(mkdirpath, &st);
1717111398Sgad		if (res != 0) {
1718111398Sgad			if (noaction) {
1719111967Sgad				printf("\tmkdir %s\n", mkdirpath);
1720111398Sgad			} else {
1721111398Sgad				res = mkdir(mkdirpath, 0755);
1722111398Sgad				if (res != 0)
1723111398Sgad					err(1, "Error on mkdir(\"%s\") for -a",
1724111398Sgad					    mkdirpath);
1725111398Sgad			}
172659004Shm		}
172759004Shm		if (*s == '\0')
172859004Shm			break;
172959004Shm	}
1730114137Sgad	if (verbose) {
1731114137Sgad		if (ent->firstcreate)
1732114137Sgad			printf("Created directory '%s' for new %s\n",
1733114137Sgad			    dirpart, ent->log);
1734114137Sgad		else
1735114137Sgad			printf("Created directory '%s' for -a\n", dirpart);
1736114137Sgad	}
173759004Shm}
173859004Shm
1739114137Sgad/*
1740114137Sgad * Create a new log file, destroying any currently-existing version
1741114137Sgad * of the log file in the process.  If the caller wants a backup copy
1742114137Sgad * of the file to exist, they should call 'link(logfile,logbackup)'
1743114137Sgad * before calling this routine.
1744114137Sgad */
1745114137Sgadvoid
1746114137Sgadcreatelog(const struct conf_entry *ent)
1747114137Sgad{
1748114137Sgad	int fd, failed;
1749114137Sgad	struct stat st;
1750114137Sgad	char *realfile, *slash, tempfile[MAXPATHLEN];
1751114137Sgad
1752114137Sgad	fd = -1;
1753114137Sgad	realfile = ent->log;
1754114137Sgad
1755114137Sgad	/*
1756114137Sgad	 * If this log file is being created for the first time (-C option),
1757114137Sgad	 * then it may also be true that the parent directory does not exist
1758114137Sgad	 * yet.  Check, and create that directory if it is missing.
1759114137Sgad	 */
1760114137Sgad	if (ent->firstcreate) {
1761114137Sgad		strlcpy(tempfile, realfile, sizeof(tempfile));
1762114137Sgad		slash = strrchr(tempfile, '/');
1763114137Sgad		if (slash != NULL) {
1764114137Sgad			*slash = '\0';
1765114137Sgad			failed = lstat(tempfile, &st);
1766114137Sgad			if (failed && errno != ENOENT)
1767114137Sgad				err(1, "Error on lstat(%s)", tempfile);
1768114137Sgad			if (failed)
1769114137Sgad				createdir(ent, tempfile);
1770114137Sgad			else if (!S_ISDIR(st.st_mode))
1771114137Sgad				errx(1, "%s exists but is not a directory",
1772114137Sgad				    tempfile);
1773114137Sgad		}
1774114137Sgad	}
1775114137Sgad
1776114137Sgad	/*
1777114137Sgad	 * First create an unused filename, so it can be chown'ed and
1778114137Sgad	 * chmod'ed before it is moved into the real location.  mkstemp
1779114137Sgad	 * will create the file mode=600 & owned by us.  Note that all
1780114137Sgad	 * temp files will have a suffix of '.z<something>'.
1781114137Sgad	 */
1782114137Sgad	strlcpy(tempfile, realfile, sizeof(tempfile));
1783114137Sgad	strlcat(tempfile, ".zXXXXXX", sizeof(tempfile));
1784114137Sgad	if (noaction)
1785114137Sgad		printf("\tmktemp %s\n", tempfile);
1786114137Sgad	else {
1787114137Sgad		fd = mkstemp(tempfile);
1788114137Sgad		if (fd < 0)
1789114137Sgad			err(1, "can't mkstemp logfile %s", tempfile);
1790114137Sgad
1791114137Sgad		/*
1792114137Sgad		 * Add status message to what will become the new log file.
1793114137Sgad		 */
1794114137Sgad		if (!(ent->flags & CE_BINARY)) {
1795114137Sgad			if (log_trim(tempfile, ent))
1796114137Sgad				err(1, "can't add status message to log");
1797114137Sgad		}
1798114137Sgad	}
1799114137Sgad
1800114137Sgad	/* Change the owner/group, if we are supposed to */
1801114137Sgad	if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
1802114137Sgad		if (noaction)
1803114137Sgad			printf("\tchown %u:%u %s\n", ent->uid, ent->gid,
1804114137Sgad			    tempfile);
1805114137Sgad		else {
1806114137Sgad			failed = fchown(fd, ent->uid, ent->gid);
1807114137Sgad			if (failed)
1808114137Sgad				err(1, "can't fchown temp file %s", tempfile);
1809114137Sgad		}
1810114137Sgad	}
1811114137Sgad
1812114137Sgad	/*
1813114137Sgad	 * Note that if the real logfile still exists, and if the call
1814114137Sgad	 * to rename() fails, then "neither the old file nor the new
1815114137Sgad	 * file shall be changed or created" (to quote the standard).
1816114137Sgad	 * If the call succeeds, then the file will be replaced without
1817114137Sgad	 * any window where some other process might find that the file
1818114137Sgad	 * did not exist.
1819114137Sgad	 * XXX - ? It may be that for some error conditions, we could
1820114137Sgad	 *	retry by first removing the realfile and then renaming.
1821114137Sgad	 */
1822114137Sgad	if (noaction) {
1823114137Sgad		printf("\tchmod %o %s\n", ent->permissions, tempfile);
1824114137Sgad		printf("\tmv %s %s\n", tempfile, realfile);
1825114137Sgad	} else {
1826114137Sgad		failed = fchmod(fd, ent->permissions);
1827114137Sgad		if (failed)
1828114137Sgad			err(1, "can't fchmod temp file '%s'", tempfile);
1829114137Sgad		failed = rename(tempfile, realfile);
1830114137Sgad		if (failed)
1831114137Sgad			err(1, "can't mv %s to %s", tempfile, realfile);
1832114137Sgad	}
1833114137Sgad
1834114137Sgad	if (fd >= 0)
1835114137Sgad		close(fd);
1836114137Sgad}
1837