newsyslog.c revision 130038
1/*
2 * This file contains changes from the Open Software Foundation.
3 */
4
5/*
6 * Copyright 1988, 1989 by the Massachusetts Institute of Technology
7 *
8 * Permission to use, copy, modify, and distribute this software and its
9 * documentation for any purpose and without fee is hereby granted, provided
10 * that the above copyright notice appear in all copies and that both that
11 * copyright notice and this permission notice appear in supporting
12 * documentation, and that the names of M.I.T. and the M.I.T. S.I.P.B. not be
13 * used in advertising or publicity pertaining to distribution of the
14 * software without specific, written prior permission. M.I.T. and the M.I.T.
15 * S.I.P.B. make no representations about the suitability of this software
16 * for any purpose.  It is provided "as is" without express or implied
17 * warranty.
18 *
19 */
20
21/*
22 * newsyslog - roll over selected logs at the appropriate time, keeping the a
23 * specified number of backup files around.
24 */
25
26#include <sys/cdefs.h>
27__FBSDID("$FreeBSD: head/usr.sbin/newsyslog/newsyslog.c 130038 2004-06-03 22:26:16Z gad $");
28
29#define OSF
30#ifndef COMPRESS_POSTFIX
31#define COMPRESS_POSTFIX ".gz"
32#endif
33#ifndef	BZCOMPRESS_POSTFIX
34#define	BZCOMPRESS_POSTFIX ".bz2"
35#endif
36
37#include <sys/param.h>
38#include <sys/stat.h>
39#include <sys/wait.h>
40
41#include <ctype.h>
42#include <err.h>
43#include <errno.h>
44#include <fcntl.h>
45#include <fnmatch.h>
46#include <glob.h>
47#include <grp.h>
48#include <paths.h>
49#include <pwd.h>
50#include <signal.h>
51#include <stdio.h>
52#include <stdlib.h>
53#include <string.h>
54#include <time.h>
55#include <unistd.h>
56
57#include "pathnames.h"
58#include "extern.h"
59
60/*
61 * Bit-values for the 'flags' parsed from a config-file entry.
62 */
63#define CE_COMPACT	0x0001	/* Compact the achived log files with gzip. */
64#define CE_BZCOMPACT	0x0002	/* Compact the achived log files with bzip2. */
65#define CE_COMPACTWAIT	0x0004	/* wait until compressing one file finishes */
66				/*    before starting the next step. */
67#define CE_BINARY	0x0008	/* Logfile is in binary, do not add status */
68				/*    messages to logfile(s) when rotating. */
69#define CE_NOSIGNAL	0x0010	/* There is no process to signal when */
70				/*    trimming this file. */
71#define CE_TRIMAT	0x0020	/* trim file at a specific time. */
72#define CE_GLOB		0x0040	/* name of the log is file name pattern. */
73#define CE_SIGNALGROUP	0x0080	/* Signal a process-group instead of a single */
74				/*    process when trimming this file. */
75#define CE_CREATE	0x0100	/* Create the log file if it does not exist. */
76
77#define MIN_PID         5	/* Don't touch pids lower than this */
78#define MAX_PID		99999	/* was lower, see /usr/include/sys/proc.h */
79
80#define kbytes(size)  (((size) + 1023) >> 10)
81
82struct conf_entry {
83	char *log;		/* Name of the log */
84	char *pid_file;		/* PID file */
85	char *r_reason;		/* The reason this file is being rotated */
86	int firstcreate;	/* Creating log for the first time (-C). */
87	int rotate;		/* Non-zero if this file should be rotated */
88	uid_t uid;		/* Owner of log */
89	gid_t gid;		/* Group of log */
90	int numlogs;		/* Number of logs to keep */
91	int size;		/* Size cutoff to trigger trimming the log */
92	int hours;		/* Hours between log trimming */
93	struct ptime_data *trim_at;	/* Specific time to do trimming */
94	int permissions;	/* File permissions on the log */
95	int flags;		/* CE_COMPACT, CE_BZCOMPACT, CE_BINARY */
96	int sig;		/* Signal to send */
97	int def_cfg;		/* Using the <default> rule for this file */
98	struct conf_entry *next;/* Linked list pointer */
99};
100
101#define DEFAULT_MARKER "<default>"
102
103int dbg_at_times;		/* -D Show details of 'trim_at' code */
104
105int archtodir = 0;		/* Archive old logfiles to other directory */
106int createlogs;			/* Create (non-GLOB) logfiles which do not */
107				/*    already exist.  1=='for entries with */
108				/*    C flag', 2=='for all entries'. */
109int verbose = 0;		/* Print out what's going on */
110int needroot = 1;		/* Root privs are necessary */
111int noaction = 0;		/* Don't do anything, just show it */
112int nosignal;			/* Do not send any signals */
113int force = 0;			/* Force the trim no matter what */
114int rotatereq = 0;		/* -R = Always rotate the file(s) as given */
115				/*    on the command (this also requires   */
116				/*    that a list of files *are* given on  */
117				/*    the run command). */
118char *requestor;		/* The name given on a -R request */
119char *archdirname;		/* Directory path to old logfiles archive */
120const char *conf;		/* Configuration file to use */
121
122struct ptime_data *dbg_timenow;	/* A "timenow" value set via -D option */
123struct ptime_data *timenow;	/* The time to use for checking at-fields */
124
125char hostname[MAXHOSTNAMELEN];	/* hostname */
126char daytime[16];		/* The current time in human readable form,
127				 * used for rotation-tracking messages. */
128
129static struct conf_entry *get_worklist(char **files);
130static void parse_file(FILE *cf, const char *cfname, struct conf_entry **work_p,
131		struct conf_entry **glob_p, struct conf_entry **defconf_p);
132static char *sob(char *p);
133static char *son(char *p);
134static int isnumberstr(const char *);
135static char *missing_field(char *p, char *errline);
136static void do_entry(struct conf_entry * ent);
137static void expand_globs(struct conf_entry **work_p,
138		struct conf_entry **glob_p);
139static void free_clist(struct conf_entry **firstent);
140static void free_entry(struct conf_entry *ent);
141static struct conf_entry *init_entry(const char *fname,
142		struct conf_entry *src_entry);
143static void parse_args(int argc, char **argv);
144static int parse_doption(const char *doption);
145static void usage(void);
146static void dotrim(const struct conf_entry *ent);
147static int log_trim(const char *logname, const struct conf_entry *log_ent);
148static void compress_log(char *logname, int dowait);
149static void bzcompress_log(char *logname, int dowait);
150static int sizefile(char *file);
151static int age_old_log(char *file);
152static int send_signal(const struct conf_entry *ent);
153static void savelog(char *from, char *to);
154static void createdir(const struct conf_entry *ent, char *dirpart);
155static void createlog(const struct conf_entry *ent);
156
157/*
158 * All the following take a parameter of 'int', but expect values in the
159 * range of unsigned char.  Define wrappers which take values of type 'char',
160 * whether signed or unsigned, and ensure they end up in the right range.
161 */
162#define	isdigitch(Anychar) isdigit((u_char)(Anychar))
163#define	isprintch(Anychar) isprint((u_char)(Anychar))
164#define	isspacech(Anychar) isspace((u_char)(Anychar))
165#define	tolowerch(Anychar) tolower((u_char)(Anychar))
166
167int
168main(int argc, char **argv)
169{
170	struct conf_entry *p, *q;
171
172	parse_args(argc, argv);
173	argc -= optind;
174	argv += optind;
175
176	if (needroot && getuid() && geteuid())
177		errx(1, "must have root privs");
178	p = q = get_worklist(argv);
179
180	while (p) {
181		do_entry(p);
182		p = p->next;
183		free_entry(q);
184		q = p;
185	}
186	while (wait(NULL) > 0 || errno == EINTR)
187		;
188	return (0);
189}
190
191static struct conf_entry *
192init_entry(const char *fname, struct conf_entry *src_entry)
193{
194	struct conf_entry *tempwork;
195
196	if (verbose > 4)
197		printf("\t--> [creating entry for %s]\n", fname);
198
199	tempwork = malloc(sizeof(struct conf_entry));
200	if (tempwork == NULL)
201		err(1, "malloc of conf_entry for %s", fname);
202
203	tempwork->log = strdup(fname);
204	if (tempwork->log == NULL)
205		err(1, "strdup for %s", fname);
206
207	if (src_entry != NULL) {
208		tempwork->pid_file = NULL;
209		if (src_entry->pid_file)
210			tempwork->pid_file = strdup(src_entry->pid_file);
211		tempwork->r_reason = NULL;
212		tempwork->firstcreate = 0;
213		tempwork->rotate = 0;
214		tempwork->uid = src_entry->uid;
215		tempwork->gid = src_entry->gid;
216		tempwork->numlogs = src_entry->numlogs;
217		tempwork->size = src_entry->size;
218		tempwork->hours = src_entry->hours;
219		tempwork->trim_at = NULL;
220		if (src_entry->trim_at != NULL)
221			tempwork->trim_at = ptime_init(src_entry->trim_at);
222		tempwork->permissions = src_entry->permissions;
223		tempwork->flags = src_entry->flags;
224		tempwork->sig = src_entry->sig;
225		tempwork->def_cfg = src_entry->def_cfg;
226	} else {
227		/* Initialize as a "do-nothing" entry */
228		tempwork->pid_file = NULL;
229		tempwork->r_reason = NULL;
230		tempwork->firstcreate = 0;
231		tempwork->rotate = 0;
232		tempwork->uid = (uid_t)-1;
233		tempwork->gid = (gid_t)-1;
234		tempwork->numlogs = 1;
235		tempwork->size = -1;
236		tempwork->hours = -1;
237		tempwork->trim_at = NULL;
238		tempwork->permissions = 0;
239		tempwork->flags = 0;
240		tempwork->sig = SIGHUP;
241		tempwork->def_cfg = 0;
242	}
243	tempwork->next = NULL;
244
245	return (tempwork);
246}
247
248static void
249free_entry(struct conf_entry *ent)
250{
251
252	if (ent == NULL)
253		return;
254
255	if (ent->log != NULL) {
256		if (verbose > 4)
257			printf("\t--> [freeing entry for %s]\n", ent->log);
258		free(ent->log);
259		ent->log = NULL;
260	}
261
262	if (ent->pid_file != NULL) {
263		free(ent->pid_file);
264		ent->pid_file = NULL;
265	}
266
267	if (ent->r_reason != NULL) {
268		free(ent->r_reason);
269		ent->r_reason = NULL;
270	}
271
272	if (ent->trim_at != NULL) {
273		ptime_free(ent->trim_at);
274		ent->trim_at = NULL;
275	}
276
277	free(ent);
278}
279
280static void
281free_clist(struct conf_entry **firstent)
282{
283	struct conf_entry *ent, *nextent;
284
285	if (firstent == NULL)
286		return;			/* There is nothing to do. */
287
288	ent = *firstent;
289	firstent = NULL;
290
291	while (ent) {
292		nextent = ent->next;
293		free_entry(ent);
294		ent = nextent;
295	}
296}
297
298static void
299do_entry(struct conf_entry * ent)
300{
301#define REASON_MAX	80
302	int size, modtime;
303	double diffsecs;
304	char temp_reason[REASON_MAX];
305
306	if (verbose) {
307		if (ent->flags & CE_COMPACT)
308			printf("%s <%dZ>: ", ent->log, ent->numlogs);
309		else if (ent->flags & CE_BZCOMPACT)
310			printf("%s <%dJ>: ", ent->log, ent->numlogs);
311		else
312			printf("%s <%d>: ", ent->log, ent->numlogs);
313	}
314	size = sizefile(ent->log);
315	modtime = age_old_log(ent->log);
316	ent->rotate = 0;
317	ent->firstcreate = 0;
318	if (size < 0) {
319		/*
320		 * If either the C flag or the -C option was specified,
321		 * and if we won't be creating the file, then have the
322		 * verbose message include a hint as to why the file
323		 * will not be created.
324		 */
325		temp_reason[0] = '\0';
326		if (createlogs > 1)
327			ent->firstcreate = 1;
328		else if ((ent->flags & CE_CREATE) && createlogs)
329			ent->firstcreate = 1;
330		else if (ent->flags & CE_CREATE)
331			strncpy(temp_reason, " (no -C option)", REASON_MAX);
332		else if (createlogs)
333			strncpy(temp_reason, " (no C flag)", REASON_MAX);
334
335		if (ent->firstcreate) {
336			if (verbose)
337				printf("does not exist -> will create.\n");
338			createlog(ent);
339		} else if (verbose) {
340			printf("does not exist, skipped%s.\n", temp_reason);
341		}
342	} else {
343		if (ent->flags & CE_TRIMAT && !force && !rotatereq) {
344			diffsecs = ptimeget_diff(timenow, ent->trim_at);
345			if (diffsecs < 0.0) {
346				/* trim_at is some time in the future. */
347				if (verbose) {
348					ptime_adjust4dst(ent->trim_at,
349					    timenow);
350					printf("--> will trim at %s",
351					    ptimeget_ctime(ent->trim_at));
352				}
353				return;
354			} else if (diffsecs >= 3600.0) {
355				/*
356				 * trim_at is more than an hour in the past,
357				 * so find the next valid trim_at time, and
358				 * tell the user what that will be.
359				 */
360				if (verbose && dbg_at_times)
361					printf("\n\t--> prev trim at %s\t",
362					    ptimeget_ctime(ent->trim_at));
363				if (verbose) {
364					ptimeset_nxtime(ent->trim_at);
365					printf("--> will trim at %s",
366					    ptimeget_ctime(ent->trim_at));
367				}
368				return;
369			} else if (verbose && noaction && dbg_at_times) {
370				/*
371				 * If we are just debugging at-times, then
372				 * a detailed message is helpful.  Also
373				 * skip "doing" any commands, since they
374				 * would all be turned off by no-action.
375				 */
376				printf("\n\t--> timematch at %s",
377				    ptimeget_ctime(ent->trim_at));
378				return;
379			} else if (verbose && ent->hours <= 0) {
380				printf("--> time is up\n");
381			}
382		}
383		if (verbose && (ent->size > 0))
384			printf("size (Kb): %d [%d] ", size, ent->size);
385		if (verbose && (ent->hours > 0))
386			printf(" age (hr): %d [%d] ", modtime, ent->hours);
387
388		/*
389		 * Figure out if this logfile needs to be rotated.
390		 */
391		temp_reason[0] = '\0';
392		if (rotatereq) {
393			ent->rotate = 1;
394			snprintf(temp_reason, REASON_MAX, " due to -R from %s",
395			    requestor);
396		} else if (force) {
397			ent->rotate = 1;
398			snprintf(temp_reason, REASON_MAX, " due to -F request");
399		} else if ((ent->size > 0) && (size >= ent->size)) {
400			ent->rotate = 1;
401			snprintf(temp_reason, REASON_MAX, " due to size>%dK",
402			    ent->size);
403		} else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) {
404			ent->rotate = 1;
405		} else if ((ent->hours > 0) && ((modtime >= ent->hours) ||
406		    (modtime < 0))) {
407			ent->rotate = 1;
408		}
409
410		/*
411		 * If the file needs to be rotated, then rotate it.
412		 */
413		if (ent->rotate) {
414			if (temp_reason[0] != '\0')
415				ent->r_reason = strdup(temp_reason);
416			if (verbose)
417				printf("--> trimming log....\n");
418			if (noaction && !verbose) {
419				if (ent->flags & CE_COMPACT)
420					printf("%s <%dZ>: trimming\n",
421					    ent->log, ent->numlogs);
422				else if (ent->flags & CE_BZCOMPACT)
423					printf("%s <%dJ>: trimming\n",
424					    ent->log, ent->numlogs);
425				else
426					printf("%s <%d>: trimming\n",
427					    ent->log, ent->numlogs);
428			}
429			dotrim(ent);
430		} else {
431			if (verbose)
432				printf("--> skipping\n");
433		}
434	}
435#undef REASON_MAX
436}
437
438/* Send a signal to the pid specified by pidfile */
439static int
440send_signal(const struct conf_entry *ent)
441{
442	pid_t target_pid;
443	int did_notify;
444	FILE *f;
445	long minok, maxok, rval;
446	const char *target_name;
447	char *endp, *linep, line[BUFSIZ];
448
449	did_notify = 0;
450	f = fopen(ent->pid_file, "r");
451	if (f == NULL) {
452		warn("can't open pid file: %s", ent->pid_file);
453		return (did_notify);
454		/* NOTREACHED */
455	}
456
457	if (fgets(line, BUFSIZ, f) == NULL) {
458		/*
459		 * XXX - If the pid file is empty, is that really a
460		 *	problem?  Wouldn't that mean that the process
461		 *	has shut down?  In that case there would be no
462		 *	problem with compressing the rotated log file.
463		 */
464		if (feof(f))
465			warnx("pid file is empty: %s",  ent->pid_file);
466		else
467			warn("can't read from pid file: %s", ent->pid_file);
468		(void) fclose(f);
469		return (did_notify);
470		/* NOTREACHED */
471	}
472	(void) fclose(f);
473
474	target_name = "daemon";
475	minok = MIN_PID;
476	maxok = MAX_PID;
477	if (ent->flags & CE_SIGNALGROUP) {
478		/*
479		 * If we are expected to signal a process-group when
480		 * rotating this logfile, then the value read in should
481		 * be the negative of a valid process ID.
482		 */
483		target_name = "process-group";
484		minok = -MAX_PID;
485		maxok = -MIN_PID;
486	}
487
488	errno = 0;
489	linep = line;
490	while (*linep == ' ')
491		linep++;
492	rval = strtol(linep, &endp, 10);
493	if (*endp != '\0' && !isspacech(*endp)) {
494		warnx("pid file does not start with a valid number: %s",
495		    ent->pid_file);
496		rval = 0;
497	} else if (rval < minok || rval > maxok) {
498		warnx("bad value '%ld' for process number in %s",
499		    rval, ent->pid_file);
500		if (verbose)
501			warnx("\t(expecting value between %ld and %ld)",
502			    minok, maxok);
503		rval = 0;
504	}
505	if (rval == 0) {
506		return (did_notify);
507		/* NOTREACHED */
508	}
509
510	target_pid = rval;
511
512	if (noaction) {
513		did_notify = 1;
514		printf("\tkill -%d %d\n", ent->sig, (int) target_pid);
515	} else if (kill(target_pid, ent->sig)) {
516		/*
517		 * XXX - Iff the error was "no such process", should that
518		 *	really be an error for us?  Perhaps the process
519		 *	is already gone, in which case there would be no
520		 *	problem with compressing the rotated log file.
521		 */
522		warn("can't notify %s, pid %d", target_name,
523		    (int) target_pid);
524	} else {
525		did_notify = 1;
526		if (verbose)
527			printf("%s pid %d notified\n", target_name,
528			    (int) target_pid);
529	}
530
531	return (did_notify);
532}
533
534static void
535parse_args(int argc, char **argv)
536{
537	int ch;
538	char *p;
539
540	timenow = ptime_init(NULL);
541	ptimeset_time(timenow, time(NULL));
542	(void)strncpy(daytime, ptimeget_ctime(timenow) + 4, 15);
543	daytime[15] = '\0';
544
545	/* Let's get our hostname */
546	(void)gethostname(hostname, sizeof(hostname));
547
548	/* Truncate domain */
549	if ((p = strchr(hostname, '.')) != NULL)
550		*p = '\0';
551
552	/* Parse command line options. */
553	while ((ch = getopt(argc, argv, "a:f:nrsvCD:FR:")) != -1)
554		switch (ch) {
555		case 'a':
556			archtodir++;
557			archdirname = optarg;
558			break;
559		case 'f':
560			conf = optarg;
561			break;
562		case 'n':
563			noaction++;
564			break;
565		case 'r':
566			needroot = 0;
567			break;
568		case 's':
569			nosignal = 1;
570			break;
571		case 'v':
572			verbose++;
573			break;
574		case 'C':
575			/* Useful for things like rc.diskless... */
576			createlogs++;
577			break;
578		case 'D':
579			/*
580			 * Set some debugging option.  The specific option
581			 * depends on the value of optarg.  These options
582			 * may come and go without notice or documentation.
583			 */
584			if (parse_doption(optarg))
585				break;
586			usage();
587			/* NOTREACHED */
588		case 'F':
589			force++;
590			break;
591		case 'R':
592			rotatereq++;
593			requestor = strdup(optarg);
594			break;
595		case 'm':	/* Used by OpenBSD for "monitor mode" */
596		default:
597			usage();
598			/* NOTREACHED */
599		}
600
601	if (rotatereq) {
602		if (optind == argc) {
603			warnx("At least one filename must be given when -R is specified.");
604			usage();
605			/* NOTREACHED */
606		}
607		/* Make sure "requestor" value is safe for a syslog message. */
608		for (p = requestor; *p != '\0'; p++) {
609			if (!isprintch(*p) && (*p != '\t'))
610				*p = '.';
611		}
612	}
613
614	if (dbg_timenow) {
615		/*
616		 * Note that the 'daytime' variable is not changed.
617		 * That is only used in messages that track when a
618		 * logfile is rotated, and if a file *is* rotated,
619		 * then it will still rotated at the "real now" time.
620		 */
621		ptime_free(timenow);
622		timenow = dbg_timenow;
623		fprintf(stderr, "Debug: Running as if TimeNow is %s",
624		    ptimeget_ctime(dbg_timenow));
625	}
626
627}
628
629/*
630 * These debugging options are mainly meant for developer use, such
631 * as writing regression-tests.  They would not be needed by users
632 * during normal operation of newsyslog...
633 */
634static int
635parse_doption(const char *doption)
636{
637	const char TN[] = "TN=";
638	int res;
639
640	if (strncmp(doption, TN, sizeof(TN) - 1) == 0) {
641		/*
642		 * The "TimeNow" debugging option.  This might be off
643		 * by an hour when crossing a timezone change.
644		 */
645		dbg_timenow = ptime_init(NULL);
646		res = ptime_relparse(dbg_timenow, PTM_PARSE_ISO8601,
647		    time(NULL), doption + sizeof(TN) - 1);
648		if (res == -2) {
649			warnx("Non-existent time specified on -D %s", doption);
650			return (0);			/* failure */
651		} else if (res < 0) {
652			warnx("Malformed time given on -D %s", doption);
653			return (0);			/* failure */
654		}
655		return (1);			/* successfully parsed */
656
657	}
658
659	if (strcmp(doption, "ats") == 0) {
660		dbg_at_times++;
661		return (1);			/* successfully parsed */
662	}
663
664	warnx("Unknown -D (debug) option: %s", doption);
665	return (0);				/* failure */
666}
667
668static void
669usage(void)
670{
671
672	fprintf(stderr,
673	    "usage: newsyslog [-CFnrsv] [-a directory] [-f config-file]\n"
674	    "                 [ [-R requestor] filename ... ]\n");
675	exit(1);
676}
677
678/*
679 * Parse a configuration file and return a linked list of all the logs
680 * which should be processed.
681 */
682static struct conf_entry *
683get_worklist(char **files)
684{
685	FILE *f;
686	const char *fname;
687	char **given;
688	struct conf_entry *defconf, *dupent, *ent, *firstnew;
689	struct conf_entry *globlist, *lastnew, *worklist;
690	int gmatch, fnres;
691
692	defconf = globlist = worklist = NULL;
693
694	fname = conf;
695	if (fname == NULL)
696		fname = _PATH_CONF;
697
698	if (strcmp(fname, "-") != 0)
699		f = fopen(fname, "r");
700	else {
701		f = stdin;
702		fname = "<stdin>";
703	}
704	if (!f)
705		err(1, "%s", conf);
706
707	parse_file(f, fname, &worklist, &globlist, &defconf);
708	(void) fclose(f);
709
710	/*
711	 * All config-file information has been read in and turned into
712	 * a worklist and a globlist.  If there were no specific files
713	 * given on the run command, then the only thing left to do is to
714	 * call a routine which finds all files matched by the globlist
715	 * and adds them to the worklist.  Then return the worklist.
716	 */
717	if (*files == NULL) {
718		expand_globs(&worklist, &globlist);
719		free_clist(&globlist);
720		if (defconf != NULL)
721			free_entry(defconf);
722		return (worklist);
723		/* NOTREACHED */
724	}
725
726	/*
727	 * If newsyslog was given a specific list of files to process,
728	 * it may be that some of those files were not listed in any
729	 * config file.  Those unlisted files should get the default
730	 * rotation action.  First, create the default-rotation action
731	 * if none was found in a system config file.
732	 */
733	if (defconf == NULL) {
734		defconf = init_entry(DEFAULT_MARKER, NULL);
735		defconf->numlogs = 3;
736		defconf->size = 50;
737		defconf->permissions = S_IRUSR|S_IWUSR;
738	}
739
740	/*
741	 * If newsyslog was run with a list of specific filenames,
742	 * then create a new worklist which has only those files in
743	 * it, picking up the rotation-rules for those files from
744	 * the original worklist.
745	 *
746	 * XXX - Note that this will copy multiple rules for a single
747	 *	logfile, if multiple entries are an exact match for
748	 *	that file.  That matches the historic behavior, but do
749	 *	we want to continue to allow it?  If so, it should
750	 *	probably be handled more intelligently.
751	 */
752	firstnew = lastnew = NULL;
753	for (given = files; *given; ++given) {
754		/*
755		 * First try to find exact-matches for this given file.
756		 */
757		gmatch = 0;
758		for (ent = worklist; ent; ent = ent->next) {
759			if (strcmp(ent->log, *given) == 0) {
760				gmatch++;
761				dupent = init_entry(*given, ent);
762				if (!firstnew)
763					firstnew = dupent;
764				else
765					lastnew->next = dupent;
766				lastnew = dupent;
767			}
768		}
769		if (gmatch) {
770			if (verbose > 2)
771				printf("\t+ Matched entry %s\n", *given);
772			continue;
773		}
774
775		/*
776		 * There was no exact-match for this given file, so look
777		 * for a "glob" entry which does match.
778		 */
779		gmatch = 0;
780		if (verbose > 2 && globlist != NULL)
781			printf("\t+ Checking globs for %s\n", *given);
782		for (ent = globlist; ent; ent = ent->next) {
783			fnres = fnmatch(ent->log, *given, FNM_PATHNAME);
784			if (verbose > 2)
785				printf("\t+    = %d for pattern %s\n", fnres,
786				    ent->log);
787			if (fnres == 0) {
788				gmatch++;
789				dupent = init_entry(*given, ent);
790				if (!firstnew)
791					firstnew = dupent;
792				else
793					lastnew->next = dupent;
794				lastnew = dupent;
795				/* This new entry is not a glob! */
796				dupent->flags &= ~CE_GLOB;
797				/* Only allow a match to one glob-entry */
798				break;
799			}
800		}
801		if (gmatch) {
802			if (verbose > 2)
803				printf("\t+ Matched %s via %s\n", *given,
804				    ent->log);
805			continue;
806		}
807
808		/*
809		 * This given file was not found in any config file, so
810		 * add a worklist item based on the default entry.
811		 */
812		if (verbose > 2)
813			printf("\t+ No entry matched %s  (will use %s)\n",
814			    *given, DEFAULT_MARKER);
815		dupent = init_entry(*given, defconf);
816		if (!firstnew)
817			firstnew = dupent;
818		else
819			lastnew->next = dupent;
820		/* Mark that it was *not* found in a config file */
821		dupent->def_cfg = 1;
822		lastnew = dupent;
823	}
824
825	/*
826	 * Free all the entries in the original work list, the list of
827	 * glob entries, and the default entry.
828	 */
829	free_clist(&worklist);
830	free_clist(&globlist);
831	free_entry(defconf);
832
833	/* And finally, return a worklist which matches the given files. */
834	return (firstnew);
835}
836
837/*
838 * Expand the list of entries with filename patterns, and add all files
839 * which match those glob-entries onto the worklist.
840 */
841static void
842expand_globs(struct conf_entry **work_p, struct conf_entry **glob_p)
843{
844	int gmatch, gres, i;
845	char *mfname;
846	struct conf_entry *dupent, *ent, *firstmatch, *globent;
847	struct conf_entry *lastmatch;
848	glob_t pglob;
849	struct stat st_fm;
850
851	if ((glob_p == NULL) || (*glob_p == NULL))
852		return;			/* There is nothing to do. */
853
854	/*
855	 * The worklist contains all fully-specified (non-GLOB) names.
856	 *
857	 * Now expand the list of filename-pattern (GLOB) entries into
858	 * a second list, which (by definition) will only match files
859	 * that already exist.  Do not add a glob-related entry for any
860	 * file which already exists in the fully-specified list.
861	 */
862	firstmatch = lastmatch = NULL;
863	for (globent = *glob_p; globent; globent = globent->next) {
864
865		gres = glob(globent->log, GLOB_NOCHECK, NULL, &pglob);
866		if (gres != 0) {
867			warn("cannot expand pattern (%d): %s", gres,
868			    globent->log);
869			continue;
870		}
871
872		if (verbose > 2)
873			printf("\t+ Expanding pattern %s\n", globent->log);
874		for (i = 0; i < pglob.gl_matchc; i++) {
875			mfname = pglob.gl_pathv[i];
876
877			/* See if this file already has a specific entry. */
878			gmatch = 0;
879			for (ent = *work_p; ent; ent = ent->next) {
880				if (strcmp(mfname, ent->log) == 0) {
881					gmatch++;
882					break;
883				}
884			}
885			if (gmatch)
886				continue;
887
888			/* Make sure the named matched is a file. */
889			gres = lstat(mfname, &st_fm);
890			if (gres != 0) {
891				/* Error on a file that glob() matched?!? */
892				warn("Skipping %s - lstat() error", mfname);
893				continue;
894			}
895			if (!S_ISREG(st_fm.st_mode)) {
896				/* We only rotate files! */
897				if (verbose > 2)
898					printf("\t+  . skipping %s (!file)\n",
899					    mfname);
900				continue;
901			}
902
903			if (verbose > 2)
904				printf("\t+  . add file %s\n", mfname);
905			dupent = init_entry(mfname, globent);
906			if (!firstmatch)
907				firstmatch = dupent;
908			else
909				lastmatch->next = dupent;
910			lastmatch = dupent;
911			/* This new entry is not a glob! */
912			dupent->flags &= ~CE_GLOB;
913		}
914		globfree(&pglob);
915		if (verbose > 2)
916			printf("\t+ Done with pattern %s\n", globent->log);
917	}
918
919	/* Add the list of matched files to the end of the worklist. */
920	if (!*work_p)
921		*work_p = firstmatch;
922	else {
923		ent = *work_p;
924		while (ent->next)
925			ent = ent->next;
926		ent->next = firstmatch;
927	}
928
929}
930
931/*
932 * Parse a configuration file and update a linked list of all the logs to
933 * process.
934 */
935static void
936parse_file(FILE *cf, const char *cfname, struct conf_entry **work_p,
937    struct conf_entry **glob_p, struct conf_entry **defconf_p)
938{
939	char line[BUFSIZ], *parse, *q;
940	char *cp, *errline, *group;
941	struct conf_entry *lastglob, *lastwork, *working;
942	struct passwd *pwd;
943	struct group *grp;
944	int eol, ptm_opts, res, special;
945
946	/*
947	 * XXX - for now, assume that only one config file will be read,
948	 *	ie, this routine is only called one time.
949	 */
950	lastglob = lastwork = NULL;
951
952	while (fgets(line, BUFSIZ, cf)) {
953		if ((line[0] == '\n') || (line[0] == '#') ||
954		    (strlen(line) == 0))
955			continue;
956		errline = strdup(line);
957		for (cp = line + 1; *cp != '\0'; cp++) {
958			if (*cp != '#')
959				continue;
960			if (*(cp - 1) == '\\') {
961				strcpy(cp - 1, cp);
962				cp--;
963				continue;
964			}
965			*cp = '\0';
966			break;
967		}
968
969		q = parse = missing_field(sob(line), errline);
970		parse = son(line);
971		if (!*parse)
972			errx(1, "malformed line (missing fields):\n%s",
973			    errline);
974		*parse = '\0';
975
976		special = 0;
977		working = init_entry(q, NULL);
978		if (strcasecmp(DEFAULT_MARKER, q) == 0) {
979			special = 1;
980			if (defconf_p == NULL) {
981				warnx("Ignoring entry for %s in %s!", q,
982				    cfname);
983				free_entry(working);
984				continue;
985			} else if (*defconf_p != NULL) {
986				warnx("Ignoring duplicate entry for %s!", q);
987				free_entry(working);
988				continue;
989			}
990			*defconf_p = working;
991		}
992
993		q = parse = missing_field(sob(++parse), errline);
994		parse = son(parse);
995		if (!*parse)
996			errx(1, "malformed line (missing fields):\n%s",
997			    errline);
998		*parse = '\0';
999		if ((group = strchr(q, ':')) != NULL ||
1000		    (group = strrchr(q, '.')) != NULL) {
1001			*group++ = '\0';
1002			if (*q) {
1003				if (!(isnumberstr(q))) {
1004					if ((pwd = getpwnam(q)) == NULL)
1005						errx(1,
1006				     "error in config file; unknown user:\n%s",
1007						    errline);
1008					working->uid = pwd->pw_uid;
1009				} else
1010					working->uid = atoi(q);
1011			} else
1012				working->uid = (uid_t)-1;
1013
1014			q = group;
1015			if (*q) {
1016				if (!(isnumberstr(q))) {
1017					if ((grp = getgrnam(q)) == NULL)
1018						errx(1,
1019				    "error in config file; unknown group:\n%s",
1020						    errline);
1021					working->gid = grp->gr_gid;
1022				} else
1023					working->gid = atoi(q);
1024			} else
1025				working->gid = (gid_t)-1;
1026
1027			q = parse = missing_field(sob(++parse), errline);
1028			parse = son(parse);
1029			if (!*parse)
1030				errx(1, "malformed line (missing fields):\n%s",
1031				    errline);
1032			*parse = '\0';
1033		} else {
1034			working->uid = (uid_t)-1;
1035			working->gid = (gid_t)-1;
1036		}
1037
1038		if (!sscanf(q, "%o", &working->permissions))
1039			errx(1, "error in config file; bad permissions:\n%s",
1040			    errline);
1041
1042		q = parse = missing_field(sob(++parse), errline);
1043		parse = son(parse);
1044		if (!*parse)
1045			errx(1, "malformed line (missing fields):\n%s",
1046			    errline);
1047		*parse = '\0';
1048		if (!sscanf(q, "%d", &working->numlogs) || working->numlogs < 0)
1049			errx(1, "error in config file; bad value for count of logs to save:\n%s",
1050			    errline);
1051
1052		q = parse = missing_field(sob(++parse), errline);
1053		parse = son(parse);
1054		if (!*parse)
1055			errx(1, "malformed line (missing fields):\n%s",
1056			    errline);
1057		*parse = '\0';
1058		if (isdigitch(*q))
1059			working->size = atoi(q);
1060		else if (strcmp(q,"*") == 0)
1061			working->size = -1;
1062		else {
1063			warnx("Invalid value of '%s' for 'size' in line:\n%s",
1064			    q, errline);
1065			working->size = -1;
1066		}
1067
1068		working->flags = 0;
1069		q = parse = missing_field(sob(++parse), errline);
1070		parse = son(parse);
1071		eol = !*parse;
1072		*parse = '\0';
1073		{
1074			char *ep;
1075			u_long ul;
1076
1077			ul = strtoul(q, &ep, 10);
1078			if (ep == q)
1079				working->hours = 0;
1080			else if (*ep == '*')
1081				working->hours = -1;
1082			else if (ul > INT_MAX)
1083				errx(1, "interval is too large:\n%s", errline);
1084			else
1085				working->hours = ul;
1086
1087			if (*ep == '\0' || strcmp(ep, "*") == 0)
1088				goto no_trimat;
1089			if (*ep != '@' && *ep != '$')
1090				errx(1, "malformed interval/at:\n%s", errline);
1091
1092			working->flags |= CE_TRIMAT;
1093			working->trim_at = ptime_init(NULL);
1094			ptm_opts = PTM_PARSE_ISO8601;
1095			if (*ep == '$')
1096				ptm_opts = PTM_PARSE_DWM;
1097			ptm_opts |= PTM_PARSE_MATCHDOM;
1098			res = ptime_relparse(working->trim_at, ptm_opts,
1099			    ptimeget_secs(timenow), ep + 1);
1100			if (res == -2)
1101				errx(1, "nonexistent time for 'at' value:\n%s",
1102				    errline);
1103			else if (res < 0)
1104				errx(1, "malformed 'at' value:\n%s", errline);
1105		}
1106no_trimat:
1107
1108		if (eol)
1109			q = NULL;
1110		else {
1111			q = parse = sob(++parse);	/* Optional field */
1112			parse = son(parse);
1113			if (!*parse)
1114				eol = 1;
1115			*parse = '\0';
1116		}
1117
1118		for (; q && *q && !isspacech(*q); q++) {
1119			switch (tolowerch(*q)) {
1120			case 'b':
1121				working->flags |= CE_BINARY;
1122				break;
1123			case 'c':
1124				/*
1125				 * XXX - 	Ick! Ugly! Remove ASAP!
1126				 * We want `c' and `C' for "create".  But we
1127				 * will temporarily treat `c' as `g', because
1128				 * FreeBSD releases <= 4.8 have a typo of
1129				 * checking  ('G' || 'c')  for CE_GLOB.
1130				 */
1131				if (*q == 'c') {
1132					warnx("Assuming 'g' for 'c' in flags for line:\n%s",
1133					    errline);
1134					warnx("The 'c' flag will eventually mean 'CREATE'");
1135					working->flags |= CE_GLOB;
1136					break;
1137				}
1138				working->flags |= CE_CREATE;
1139				break;
1140			case 'g':
1141				working->flags |= CE_GLOB;
1142				break;
1143			case 'j':
1144				working->flags |= CE_BZCOMPACT;
1145				break;
1146			case 'n':
1147				working->flags |= CE_NOSIGNAL;
1148				break;
1149			case 'u':
1150				working->flags |= CE_SIGNALGROUP;
1151				break;
1152			case 'w':
1153				working->flags |= CE_COMPACTWAIT;
1154				break;
1155			case 'z':
1156				working->flags |= CE_COMPACT;
1157				break;
1158			case '-':
1159				break;
1160			case 'f':	/* Used by OpenBSD for "CE_FOLLOW" */
1161			case 'm':	/* Used by OpenBSD for "CE_MONITOR" */
1162			case 'p':	/* Used by NetBSD  for "CE_PLAIN0" */
1163			default:
1164				errx(1, "illegal flag in config file -- %c",
1165				    *q);
1166			}
1167		}
1168
1169		if (eol)
1170			q = NULL;
1171		else {
1172			q = parse = sob(++parse);	/* Optional field */
1173			parse = son(parse);
1174			if (!*parse)
1175				eol = 1;
1176			*parse = '\0';
1177		}
1178
1179		working->pid_file = NULL;
1180		if (q && *q) {
1181			if (*q == '/')
1182				working->pid_file = strdup(q);
1183			else if (isdigit(*q))
1184				goto got_sig;
1185			else
1186				errx(1,
1187			"illegal pid file or signal number in config file:\n%s",
1188				    errline);
1189		}
1190		if (eol)
1191			q = NULL;
1192		else {
1193			q = parse = sob(++parse);	/* Optional field */
1194			*(parse = son(parse)) = '\0';
1195		}
1196
1197		working->sig = SIGHUP;
1198		if (q && *q) {
1199			if (isdigit(*q)) {
1200		got_sig:
1201				working->sig = atoi(q);
1202			} else {
1203		err_sig:
1204				errx(1,
1205				    "illegal signal number in config file:\n%s",
1206				    errline);
1207			}
1208			if (working->sig < 1 || working->sig >= NSIG)
1209				goto err_sig;
1210		}
1211
1212		/*
1213		 * Finish figuring out what pid-file to use (if any) in
1214		 * later processing if this logfile needs to be rotated.
1215		 */
1216		if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) {
1217			/*
1218			 * This config-entry specified 'n' for nosignal,
1219			 * see if it also specified an explicit pid_file.
1220			 * This would be a pretty pointless combination.
1221			 */
1222			if (working->pid_file != NULL) {
1223				warnx("Ignoring '%s' because flag 'n' was specified in line:\n%s",
1224				    working->pid_file, errline);
1225				free(working->pid_file);
1226				working->pid_file = NULL;
1227			}
1228		} else if (working->pid_file == NULL) {
1229			/*
1230			 * This entry did not specify the 'n' flag, which
1231			 * means it should signal syslogd unless it had
1232			 * specified some other pid-file (and obviously the
1233			 * syslog pid-file will not be for a process-group).
1234			 * Also, we should only try to notify syslog if we
1235			 * are root.
1236			 */
1237			if (working->flags & CE_SIGNALGROUP) {
1238				warnx("Ignoring flag 'U' in line:\n%s",
1239				    errline);
1240				working->flags &= ~CE_SIGNALGROUP;
1241			}
1242			if (needroot)
1243				working->pid_file = strdup(_PATH_SYSLOGPID);
1244		}
1245
1246		/*
1247		 * Add this entry to the appropriate list of entries, unless
1248		 * it was some kind of special entry (eg: <default>).
1249		 */
1250		if (special) {
1251			;			/* Do not add to any list */
1252		} else if (working->flags & CE_GLOB) {
1253			if (!*glob_p)
1254				*glob_p = working;
1255			else
1256				lastglob->next = working;
1257			lastglob = working;
1258		} else {
1259			if (!*work_p)
1260				*work_p = working;
1261			else
1262				lastwork->next = working;
1263			lastwork = working;
1264		}
1265
1266		free(errline);
1267		errline = NULL;
1268	}
1269}
1270
1271static char *
1272missing_field(char *p, char *errline)
1273{
1274
1275	if (!p || !*p)
1276		errx(1, "missing field in config file:\n%s", errline);
1277	return (p);
1278}
1279
1280static void
1281dotrim(const struct conf_entry *ent)
1282{
1283	char dirpart[MAXPATHLEN], namepart[MAXPATHLEN];
1284	char file1[MAXPATHLEN], file2[MAXPATHLEN];
1285	char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN];
1286	char jfile1[MAXPATHLEN];
1287	int flags, notified, need_notification, numlogs_c;
1288	struct stat st;
1289
1290	flags = ent->flags;
1291
1292	if (archtodir) {
1293		char *p;
1294
1295		/* build complete name of archive directory into dirpart */
1296		if (*archdirname == '/') {	/* absolute */
1297			strlcpy(dirpart, archdirname, sizeof(dirpart));
1298		} else {	/* relative */
1299			/* get directory part of logfile */
1300			strlcpy(dirpart, ent->log, sizeof(dirpart));
1301			if ((p = rindex(dirpart, '/')) == NULL)
1302				dirpart[0] = '\0';
1303			else
1304				*(p + 1) = '\0';
1305			strlcat(dirpart, archdirname, sizeof(dirpart));
1306		}
1307
1308		/* check if archive directory exists, if not, create it */
1309		if (lstat(dirpart, &st))
1310			createdir(ent, dirpart);
1311
1312		/* get filename part of logfile */
1313		if ((p = rindex(ent->log, '/')) == NULL)
1314			strlcpy(namepart, ent->log, sizeof(namepart));
1315		else
1316			strlcpy(namepart, p + 1, sizeof(namepart));
1317
1318		/* name of oldest log */
1319		(void) snprintf(file1, sizeof(file1), "%s/%s.%d", dirpart,
1320		    namepart, ent->numlogs);
1321		(void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1322		    COMPRESS_POSTFIX);
1323		snprintf(jfile1, sizeof(jfile1), "%s%s", file1,
1324		    BZCOMPRESS_POSTFIX);
1325	} else {
1326		/* name of oldest log */
1327		(void) snprintf(file1, sizeof(file1), "%s.%d", ent->log,
1328		    ent->numlogs);
1329		(void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1330		    COMPRESS_POSTFIX);
1331		snprintf(jfile1, sizeof(jfile1), "%s%s", file1,
1332		    BZCOMPRESS_POSTFIX);
1333	}
1334
1335	if (noaction) {
1336		printf("\trm -f %s\n", file1);
1337		printf("\trm -f %s\n", zfile1);
1338		printf("\trm -f %s\n", jfile1);
1339	} else {
1340		(void) unlink(file1);
1341		(void) unlink(zfile1);
1342		(void) unlink(jfile1);
1343	}
1344
1345	/* Move down log files */
1346	numlogs_c = ent->numlogs;		/* copy for countdown */
1347	while (numlogs_c--) {
1348
1349		(void) strlcpy(file2, file1, sizeof(file2));
1350
1351		if (archtodir)
1352			(void) snprintf(file1, sizeof(file1), "%s/%s.%d",
1353			    dirpart, namepart, numlogs_c);
1354		else
1355			(void) snprintf(file1, sizeof(file1), "%s.%d",
1356			    ent->log, numlogs_c);
1357
1358		(void) strlcpy(zfile1, file1, sizeof(zfile1));
1359		(void) strlcpy(zfile2, file2, sizeof(zfile2));
1360		if (lstat(file1, &st)) {
1361			(void) strlcat(zfile1, COMPRESS_POSTFIX,
1362			    sizeof(zfile1));
1363			(void) strlcat(zfile2, COMPRESS_POSTFIX,
1364			    sizeof(zfile2));
1365			if (lstat(zfile1, &st)) {
1366				strlcpy(zfile1, file1, sizeof(zfile1));
1367				strlcpy(zfile2, file2, sizeof(zfile2));
1368				strlcat(zfile1, BZCOMPRESS_POSTFIX,
1369				    sizeof(zfile1));
1370				strlcat(zfile2, BZCOMPRESS_POSTFIX,
1371				    sizeof(zfile2));
1372				if (lstat(zfile1, &st))
1373					continue;
1374			}
1375		}
1376		if (noaction) {
1377			printf("\tmv %s %s\n", zfile1, zfile2);
1378			printf("\tchmod %o %s\n", ent->permissions, zfile2);
1379			if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
1380				printf("\tchown %u:%u %s\n",
1381				    ent->uid, ent->gid, zfile2);
1382		} else {
1383			(void) rename(zfile1, zfile2);
1384			if (chmod(zfile2, ent->permissions))
1385				warn("can't chmod %s", file2);
1386			if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
1387				if (chown(zfile2, ent->uid, ent->gid))
1388					warn("can't chown %s", zfile2);
1389		}
1390	}
1391
1392	if (ent->numlogs > 0) {
1393		if (noaction) {
1394			/*
1395			 * Note that savelog() may succeed with using link()
1396			 * for the archtodir case, but there is no good way
1397			 * of knowing if it will when doing "noaction", so
1398			 * here we claim that it will have to do a copy...
1399			 */
1400			if (archtodir)
1401				printf("\tcp %s %s\n", ent->log, file1);
1402			else
1403				printf("\tln %s %s\n", ent->log, file1);
1404			printf("\tchmod %o %s\n", ent->permissions, file1);
1405			if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
1406				printf("\tchown %u:%u %s\n", ent->uid,
1407				    ent->gid, file1);
1408 		} else {
1409			if (!(flags & CE_BINARY)) {
1410				/* Report the trimming to the old log */
1411				log_trim(ent->log, ent);
1412			}
1413			savelog(ent->log, file1);
1414			if (chmod(file1, ent->permissions))
1415				warn("can't chmod %s", file1);
1416			if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
1417				if (chown(file1, ent->uid, ent->gid))
1418					warn("can't chown %s", file1);
1419		}
1420	}
1421
1422	/* Create the new log file and move it into place */
1423	if (noaction)
1424		printf("Start new log...\n");
1425	createlog(ent);
1426
1427	/*
1428	 * Find out if there is a process to signal.  If nosignal (-s) was
1429	 * specified, then do not signal any process.  Note that nosignal
1430	 * will trigger a warning message if the rotated logfile needs to
1431	 * be compressed, *unless* -R was specified.  This is because there
1432	 * presumably still are process(es) writing to the old logfile, but
1433	 * we assume that a -sR request comes from a process which writes
1434	 * to the logfile, and as such, that process has already made sure
1435	 * that the logfile is not presently in use.
1436	 */
1437	need_notification = notified = 0;
1438	if (ent->pid_file != NULL) {
1439		need_notification = 1;
1440		if (!nosignal)
1441			notified = send_signal(ent);	/* the normal case! */
1442		else if (rotatereq)
1443			need_notification = 0;
1444	}
1445
1446	if ((flags & CE_COMPACT) || (flags & CE_BZCOMPACT)) {
1447		if (need_notification && !notified)
1448			warnx(
1449			    "log %s.0 not compressed because daemon(s) not notified",
1450			    ent->log);
1451		else if (noaction)
1452			if (flags & CE_COMPACT)
1453				printf("\tgzip %s.0\n", ent->log);
1454			else
1455				printf("\tbzip2 %s.0\n", ent->log);
1456		else {
1457			if (notified) {
1458				if (verbose)
1459					printf("small pause to allow daemon(s) to close log\n");
1460				sleep(10);
1461			}
1462			if (archtodir) {
1463				(void) snprintf(file1, sizeof(file1), "%s/%s",
1464				    dirpart, namepart);
1465				if (flags & CE_COMPACT)
1466					compress_log(file1,
1467					    flags & CE_COMPACTWAIT);
1468				else if (flags & CE_BZCOMPACT)
1469					bzcompress_log(file1,
1470					    flags & CE_COMPACTWAIT);
1471			} else {
1472				if (flags & CE_COMPACT)
1473					compress_log(ent->log,
1474					    flags & CE_COMPACTWAIT);
1475				else if (flags & CE_BZCOMPACT)
1476					bzcompress_log(ent->log,
1477					    flags & CE_COMPACTWAIT);
1478			}
1479		}
1480	}
1481}
1482
1483/* Log the fact that the logs were turned over */
1484static int
1485log_trim(const char *logname, const struct conf_entry *log_ent)
1486{
1487	FILE *f;
1488	const char *xtra;
1489
1490	if ((f = fopen(logname, "a")) == NULL)
1491		return (-1);
1492	xtra = "";
1493	if (log_ent->def_cfg)
1494		xtra = " using <default> rule";
1495	if (log_ent->firstcreate)
1496		fprintf(f, "%s %s newsyslog[%d]: logfile first created%s\n",
1497		    daytime, hostname, (int) getpid(), xtra);
1498	else if (log_ent->r_reason != NULL)
1499		fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s%s\n",
1500		    daytime, hostname, (int) getpid(), log_ent->r_reason, xtra);
1501	else
1502		fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s\n",
1503		    daytime, hostname, (int) getpid(), xtra);
1504	if (fclose(f) == EOF)
1505		err(1, "log_trim: fclose");
1506	return (0);
1507}
1508
1509/* Fork of gzip to compress the old log file */
1510static void
1511compress_log(char *logname, int dowait)
1512{
1513	pid_t pid;
1514	char tmp[MAXPATHLEN];
1515
1516	while (dowait && (wait(NULL) > 0 || errno == EINTR))
1517		;
1518	(void) snprintf(tmp, sizeof(tmp), "%s.0", logname);
1519	pid = fork();
1520	if (pid < 0)
1521		err(1, "gzip fork");
1522	else if (!pid) {
1523		(void) execl(_PATH_GZIP, _PATH_GZIP, "-f", tmp, (char *)0);
1524		err(1, _PATH_GZIP);
1525	}
1526}
1527
1528/* Fork of bzip2 to compress the old log file */
1529static void
1530bzcompress_log(char *logname, int dowait)
1531{
1532	pid_t pid;
1533	char tmp[MAXPATHLEN];
1534
1535	while (dowait && (wait(NULL) > 0 || errno == EINTR))
1536		;
1537	snprintf(tmp, sizeof(tmp), "%s.0", logname);
1538	pid = fork();
1539	if (pid < 0)
1540		err(1, "bzip2 fork");
1541	else if (!pid) {
1542		execl(_PATH_BZIP2, _PATH_BZIP2, "-f", tmp, (char *)0);
1543		err(1, _PATH_BZIP2);
1544	}
1545}
1546
1547/* Return size in kilobytes of a file */
1548static int
1549sizefile(char *file)
1550{
1551	struct stat sb;
1552
1553	if (stat(file, &sb) < 0)
1554		return (-1);
1555	return (kbytes(dbtob(sb.st_blocks)));
1556}
1557
1558/* Return the age of old log file (file.0) */
1559static int
1560age_old_log(char *file)
1561{
1562	struct stat sb;
1563	char *endp;
1564	char tmp[MAXPATHLEN + sizeof(".0") + sizeof(COMPRESS_POSTFIX) +
1565		sizeof(BZCOMPRESS_POSTFIX) + 1];
1566
1567	if (archtodir) {
1568		char *p;
1569
1570		/* build name of archive directory into tmp */
1571		if (*archdirname == '/') {	/* absolute */
1572			strlcpy(tmp, archdirname, sizeof(tmp));
1573		} else {	/* relative */
1574			/* get directory part of logfile */
1575			strlcpy(tmp, file, sizeof(tmp));
1576			if ((p = rindex(tmp, '/')) == NULL)
1577				tmp[0] = '\0';
1578			else
1579				*(p + 1) = '\0';
1580			strlcat(tmp, archdirname, sizeof(tmp));
1581		}
1582
1583		strlcat(tmp, "/", sizeof(tmp));
1584
1585		/* get filename part of logfile */
1586		if ((p = rindex(file, '/')) == NULL)
1587			strlcat(tmp, file, sizeof(tmp));
1588		else
1589			strlcat(tmp, p + 1, sizeof(tmp));
1590	} else {
1591		(void) strlcpy(tmp, file, sizeof(tmp));
1592	}
1593
1594	strlcat(tmp, ".0", sizeof(tmp));
1595	if (stat(tmp, &sb) < 0) {
1596		/*
1597		 * A plain '.0' file does not exist.  Try again, first
1598		 * with the added suffix of '.gz', then with an added
1599		 * suffix of '.bz2' instead of '.gz'.
1600		 */
1601		endp = strchr(tmp, '\0');
1602		strlcat(tmp, COMPRESS_POSTFIX, sizeof(tmp));
1603		if (stat(tmp, &sb) < 0) {
1604			*endp = '\0';		/* Remove .gz */
1605			strlcat(tmp, BZCOMPRESS_POSTFIX, sizeof(tmp));
1606			if (stat(tmp, &sb) < 0)
1607				return (-1);
1608		}
1609	}
1610	return ((int)(ptimeget_secs(timenow) - sb.st_mtime + 1800) / 3600);
1611}
1612
1613/* Skip Over Blanks */
1614static char *
1615sob(char *p)
1616{
1617	while (p && *p && isspace(*p))
1618		p++;
1619	return (p);
1620}
1621
1622/* Skip Over Non-Blanks */
1623static char *
1624son(char *p)
1625{
1626	while (p && *p && !isspace(*p))
1627		p++;
1628	return (p);
1629}
1630
1631/* Check if string is actually a number */
1632static int
1633isnumberstr(const char *string)
1634{
1635	while (*string) {
1636		if (!isdigitch(*string++))
1637			return (0);
1638	}
1639	return (1);
1640}
1641
1642/*
1643 * Save the active log file under a new name.  A link to the new name
1644 * is the quick-and-easy way to do this.  If that fails (which it will
1645 * if the destination is on another partition), then make a copy of
1646 * the file to the new location.
1647 */
1648static void
1649savelog(char *from, char *to)
1650{
1651	FILE *src, *dst;
1652	int c, res;
1653
1654	res = link(from, to);
1655	if (res == 0)
1656		return;
1657
1658	if ((src = fopen(from, "r")) == NULL)
1659		err(1, "can't fopen %s for reading", from);
1660	if ((dst = fopen(to, "w")) == NULL)
1661		err(1, "can't fopen %s for writing", to);
1662
1663	while ((c = getc(src)) != EOF) {
1664		if ((putc(c, dst)) == EOF)
1665			err(1, "error writing to %s", to);
1666	}
1667
1668	if (ferror(src))
1669		err(1, "error reading from %s", from);
1670	if ((fclose(src)) != 0)
1671		err(1, "can't fclose %s", to);
1672	if ((fclose(dst)) != 0)
1673		err(1, "can't fclose %s", from);
1674}
1675
1676/* create one or more directory components of a path */
1677static void
1678createdir(const struct conf_entry *ent, char *dirpart)
1679{
1680	int res;
1681	char *s, *d;
1682	char mkdirpath[MAXPATHLEN];
1683	struct stat st;
1684
1685	s = dirpart;
1686	d = mkdirpath;
1687
1688	for (;;) {
1689		*d++ = *s++;
1690		if (*s != '/' && *s != '\0')
1691			continue;
1692		*d = '\0';
1693		res = lstat(mkdirpath, &st);
1694		if (res != 0) {
1695			if (noaction) {
1696				printf("\tmkdir %s\n", mkdirpath);
1697			} else {
1698				res = mkdir(mkdirpath, 0755);
1699				if (res != 0)
1700					err(1, "Error on mkdir(\"%s\") for -a",
1701					    mkdirpath);
1702			}
1703		}
1704		if (*s == '\0')
1705			break;
1706	}
1707	if (verbose) {
1708		if (ent->firstcreate)
1709			printf("Created directory '%s' for new %s\n",
1710			    dirpart, ent->log);
1711		else
1712			printf("Created directory '%s' for -a\n", dirpart);
1713	}
1714}
1715
1716/*
1717 * Create a new log file, destroying any currently-existing version
1718 * of the log file in the process.  If the caller wants a backup copy
1719 * of the file to exist, they should call 'link(logfile,logbackup)'
1720 * before calling this routine.
1721 */
1722void
1723createlog(const struct conf_entry *ent)
1724{
1725	int fd, failed;
1726	struct stat st;
1727	char *realfile, *slash, tempfile[MAXPATHLEN];
1728
1729	fd = -1;
1730	realfile = ent->log;
1731
1732	/*
1733	 * If this log file is being created for the first time (-C option),
1734	 * then it may also be true that the parent directory does not exist
1735	 * yet.  Check, and create that directory if it is missing.
1736	 */
1737	if (ent->firstcreate) {
1738		strlcpy(tempfile, realfile, sizeof(tempfile));
1739		slash = strrchr(tempfile, '/');
1740		if (slash != NULL) {
1741			*slash = '\0';
1742			failed = lstat(tempfile, &st);
1743			if (failed && errno != ENOENT)
1744				err(1, "Error on lstat(%s)", tempfile);
1745			if (failed)
1746				createdir(ent, tempfile);
1747			else if (!S_ISDIR(st.st_mode))
1748				errx(1, "%s exists but is not a directory",
1749				    tempfile);
1750		}
1751	}
1752
1753	/*
1754	 * First create an unused filename, so it can be chown'ed and
1755	 * chmod'ed before it is moved into the real location.  mkstemp
1756	 * will create the file mode=600 & owned by us.  Note that all
1757	 * temp files will have a suffix of '.z<something>'.
1758	 */
1759	strlcpy(tempfile, realfile, sizeof(tempfile));
1760	strlcat(tempfile, ".zXXXXXX", sizeof(tempfile));
1761	if (noaction)
1762		printf("\tmktemp %s\n", tempfile);
1763	else {
1764		fd = mkstemp(tempfile);
1765		if (fd < 0)
1766			err(1, "can't mkstemp logfile %s", tempfile);
1767
1768		/*
1769		 * Add status message to what will become the new log file.
1770		 */
1771		if (!(ent->flags & CE_BINARY)) {
1772			if (log_trim(tempfile, ent))
1773				err(1, "can't add status message to log");
1774		}
1775	}
1776
1777	/* Change the owner/group, if we are supposed to */
1778	if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
1779		if (noaction)
1780			printf("\tchown %u:%u %s\n", ent->uid, ent->gid,
1781			    tempfile);
1782		else {
1783			failed = fchown(fd, ent->uid, ent->gid);
1784			if (failed)
1785				err(1, "can't fchown temp file %s", tempfile);
1786		}
1787	}
1788
1789	/*
1790	 * Note that if the real logfile still exists, and if the call
1791	 * to rename() fails, then "neither the old file nor the new
1792	 * file shall be changed or created" (to quote the standard).
1793	 * If the call succeeds, then the file will be replaced without
1794	 * any window where some other process might find that the file
1795	 * did not exist.
1796	 * XXX - ? It may be that for some error conditions, we could
1797	 *	retry by first removing the realfile and then renaming.
1798	 */
1799	if (noaction) {
1800		printf("\tchmod %o %s\n", ent->permissions, tempfile);
1801		printf("\tmv %s %s\n", tempfile, realfile);
1802	} else {
1803		failed = fchmod(fd, ent->permissions);
1804		if (failed)
1805			err(1, "can't fchmod temp file '%s'", tempfile);
1806		failed = rename(tempfile, realfile);
1807		if (failed)
1808			err(1, "can't mv %s to %s", tempfile, realfile);
1809	}
1810
1811	if (fd >= 0)
1812		close(fd);
1813}
1814