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