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