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