newsyslog.c revision 210372
1/*-
2 * ------+---------+---------+-------- + --------+---------+---------+---------*
3 * This file includes significant modifications done by:
4 * Copyright (c) 2003, 2004  - Garance Alistair Drosehn <gad@FreeBSD.org>.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 *   1. Redistributions of source code must retain the above copyright
11 *      notice, this list of conditions and the following disclaimer.
12 *   2. Redistributions in binary form must reproduce the above copyright
13 *      notice, this list of conditions and the following disclaimer in the
14 *      documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 *
28 * ------+---------+---------+-------- + --------+---------+---------+---------*
29 */
30
31/*
32 * This file contains changes from the Open Software Foundation.
33 */
34
35/*
36 * Copyright 1988, 1989 by the Massachusetts Institute of Technology
37 *
38 * Permission to use, copy, modify, and distribute this software and its
39 * documentation for any purpose and without fee is hereby granted, provided
40 * that the above copyright notice appear in all copies and that both that
41 * copyright notice and this permission notice appear in supporting
42 * documentation, and that the names of M.I.T. and the M.I.T. S.I.P.B. not be
43 * used in advertising or publicity pertaining to distribution of the
44 * software without specific, written prior permission. M.I.T. and the M.I.T.
45 * S.I.P.B. make no representations about the suitability of this software
46 * for any purpose.  It is provided "as is" without express or implied
47 * warranty.
48 *
49 */
50
51/*
52 * newsyslog - roll over selected logs at the appropriate time, keeping the a
53 * specified number of backup files around.
54 */
55
56#include <sys/cdefs.h>
57__FBSDID("$FreeBSD: head/usr.sbin/newsyslog/newsyslog.c 210372 2010-07-22 11:23:18Z simon $");
58
59#define	OSF
60#ifndef COMPRESS_POSTFIX
61#define	COMPRESS_POSTFIX ".gz"
62#endif
63#ifndef	BZCOMPRESS_POSTFIX
64#define	BZCOMPRESS_POSTFIX ".bz2"
65#endif
66
67#include <sys/param.h>
68#include <sys/queue.h>
69#include <sys/stat.h>
70#include <sys/wait.h>
71
72#include <assert.h>
73#include <ctype.h>
74#include <err.h>
75#include <errno.h>
76#include <dirent.h>
77#include <fcntl.h>
78#include <fnmatch.h>
79#include <glob.h>
80#include <grp.h>
81#include <paths.h>
82#include <pwd.h>
83#include <signal.h>
84#include <stdio.h>
85#include <libgen.h>
86#include <stdlib.h>
87#include <string.h>
88#include <time.h>
89#include <unistd.h>
90
91#include "pathnames.h"
92#include "extern.h"
93
94/*
95 * Bit-values for the 'flags' parsed from a config-file entry.
96 */
97#define	CE_COMPACT	0x0001	/* Compact the archived log files with gzip. */
98#define	CE_BZCOMPACT	0x0002	/* Compact the archived log files with bzip2. */
99#define	CE_BINARY	0x0008	/* Logfile is in binary, do not add status */
100				/*    messages to logfile(s) when rotating. */
101#define	CE_NOSIGNAL	0x0010	/* There is no process to signal when */
102				/*    trimming this file. */
103#define	CE_TRIMAT	0x0020	/* trim file at a specific time. */
104#define	CE_GLOB		0x0040	/* name of the log is file name pattern. */
105#define	CE_SIGNALGROUP	0x0080	/* Signal a process-group instead of a single */
106				/*    process when trimming this file. */
107#define	CE_CREATE	0x0100	/* Create the log file if it does not exist. */
108#define	CE_NODUMP	0x0200	/* Set 'nodump' on newly created log file. */
109
110#define	MIN_PID         5	/* Don't touch pids lower than this */
111#define	MAX_PID		99999	/* was lower, see /usr/include/sys/proc.h */
112
113#define	kbytes(size)  (((size) + 1023) >> 10)
114
115#define	DEFAULT_MARKER	"<default>"
116#define	DEBUG_MARKER	"<debug>"
117#define	INCLUDE_MARKER	"<include>"
118#define	DEFAULT_TIMEFNAME_FMT	"%Y%m%dT%H%M%S"
119
120#define	MAX_OLDLOGS 65536	/* Default maximum number of old logfiles */
121
122struct conf_entry {
123	STAILQ_ENTRY(conf_entry) cf_nextp;
124	char *log;		/* Name of the log */
125	char *pid_file;		/* PID file */
126	char *r_reason;		/* The reason this file is being rotated */
127	int firstcreate;	/* Creating log for the first time (-C). */
128	int rotate;		/* Non-zero if this file should be rotated */
129	int fsize;		/* size found for the log file */
130	uid_t uid;		/* Owner of log */
131	gid_t gid;		/* Group of log */
132	int numlogs;		/* Number of logs to keep */
133	int trsize;		/* Size cutoff to trigger trimming the log */
134	int hours;		/* Hours between log trimming */
135	struct ptime_data *trim_at;	/* Specific time to do trimming */
136	unsigned int permissions;	/* File permissions on the log */
137	int flags;		/* CE_COMPACT, CE_BZCOMPACT, CE_BINARY */
138	int sig;		/* Signal to send */
139	int def_cfg;		/* Using the <default> rule for this file */
140};
141
142struct sigwork_entry {
143	SLIST_ENTRY(sigwork_entry) sw_nextp;
144	int	 sw_signum;		/* the signal to send */
145	int	 sw_pidok;		/* true if pid value is valid */
146	pid_t	 sw_pid;		/* the process id from the PID file */
147	const char *sw_pidtype;		/* "daemon" or "process group" */
148	char	 sw_fname[1];		/* file the PID was read from */
149};
150
151struct zipwork_entry {
152	SLIST_ENTRY(zipwork_entry) zw_nextp;
153	const struct conf_entry *zw_conf;	/* for chown/perm/flag info */
154	const struct sigwork_entry *zw_swork;	/* to know success of signal */
155	int	 zw_fsize;		/* size of the file to compress */
156	char	 zw_fname[1];		/* the file to compress */
157};
158
159struct include_entry {
160	STAILQ_ENTRY(include_entry) inc_nextp;
161	const char *file;	/* Name of file to process */
162};
163
164struct oldlog_entry {
165	char *fname;		/* Filename of the log file */
166	time_t t;		/* Parses timestamp of the logfile */
167};
168
169typedef enum {
170	FREE_ENT, KEEP_ENT
171}	fk_entry;
172
173STAILQ_HEAD(cflist, conf_entry);
174SLIST_HEAD(swlisthead, sigwork_entry) swhead = SLIST_HEAD_INITIALIZER(swhead);
175SLIST_HEAD(zwlisthead, zipwork_entry) zwhead = SLIST_HEAD_INITIALIZER(zwhead);
176STAILQ_HEAD(ilist, include_entry);
177
178int dbg_at_times;		/* -D Show details of 'trim_at' code */
179
180int archtodir = 0;		/* Archive old logfiles to other directory */
181int createlogs;			/* Create (non-GLOB) logfiles which do not */
182				/*    already exist.  1=='for entries with */
183				/*    C flag', 2=='for all entries'. */
184int verbose = 0;		/* Print out what's going on */
185int needroot = 1;		/* Root privs are necessary */
186int noaction = 0;		/* Don't do anything, just show it */
187int norotate = 0;		/* Don't rotate */
188int nosignal;			/* Do not send any signals */
189int enforcepid = 0;		/* If PID file does not exist or empty, do nothing */
190int force = 0;			/* Force the trim no matter what */
191int rotatereq = 0;		/* -R = Always rotate the file(s) as given */
192				/*    on the command (this also requires   */
193				/*    that a list of files *are* given on  */
194				/*    the run command). */
195char *requestor;		/* The name given on a -R request */
196char *timefnamefmt = NULL;	/* Use time based filenames instead of .0 etc */
197char *archdirname;		/* Directory path to old logfiles archive */
198char *destdir = NULL;		/* Directory to treat at root for logs */
199const char *conf;		/* Configuration file to use */
200
201struct ptime_data *dbg_timenow;	/* A "timenow" value set via -D option */
202struct ptime_data *timenow;	/* The time to use for checking at-fields */
203
204#define	DAYTIME_LEN	16
205char daytime[DAYTIME_LEN];	/* The current time in human readable form,
206				 * used for rotation-tracking messages. */
207char hostname[MAXHOSTNAMELEN];	/* hostname */
208
209static struct cflist *get_worklist(char **files);
210static void parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
211		    struct conf_entry *defconf_p, struct ilist *inclist);
212static void add_to_queue(const char *fname, struct ilist *inclist);
213static char *sob(char *p);
214static char *son(char *p);
215static int isnumberstr(const char *);
216static int isglobstr(const char *);
217static char *missing_field(char *p, char *errline);
218static void	 change_attrs(const char *, const struct conf_entry *);
219static fk_entry	 do_entry(struct conf_entry *);
220static fk_entry	 do_rotate(const struct conf_entry *);
221static void	 do_sigwork(struct sigwork_entry *);
222static void	 do_zipwork(struct zipwork_entry *);
223static struct sigwork_entry *
224		 save_sigwork(const struct conf_entry *);
225static struct zipwork_entry *
226		 save_zipwork(const struct conf_entry *, const struct
227		    sigwork_entry *, int, const char *);
228static void	 set_swpid(struct sigwork_entry *, const struct conf_entry *);
229static int	 sizefile(const char *);
230static void expand_globs(struct cflist *work_p, struct cflist *glob_p);
231static void free_clist(struct cflist *list);
232static void free_entry(struct conf_entry *ent);
233static struct conf_entry *init_entry(const char *fname,
234		struct conf_entry *src_entry);
235static void parse_args(int argc, char **argv);
236static int parse_doption(const char *doption);
237static void usage(void);
238static int log_trim(const char *logname, const struct conf_entry *log_ent);
239static int age_old_log(char *file);
240static void savelog(char *from, char *to);
241static void createdir(const struct conf_entry *ent, char *dirpart);
242static void createlog(const struct conf_entry *ent);
243
244/*
245 * All the following take a parameter of 'int', but expect values in the
246 * range of unsigned char.  Define wrappers which take values of type 'char',
247 * whether signed or unsigned, and ensure they end up in the right range.
248 */
249#define	isdigitch(Anychar) isdigit((u_char)(Anychar))
250#define	isprintch(Anychar) isprint((u_char)(Anychar))
251#define	isspacech(Anychar) isspace((u_char)(Anychar))
252#define	tolowerch(Anychar) tolower((u_char)(Anychar))
253
254int
255main(int argc, char **argv)
256{
257	struct cflist *worklist;
258	struct conf_entry *p;
259	struct sigwork_entry *stmp;
260	struct zipwork_entry *ztmp;
261
262	SLIST_INIT(&swhead);
263	SLIST_INIT(&zwhead);
264
265	parse_args(argc, argv);
266	argc -= optind;
267	argv += optind;
268
269	if (needroot && getuid() && geteuid())
270		errx(1, "must have root privs");
271	worklist = get_worklist(argv);
272
273	/*
274	 * Rotate all the files which need to be rotated.  Note that
275	 * some users have *hundreds* of entries in newsyslog.conf!
276	 */
277	while (!STAILQ_EMPTY(worklist)) {
278		p = STAILQ_FIRST(worklist);
279		STAILQ_REMOVE_HEAD(worklist, cf_nextp);
280		if (do_entry(p) == FREE_ENT)
281			free_entry(p);
282	}
283
284	/*
285	 * Send signals to any processes which need a signal to tell
286	 * them to close and re-open the log file(s) we have rotated.
287	 * Note that zipwork_entries include pointers to these
288	 * sigwork_entry's, so we can not free the entries here.
289	 */
290	if (!SLIST_EMPTY(&swhead)) {
291		if (noaction || verbose)
292			printf("Signal all daemon process(es)...\n");
293		SLIST_FOREACH(stmp, &swhead, sw_nextp)
294			do_sigwork(stmp);
295		if (noaction)
296			printf("\tsleep 10\n");
297		else {
298			if (verbose)
299				printf("Pause 10 seconds to allow daemon(s)"
300				    " to close log file(s)\n");
301			sleep(10);
302		}
303	}
304	/*
305	 * Compress all files that we're expected to compress, now
306	 * that all processes should have closed the files which
307	 * have been rotated.
308	 */
309	if (!SLIST_EMPTY(&zwhead)) {
310		if (noaction || verbose)
311			printf("Compress all rotated log file(s)...\n");
312		while (!SLIST_EMPTY(&zwhead)) {
313			ztmp = SLIST_FIRST(&zwhead);
314			do_zipwork(ztmp);
315			SLIST_REMOVE_HEAD(&zwhead, zw_nextp);
316			free(ztmp);
317		}
318	}
319	/* Now free all the sigwork entries. */
320	while (!SLIST_EMPTY(&swhead)) {
321		stmp = SLIST_FIRST(&swhead);
322		SLIST_REMOVE_HEAD(&swhead, sw_nextp);
323		free(stmp);
324	}
325
326	while (wait(NULL) > 0 || errno == EINTR)
327		;
328	return (0);
329}
330
331static struct conf_entry *
332init_entry(const char *fname, struct conf_entry *src_entry)
333{
334	struct conf_entry *tempwork;
335
336	if (verbose > 4)
337		printf("\t--> [creating entry for %s]\n", fname);
338
339	tempwork = malloc(sizeof(struct conf_entry));
340	if (tempwork == NULL)
341		err(1, "malloc of conf_entry for %s", fname);
342
343	if (destdir == NULL || fname[0] != '/')
344		tempwork->log = strdup(fname);
345	else
346		asprintf(&tempwork->log, "%s%s", destdir, fname);
347	if (tempwork->log == NULL)
348		err(1, "strdup for %s", fname);
349
350	if (src_entry != NULL) {
351		tempwork->pid_file = NULL;
352		if (src_entry->pid_file)
353			tempwork->pid_file = strdup(src_entry->pid_file);
354		tempwork->r_reason = NULL;
355		tempwork->firstcreate = 0;
356		tempwork->rotate = 0;
357		tempwork->fsize = -1;
358		tempwork->uid = src_entry->uid;
359		tempwork->gid = src_entry->gid;
360		tempwork->numlogs = src_entry->numlogs;
361		tempwork->trsize = src_entry->trsize;
362		tempwork->hours = src_entry->hours;
363		tempwork->trim_at = NULL;
364		if (src_entry->trim_at != NULL)
365			tempwork->trim_at = ptime_init(src_entry->trim_at);
366		tempwork->permissions = src_entry->permissions;
367		tempwork->flags = src_entry->flags;
368		tempwork->sig = src_entry->sig;
369		tempwork->def_cfg = src_entry->def_cfg;
370	} else {
371		/* Initialize as a "do-nothing" entry */
372		tempwork->pid_file = NULL;
373		tempwork->r_reason = NULL;
374		tempwork->firstcreate = 0;
375		tempwork->rotate = 0;
376		tempwork->fsize = -1;
377		tempwork->uid = (uid_t)-1;
378		tempwork->gid = (gid_t)-1;
379		tempwork->numlogs = 1;
380		tempwork->trsize = -1;
381		tempwork->hours = -1;
382		tempwork->trim_at = NULL;
383		tempwork->permissions = 0;
384		tempwork->flags = 0;
385		tempwork->sig = SIGHUP;
386		tempwork->def_cfg = 0;
387	}
388
389	return (tempwork);
390}
391
392static void
393free_entry(struct conf_entry *ent)
394{
395
396	if (ent == NULL)
397		return;
398
399	if (ent->log != NULL) {
400		if (verbose > 4)
401			printf("\t--> [freeing entry for %s]\n", ent->log);
402		free(ent->log);
403		ent->log = NULL;
404	}
405
406	if (ent->pid_file != NULL) {
407		free(ent->pid_file);
408		ent->pid_file = NULL;
409	}
410
411	if (ent->r_reason != NULL) {
412		free(ent->r_reason);
413		ent->r_reason = NULL;
414	}
415
416	if (ent->trim_at != NULL) {
417		ptime_free(ent->trim_at);
418		ent->trim_at = NULL;
419	}
420
421	free(ent);
422}
423
424static void
425free_clist(struct cflist *list)
426{
427	struct conf_entry *ent;
428
429	while (!STAILQ_EMPTY(list)) {
430		ent = STAILQ_FIRST(list);
431		STAILQ_REMOVE_HEAD(list, cf_nextp);
432		free_entry(ent);
433	}
434
435	free(list);
436	list = NULL;
437}
438
439static fk_entry
440do_entry(struct conf_entry * ent)
441{
442#define	REASON_MAX	80
443	int modtime;
444	fk_entry free_or_keep;
445	double diffsecs;
446	char temp_reason[REASON_MAX];
447
448	free_or_keep = FREE_ENT;
449	if (verbose) {
450		if (ent->flags & CE_COMPACT)
451			printf("%s <%dZ>: ", ent->log, ent->numlogs);
452		else if (ent->flags & CE_BZCOMPACT)
453			printf("%s <%dJ>: ", ent->log, ent->numlogs);
454		else
455			printf("%s <%d>: ", ent->log, ent->numlogs);
456	}
457	ent->fsize = sizefile(ent->log);
458	modtime = age_old_log(ent->log);
459	ent->rotate = 0;
460	ent->firstcreate = 0;
461	if (ent->fsize < 0) {
462		/*
463		 * If either the C flag or the -C option was specified,
464		 * and if we won't be creating the file, then have the
465		 * verbose message include a hint as to why the file
466		 * will not be created.
467		 */
468		temp_reason[0] = '\0';
469		if (createlogs > 1)
470			ent->firstcreate = 1;
471		else if ((ent->flags & CE_CREATE) && createlogs)
472			ent->firstcreate = 1;
473		else if (ent->flags & CE_CREATE)
474			strlcpy(temp_reason, " (no -C option)", REASON_MAX);
475		else if (createlogs)
476			strlcpy(temp_reason, " (no C flag)", REASON_MAX);
477
478		if (ent->firstcreate) {
479			if (verbose)
480				printf("does not exist -> will create.\n");
481			createlog(ent);
482		} else if (verbose) {
483			printf("does not exist, skipped%s.\n", temp_reason);
484		}
485	} else {
486		if (ent->flags & CE_TRIMAT && !force && !rotatereq) {
487			diffsecs = ptimeget_diff(timenow, ent->trim_at);
488			if (diffsecs < 0.0) {
489				/* trim_at is some time in the future. */
490				if (verbose) {
491					ptime_adjust4dst(ent->trim_at,
492					    timenow);
493					printf("--> will trim at %s",
494					    ptimeget_ctime(ent->trim_at));
495				}
496				return (free_or_keep);
497			} else if (diffsecs >= 3600.0) {
498				/*
499				 * trim_at is more than an hour in the past,
500				 * so find the next valid trim_at time, and
501				 * tell the user what that will be.
502				 */
503				if (verbose && dbg_at_times)
504					printf("\n\t--> prev trim at %s\t",
505					    ptimeget_ctime(ent->trim_at));
506				if (verbose) {
507					ptimeset_nxtime(ent->trim_at);
508					printf("--> will trim at %s",
509					    ptimeget_ctime(ent->trim_at));
510				}
511				return (free_or_keep);
512			} else if (verbose && noaction && dbg_at_times) {
513				/*
514				 * If we are just debugging at-times, then
515				 * a detailed message is helpful.  Also
516				 * skip "doing" any commands, since they
517				 * would all be turned off by no-action.
518				 */
519				printf("\n\t--> timematch at %s",
520				    ptimeget_ctime(ent->trim_at));
521				return (free_or_keep);
522			} else if (verbose && ent->hours <= 0) {
523				printf("--> time is up\n");
524			}
525		}
526		if (verbose && (ent->trsize > 0))
527			printf("size (Kb): %d [%d] ", ent->fsize, ent->trsize);
528		if (verbose && (ent->hours > 0))
529			printf(" age (hr): %d [%d] ", modtime, ent->hours);
530
531		/*
532		 * Figure out if this logfile needs to be rotated.
533		 */
534		temp_reason[0] = '\0';
535		if (rotatereq) {
536			ent->rotate = 1;
537			snprintf(temp_reason, REASON_MAX, " due to -R from %s",
538			    requestor);
539		} else if (force) {
540			ent->rotate = 1;
541			snprintf(temp_reason, REASON_MAX, " due to -F request");
542		} else if ((ent->trsize > 0) && (ent->fsize >= ent->trsize)) {
543			ent->rotate = 1;
544			snprintf(temp_reason, REASON_MAX, " due to size>%dK",
545			    ent->trsize);
546		} else if (ent->hours <= 0 && (ent->flags & CE_TRIMAT)) {
547			ent->rotate = 1;
548		} else if ((ent->hours > 0) && ((modtime >= ent->hours) ||
549		    (modtime < 0))) {
550			ent->rotate = 1;
551		}
552
553		/*
554		 * If the file needs to be rotated, then rotate it.
555		 */
556		if (ent->rotate && !norotate) {
557			if (temp_reason[0] != '\0')
558				ent->r_reason = strdup(temp_reason);
559			if (verbose)
560				printf("--> trimming log....\n");
561			if (noaction && !verbose) {
562				if (ent->flags & CE_COMPACT)
563					printf("%s <%dZ>: trimming\n",
564					    ent->log, ent->numlogs);
565				else if (ent->flags & CE_BZCOMPACT)
566					printf("%s <%dJ>: trimming\n",
567					    ent->log, ent->numlogs);
568				else
569					printf("%s <%d>: trimming\n",
570					    ent->log, ent->numlogs);
571			}
572			free_or_keep = do_rotate(ent);
573		} else {
574			if (verbose)
575				printf("--> skipping\n");
576		}
577	}
578	return (free_or_keep);
579#undef REASON_MAX
580}
581
582static void
583parse_args(int argc, char **argv)
584{
585	int ch;
586	char *p;
587
588	timenow = ptime_init(NULL);
589	ptimeset_time(timenow, time(NULL));
590	strlcpy(daytime, ptimeget_ctime(timenow) + 4, DAYTIME_LEN);
591
592	/* Let's get our hostname */
593	(void)gethostname(hostname, sizeof(hostname));
594
595	/* Truncate domain */
596	if ((p = strchr(hostname, '.')) != NULL)
597		*p = '\0';
598
599	/* Parse command line options. */
600	while ((ch = getopt(argc, argv, "a:d:f:nrst:vCD:FNPR:")) != -1)
601		switch (ch) {
602		case 'a':
603			archtodir++;
604			archdirname = optarg;
605			break;
606		case 'd':
607			destdir = optarg;
608			break;
609		case 'f':
610			conf = optarg;
611			break;
612		case 'n':
613			noaction++;
614			break;
615		case 'r':
616			needroot = 0;
617			break;
618		case 's':
619			nosignal = 1;
620			break;
621		case 't':
622			if (optarg[0] == '\0' ||
623			    strcmp(optarg, "DEFAULT") == 0)
624				timefnamefmt = strdup(DEFAULT_TIMEFNAME_FMT);
625			else
626				timefnamefmt = strdup(optarg);
627			break;
628		case 'v':
629			verbose++;
630			break;
631		case 'C':
632			/* Useful for things like rc.diskless... */
633			createlogs++;
634			break;
635		case 'D':
636			/*
637			 * Set some debugging option.  The specific option
638			 * depends on the value of optarg.  These options
639			 * may come and go without notice or documentation.
640			 */
641			if (parse_doption(optarg))
642				break;
643			usage();
644			/* NOTREACHED */
645		case 'F':
646			force++;
647			break;
648		case 'N':
649			norotate++;
650			break;
651		case 'P':
652			enforcepid++;
653			break;
654		case 'R':
655			rotatereq++;
656			requestor = strdup(optarg);
657			break;
658		case 'm':	/* Used by OpenBSD for "monitor mode" */
659		default:
660			usage();
661			/* NOTREACHED */
662		}
663
664	if (force && norotate) {
665		warnx("Only one of -F and -N may be specified.");
666		usage();
667		/* NOTREACHED */
668	}
669
670	if (rotatereq) {
671		if (optind == argc) {
672			warnx("At least one filename must be given when -R is specified.");
673			usage();
674			/* NOTREACHED */
675		}
676		/* Make sure "requestor" value is safe for a syslog message. */
677		for (p = requestor; *p != '\0'; p++) {
678			if (!isprintch(*p) && (*p != '\t'))
679				*p = '.';
680		}
681	}
682
683	if (dbg_timenow) {
684		/*
685		 * Note that the 'daytime' variable is not changed.
686		 * That is only used in messages that track when a
687		 * logfile is rotated, and if a file *is* rotated,
688		 * then it will still rotated at the "real now" time.
689		 */
690		ptime_free(timenow);
691		timenow = dbg_timenow;
692		fprintf(stderr, "Debug: Running as if TimeNow is %s",
693		    ptimeget_ctime(dbg_timenow));
694	}
695
696}
697
698/*
699 * These debugging options are mainly meant for developer use, such
700 * as writing regression-tests.  They would not be needed by users
701 * during normal operation of newsyslog...
702 */
703static int
704parse_doption(const char *doption)
705{
706	const char TN[] = "TN=";
707	int res;
708
709	if (strncmp(doption, TN, sizeof(TN) - 1) == 0) {
710		/*
711		 * The "TimeNow" debugging option.  This might be off
712		 * by an hour when crossing a timezone change.
713		 */
714		dbg_timenow = ptime_init(NULL);
715		res = ptime_relparse(dbg_timenow, PTM_PARSE_ISO8601,
716		    time(NULL), doption + sizeof(TN) - 1);
717		if (res == -2) {
718			warnx("Non-existent time specified on -D %s", doption);
719			return (0);			/* failure */
720		} else if (res < 0) {
721			warnx("Malformed time given on -D %s", doption);
722			return (0);			/* failure */
723		}
724		return (1);			/* successfully parsed */
725
726	}
727
728	if (strcmp(doption, "ats") == 0) {
729		dbg_at_times++;
730		return (1);			/* successfully parsed */
731	}
732
733	/* XXX - This check could probably be dropped. */
734	if ((strcmp(doption, "neworder") == 0) || (strcmp(doption, "oldorder")
735	    == 0)) {
736		warnx("NOTE: newsyslog always uses 'neworder'.");
737		return (1);			/* successfully parsed */
738	}
739
740	warnx("Unknown -D (debug) option: '%s'", doption);
741	return (0);				/* failure */
742}
743
744static void
745usage(void)
746{
747
748	fprintf(stderr,
749	    "usage: newsyslog [-CFNnrsv] [-a directory] [-d directory] [-f config-file]\n"
750	    "                 [-t timefmt ] [ [-R requestor] filename ... ]\n");
751	exit(1);
752}
753
754/*
755 * Parse a configuration file and return a linked list of all the logs
756 * which should be processed.
757 */
758static struct cflist *
759get_worklist(char **files)
760{
761	FILE *f;
762	char **given;
763	struct cflist *cmdlist, *filelist, *globlist;
764	struct conf_entry *defconf, *dupent, *ent;
765	struct ilist inclist;
766	struct include_entry *inc;
767	int gmatch, fnres;
768
769	defconf = NULL;
770	STAILQ_INIT(&inclist);
771
772	filelist = malloc(sizeof(struct cflist));
773	if (filelist == NULL)
774		err(1, "malloc of filelist");
775	STAILQ_INIT(filelist);
776	globlist = malloc(sizeof(struct cflist));
777	if (globlist == NULL)
778		err(1, "malloc of globlist");
779	STAILQ_INIT(globlist);
780
781	inc = malloc(sizeof(struct include_entry));
782	if (inc == NULL)
783		err(1, "malloc of inc");
784	inc->file = conf;
785	if (inc->file == NULL)
786		inc->file = _PATH_CONF;
787	STAILQ_INSERT_TAIL(&inclist, inc, inc_nextp);
788
789	STAILQ_FOREACH(inc, &inclist, inc_nextp) {
790		if (strcmp(inc->file, "-") != 0)
791			f = fopen(inc->file, "r");
792		else {
793			f = stdin;
794			inc->file = "<stdin>";
795		}
796		if (!f)
797			err(1, "%s", inc->file);
798
799		if (verbose)
800			printf("Processing %s\n", inc->file);
801		parse_file(f, filelist, globlist, defconf, &inclist);
802		(void) fclose(f);
803	}
804
805	/*
806	 * All config-file information has been read in and turned into
807	 * a filelist and a globlist.  If there were no specific files
808	 * given on the run command, then the only thing left to do is to
809	 * call a routine which finds all files matched by the globlist
810	 * and adds them to the filelist.  Then return the worklist.
811	 */
812	if (*files == NULL) {
813		expand_globs(filelist, globlist);
814		free_clist(globlist);
815		if (defconf != NULL)
816			free_entry(defconf);
817		return (filelist);
818		/* NOTREACHED */
819	}
820
821	/*
822	 * If newsyslog was given a specific list of files to process,
823	 * it may be that some of those files were not listed in any
824	 * config file.  Those unlisted files should get the default
825	 * rotation action.  First, create the default-rotation action
826	 * if none was found in a system config file.
827	 */
828	if (defconf == NULL) {
829		defconf = init_entry(DEFAULT_MARKER, NULL);
830		defconf->numlogs = 3;
831		defconf->trsize = 50;
832		defconf->permissions = S_IRUSR|S_IWUSR;
833	}
834
835	/*
836	 * If newsyslog was run with a list of specific filenames,
837	 * then create a new worklist which has only those files in
838	 * it, picking up the rotation-rules for those files from
839	 * the original filelist.
840	 *
841	 * XXX - Note that this will copy multiple rules for a single
842	 *	logfile, if multiple entries are an exact match for
843	 *	that file.  That matches the historic behavior, but do
844	 *	we want to continue to allow it?  If so, it should
845	 *	probably be handled more intelligently.
846	 */
847	cmdlist = malloc(sizeof(struct cflist));
848	if (cmdlist == NULL)
849		err(1, "malloc of cmdlist");
850	STAILQ_INIT(cmdlist);
851
852	for (given = files; *given; ++given) {
853		/*
854		 * First try to find exact-matches for this given file.
855		 */
856		gmatch = 0;
857		STAILQ_FOREACH(ent, filelist, cf_nextp) {
858			if (strcmp(ent->log, *given) == 0) {
859				gmatch++;
860				dupent = init_entry(*given, ent);
861				STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
862			}
863		}
864		if (gmatch) {
865			if (verbose > 2)
866				printf("\t+ Matched entry %s\n", *given);
867			continue;
868		}
869
870		/*
871		 * There was no exact-match for this given file, so look
872		 * for a "glob" entry which does match.
873		 */
874		gmatch = 0;
875		if (verbose > 2 && globlist != NULL)
876			printf("\t+ Checking globs for %s\n", *given);
877		STAILQ_FOREACH(ent, globlist, cf_nextp) {
878			fnres = fnmatch(ent->log, *given, FNM_PATHNAME);
879			if (verbose > 2)
880				printf("\t+    = %d for pattern %s\n", fnres,
881				    ent->log);
882			if (fnres == 0) {
883				gmatch++;
884				dupent = init_entry(*given, ent);
885				/* This new entry is not a glob! */
886				dupent->flags &= ~CE_GLOB;
887				STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
888				/* Only allow a match to one glob-entry */
889				break;
890			}
891		}
892		if (gmatch) {
893			if (verbose > 2)
894				printf("\t+ Matched %s via %s\n", *given,
895				    ent->log);
896			continue;
897		}
898
899		/*
900		 * This given file was not found in any config file, so
901		 * add a worklist item based on the default entry.
902		 */
903		if (verbose > 2)
904			printf("\t+ No entry matched %s  (will use %s)\n",
905			    *given, DEFAULT_MARKER);
906		dupent = init_entry(*given, defconf);
907		/* Mark that it was *not* found in a config file */
908		dupent->def_cfg = 1;
909		STAILQ_INSERT_TAIL(cmdlist, dupent, cf_nextp);
910	}
911
912	/*
913	 * Free all the entries in the original work list, the list of
914	 * glob entries, and the default entry.
915	 */
916	free_clist(filelist);
917	free_clist(globlist);
918	free_entry(defconf);
919
920	/* And finally, return a worklist which matches the given files. */
921	return (cmdlist);
922}
923
924/*
925 * Expand the list of entries with filename patterns, and add all files
926 * which match those glob-entries onto the worklist.
927 */
928static void
929expand_globs(struct cflist *work_p, struct cflist *glob_p)
930{
931	int gmatch, gres;
932	size_t i;
933	char *mfname;
934	struct conf_entry *dupent, *ent, *globent;
935	glob_t pglob;
936	struct stat st_fm;
937
938	/*
939	 * The worklist contains all fully-specified (non-GLOB) names.
940	 *
941	 * Now expand the list of filename-pattern (GLOB) entries into
942	 * a second list, which (by definition) will only match files
943	 * that already exist.  Do not add a glob-related entry for any
944	 * file which already exists in the fully-specified list.
945	 */
946	STAILQ_FOREACH(globent, glob_p, cf_nextp) {
947		gres = glob(globent->log, GLOB_NOCHECK, NULL, &pglob);
948		if (gres != 0) {
949			warn("cannot expand pattern (%d): %s", gres,
950			    globent->log);
951			continue;
952		}
953
954		if (verbose > 2)
955			printf("\t+ Expanding pattern %s\n", globent->log);
956		for (i = 0; i < pglob.gl_matchc; i++) {
957			mfname = pglob.gl_pathv[i];
958
959			/* See if this file already has a specific entry. */
960			gmatch = 0;
961			STAILQ_FOREACH(ent, work_p, cf_nextp) {
962				if (strcmp(mfname, ent->log) == 0) {
963					gmatch++;
964					break;
965				}
966			}
967			if (gmatch)
968				continue;
969
970			/* Make sure the named matched is a file. */
971			gres = lstat(mfname, &st_fm);
972			if (gres != 0) {
973				/* Error on a file that glob() matched?!? */
974				warn("Skipping %s - lstat() error", mfname);
975				continue;
976			}
977			if (!S_ISREG(st_fm.st_mode)) {
978				/* We only rotate files! */
979				if (verbose > 2)
980					printf("\t+  . skipping %s (!file)\n",
981					    mfname);
982				continue;
983			}
984
985			if (verbose > 2)
986				printf("\t+  . add file %s\n", mfname);
987			dupent = init_entry(mfname, globent);
988			/* This new entry is not a glob! */
989			dupent->flags &= ~CE_GLOB;
990
991			/* Add to the worklist. */
992			STAILQ_INSERT_TAIL(work_p, dupent, cf_nextp);
993		}
994		globfree(&pglob);
995		if (verbose > 2)
996			printf("\t+ Done with pattern %s\n", globent->log);
997	}
998}
999
1000/*
1001 * Parse a configuration file and update a linked list of all the logs to
1002 * process.
1003 */
1004static void
1005parse_file(FILE *cf, struct cflist *work_p, struct cflist *glob_p,
1006    struct conf_entry *defconf_p, struct ilist *inclist)
1007{
1008	char line[BUFSIZ], *parse, *q;
1009	char *cp, *errline, *group;
1010	struct conf_entry *working;
1011	struct passwd *pwd;
1012	struct group *grp;
1013	glob_t pglob;
1014	int eol, ptm_opts, res, special;
1015	size_t i;
1016
1017	errline = NULL;
1018	while (fgets(line, BUFSIZ, cf)) {
1019		if ((line[0] == '\n') || (line[0] == '#') ||
1020		    (strlen(line) == 0))
1021			continue;
1022		if (errline != NULL)
1023			free(errline);
1024		errline = strdup(line);
1025		for (cp = line + 1; *cp != '\0'; cp++) {
1026			if (*cp != '#')
1027				continue;
1028			if (*(cp - 1) == '\\') {
1029				strcpy(cp - 1, cp);
1030				cp--;
1031				continue;
1032			}
1033			*cp = '\0';
1034			break;
1035		}
1036
1037		q = parse = missing_field(sob(line), errline);
1038		parse = son(line);
1039		if (!*parse)
1040			errx(1, "malformed line (missing fields):\n%s",
1041			    errline);
1042		*parse = '\0';
1043
1044		/*
1045		 * Allow people to set debug options via the config file.
1046		 * (NOTE: debug options are undocumented, and may disappear
1047		 * at any time, etc).
1048		 */
1049		if (strcasecmp(DEBUG_MARKER, q) == 0) {
1050			q = parse = missing_field(sob(++parse), errline);
1051			parse = son(parse);
1052			if (!*parse)
1053				warnx("debug line specifies no option:\n%s",
1054				    errline);
1055			else {
1056				*parse = '\0';
1057				parse_doption(q);
1058			}
1059			continue;
1060		} else if (strcasecmp(INCLUDE_MARKER, q) == 0) {
1061			if (verbose)
1062				printf("Found: %s", errline);
1063			q = parse = missing_field(sob(++parse), errline);
1064			parse = son(parse);
1065			if (!*parse) {
1066				warnx("include line missing argument:\n%s",
1067				    errline);
1068				continue;
1069			}
1070
1071			*parse = '\0';
1072
1073			if (isglobstr(q)) {
1074				res = glob(q, GLOB_NOCHECK, NULL, &pglob);
1075				if (res != 0) {
1076					warn("cannot expand pattern (%d): %s",
1077					    res, q);
1078					continue;
1079				}
1080
1081				if (verbose > 2)
1082					printf("\t+ Expanding pattern %s\n", q);
1083
1084				for (i = 0; i < pglob.gl_matchc; i++)
1085					add_to_queue(pglob.gl_pathv[i],
1086					    inclist);
1087				globfree(&pglob);
1088			} else
1089				add_to_queue(q, inclist);
1090			continue;
1091		}
1092
1093		special = 0;
1094		working = init_entry(q, NULL);
1095		if (strcasecmp(DEFAULT_MARKER, q) == 0) {
1096			special = 1;
1097			if (defconf_p != NULL) {
1098				warnx("Ignoring duplicate entry for %s!", q);
1099				free_entry(working);
1100				continue;
1101			}
1102			defconf_p = working;
1103		}
1104
1105		q = parse = missing_field(sob(++parse), errline);
1106		parse = son(parse);
1107		if (!*parse)
1108			errx(1, "malformed line (missing fields):\n%s",
1109			    errline);
1110		*parse = '\0';
1111		if ((group = strchr(q, ':')) != NULL ||
1112		    (group = strrchr(q, '.')) != NULL) {
1113			*group++ = '\0';
1114			if (*q) {
1115				if (!(isnumberstr(q))) {
1116					if ((pwd = getpwnam(q)) == NULL)
1117						errx(1,
1118				     "error in config file; unknown user:\n%s",
1119						    errline);
1120					working->uid = pwd->pw_uid;
1121				} else
1122					working->uid = atoi(q);
1123			} else
1124				working->uid = (uid_t)-1;
1125
1126			q = group;
1127			if (*q) {
1128				if (!(isnumberstr(q))) {
1129					if ((grp = getgrnam(q)) == NULL)
1130						errx(1,
1131				    "error in config file; unknown group:\n%s",
1132						    errline);
1133					working->gid = grp->gr_gid;
1134				} else
1135					working->gid = atoi(q);
1136			} else
1137				working->gid = (gid_t)-1;
1138
1139			q = parse = missing_field(sob(++parse), errline);
1140			parse = son(parse);
1141			if (!*parse)
1142				errx(1, "malformed line (missing fields):\n%s",
1143				    errline);
1144			*parse = '\0';
1145		} else {
1146			working->uid = (uid_t)-1;
1147			working->gid = (gid_t)-1;
1148		}
1149
1150		if (!sscanf(q, "%o", &working->permissions))
1151			errx(1, "error in config file; bad permissions:\n%s",
1152			    errline);
1153
1154		q = parse = missing_field(sob(++parse), errline);
1155		parse = son(parse);
1156		if (!*parse)
1157			errx(1, "malformed line (missing fields):\n%s",
1158			    errline);
1159		*parse = '\0';
1160		if (!sscanf(q, "%d", &working->numlogs) || working->numlogs < 0)
1161			errx(1, "error in config file; bad value for count of logs to save:\n%s",
1162			    errline);
1163
1164		q = parse = missing_field(sob(++parse), errline);
1165		parse = son(parse);
1166		if (!*parse)
1167			errx(1, "malformed line (missing fields):\n%s",
1168			    errline);
1169		*parse = '\0';
1170		if (isdigitch(*q))
1171			working->trsize = atoi(q);
1172		else if (strcmp(q, "*") == 0)
1173			working->trsize = -1;
1174		else {
1175			warnx("Invalid value of '%s' for 'size' in line:\n%s",
1176			    q, errline);
1177			working->trsize = -1;
1178		}
1179
1180		working->flags = 0;
1181		q = parse = missing_field(sob(++parse), errline);
1182		parse = son(parse);
1183		eol = !*parse;
1184		*parse = '\0';
1185		{
1186			char *ep;
1187			u_long ul;
1188
1189			ul = strtoul(q, &ep, 10);
1190			if (ep == q)
1191				working->hours = 0;
1192			else if (*ep == '*')
1193				working->hours = -1;
1194			else if (ul > INT_MAX)
1195				errx(1, "interval is too large:\n%s", errline);
1196			else
1197				working->hours = ul;
1198
1199			if (*ep == '\0' || strcmp(ep, "*") == 0)
1200				goto no_trimat;
1201			if (*ep != '@' && *ep != '$')
1202				errx(1, "malformed interval/at:\n%s", errline);
1203
1204			working->flags |= CE_TRIMAT;
1205			working->trim_at = ptime_init(NULL);
1206			ptm_opts = PTM_PARSE_ISO8601;
1207			if (*ep == '$')
1208				ptm_opts = PTM_PARSE_DWM;
1209			ptm_opts |= PTM_PARSE_MATCHDOM;
1210			res = ptime_relparse(working->trim_at, ptm_opts,
1211			    ptimeget_secs(timenow), ep + 1);
1212			if (res == -2)
1213				errx(1, "nonexistent time for 'at' value:\n%s",
1214				    errline);
1215			else if (res < 0)
1216				errx(1, "malformed 'at' value:\n%s", errline);
1217		}
1218no_trimat:
1219
1220		if (eol)
1221			q = NULL;
1222		else {
1223			q = parse = sob(++parse);	/* Optional field */
1224			parse = son(parse);
1225			if (!*parse)
1226				eol = 1;
1227			*parse = '\0';
1228		}
1229
1230		for (; q && *q && !isspacech(*q); q++) {
1231			switch (tolowerch(*q)) {
1232			case 'b':
1233				working->flags |= CE_BINARY;
1234				break;
1235			case 'c':
1236				/*
1237				 * XXX - 	Ick! Ugly! Remove ASAP!
1238				 * We want `c' and `C' for "create".  But we
1239				 * will temporarily treat `c' as `g', because
1240				 * FreeBSD releases <= 4.8 have a typo of
1241				 * checking  ('G' || 'c')  for CE_GLOB.
1242				 */
1243				if (*q == 'c') {
1244					warnx("Assuming 'g' for 'c' in flags for line:\n%s",
1245					    errline);
1246					warnx("The 'c' flag will eventually mean 'CREATE'");
1247					working->flags |= CE_GLOB;
1248					break;
1249				}
1250				working->flags |= CE_CREATE;
1251				break;
1252			case 'd':
1253				working->flags |= CE_NODUMP;
1254				break;
1255			case 'g':
1256				working->flags |= CE_GLOB;
1257				break;
1258			case 'j':
1259				working->flags |= CE_BZCOMPACT;
1260				break;
1261			case 'n':
1262				working->flags |= CE_NOSIGNAL;
1263				break;
1264			case 'u':
1265				working->flags |= CE_SIGNALGROUP;
1266				break;
1267			case 'w':
1268				/* Depreciated flag - keep for compatibility purposes */
1269				break;
1270			case 'z':
1271				working->flags |= CE_COMPACT;
1272				break;
1273			case '-':
1274				break;
1275			case 'f':	/* Used by OpenBSD for "CE_FOLLOW" */
1276			case 'm':	/* Used by OpenBSD for "CE_MONITOR" */
1277			case 'p':	/* Used by NetBSD  for "CE_PLAIN0" */
1278			default:
1279				errx(1, "illegal flag in config file -- %c",
1280				    *q);
1281			}
1282		}
1283
1284		if (eol)
1285			q = NULL;
1286		else {
1287			q = parse = sob(++parse);	/* Optional field */
1288			parse = son(parse);
1289			if (!*parse)
1290				eol = 1;
1291			*parse = '\0';
1292		}
1293
1294		working->pid_file = NULL;
1295		if (q && *q) {
1296			if (*q == '/')
1297				working->pid_file = strdup(q);
1298			else if (isdigit(*q))
1299				goto got_sig;
1300			else
1301				errx(1,
1302			"illegal pid file or signal number in config file:\n%s",
1303				    errline);
1304		}
1305		if (eol)
1306			q = NULL;
1307		else {
1308			q = parse = sob(++parse);	/* Optional field */
1309			*(parse = son(parse)) = '\0';
1310		}
1311
1312		working->sig = SIGHUP;
1313		if (q && *q) {
1314			if (isdigit(*q)) {
1315		got_sig:
1316				working->sig = atoi(q);
1317			} else {
1318		err_sig:
1319				errx(1,
1320				    "illegal signal number in config file:\n%s",
1321				    errline);
1322			}
1323			if (working->sig < 1 || working->sig >= NSIG)
1324				goto err_sig;
1325		}
1326
1327		/*
1328		 * Finish figuring out what pid-file to use (if any) in
1329		 * later processing if this logfile needs to be rotated.
1330		 */
1331		if ((working->flags & CE_NOSIGNAL) == CE_NOSIGNAL) {
1332			/*
1333			 * This config-entry specified 'n' for nosignal,
1334			 * see if it also specified an explicit pid_file.
1335			 * This would be a pretty pointless combination.
1336			 */
1337			if (working->pid_file != NULL) {
1338				warnx("Ignoring '%s' because flag 'n' was specified in line:\n%s",
1339				    working->pid_file, errline);
1340				free(working->pid_file);
1341				working->pid_file = NULL;
1342			}
1343		} else if (working->pid_file == NULL) {
1344			/*
1345			 * This entry did not specify the 'n' flag, which
1346			 * means it should signal syslogd unless it had
1347			 * specified some other pid-file (and obviously the
1348			 * syslog pid-file will not be for a process-group).
1349			 * Also, we should only try to notify syslog if we
1350			 * are root.
1351			 */
1352			if (working->flags & CE_SIGNALGROUP) {
1353				warnx("Ignoring flag 'U' in line:\n%s",
1354				    errline);
1355				working->flags &= ~CE_SIGNALGROUP;
1356			}
1357			if (needroot)
1358				working->pid_file = strdup(_PATH_SYSLOGPID);
1359		}
1360
1361		/*
1362		 * Add this entry to the appropriate list of entries, unless
1363		 * it was some kind of special entry (eg: <default>).
1364		 */
1365		if (special) {
1366			;			/* Do not add to any list */
1367		} else if (working->flags & CE_GLOB) {
1368			STAILQ_INSERT_TAIL(glob_p, working, cf_nextp);
1369		} else {
1370			STAILQ_INSERT_TAIL(work_p, working, cf_nextp);
1371		}
1372	}
1373	if (errline != NULL)
1374		free(errline);
1375}
1376
1377static char *
1378missing_field(char *p, char *errline)
1379{
1380
1381	if (!p || !*p)
1382		errx(1, "missing field in config file:\n%s", errline);
1383	return (p);
1384}
1385
1386/*
1387 * In our sort we return it in the reverse of what qsort normally
1388 * would do, as we want the newest files first.  If we have two
1389 * entries with the same time we don't really care about order.
1390 *
1391 * Support function for qsort() in delete_oldest_timelog().
1392 */
1393static int
1394oldlog_entry_compare(const void *a, const void *b)
1395{
1396	const struct oldlog_entry *ola = a, *olb = b;
1397
1398	if (ola->t > olb->t)
1399		return (-1);
1400	else if (ola->t < olb->t)
1401		return (1);
1402	else
1403		return (0);
1404}
1405
1406/*
1407 * Delete the oldest logfiles, when using time based filenames.
1408 */
1409static void
1410delete_oldest_timelog(const struct conf_entry *ent, const char *archive_dir)
1411{
1412	char *logfname, *s, *dir, errbuf[80];
1413	int logcnt, max_logcnt, dirfd, i;
1414	struct oldlog_entry *oldlogs;
1415	size_t logfname_len;
1416	struct dirent *dp;
1417	const char *cdir;
1418	struct tm tm;
1419	DIR *dirp;
1420
1421	oldlogs = malloc(MAX_OLDLOGS * sizeof(struct oldlog_entry));
1422	max_logcnt = MAX_OLDLOGS;
1423	logcnt = 0;
1424
1425	if (archive_dir != NULL && archive_dir[0] != '\0')
1426		cdir = archive_dir;
1427	else
1428		if ((cdir = dirname(ent->log)) == NULL)
1429			err(1, "dirname()");
1430	if ((dir = strdup(cdir)) == NULL)
1431		err(1, "strdup()");
1432
1433	if ((s = basename(ent->log)) == NULL)
1434		err(1, "basename()");
1435	if ((logfname = strdup(s)) == NULL)
1436		err(1, "strdup()");
1437	logfname_len = strlen(logfname);
1438	if (strcmp(logfname, "/") == 0)
1439		errx(1, "Invalid log filename - became '/'");
1440
1441	if (verbose > 2)
1442		printf("Searching for old logs in %s\n", dir);
1443
1444	/* First we create a 'list' of all archived logfiles */
1445	if ((dirp = opendir(dir)) == NULL)
1446		err(1, "Cannot open log directory '%s'", dir);
1447	dirfd = dirfd(dirp);
1448	while ((dp = readdir(dirp)) != NULL) {
1449		if (dp->d_type != DT_REG)
1450			continue;
1451
1452		/* Ignore everything but files with our logfile prefix */
1453		if (strncmp(dp->d_name, logfname, logfname_len) != 0)
1454			continue;
1455		/* Ignore the actual non-rotated logfile */
1456		if (dp->d_namlen == logfname_len)
1457			continue;
1458		/*
1459		 * Make sure we created have found a logfile, so the
1460		 * postfix is valid, IE format is: '.<time>(.[bg]z)?'.
1461		 */
1462		if (dp->d_name[logfname_len] != '.') {
1463			if (verbose)
1464				printf("Ignoring %s which has unexpected "
1465				    "extension '%s'\n", dp->d_name,
1466				    &dp->d_name[logfname_len]);
1467			continue;
1468		}
1469		if ((s = strptime(&dp->d_name[logfname_len + 1],
1470			    timefnamefmt, &tm)) == NULL) {
1471			/*
1472			 * We could special case "old" sequentially
1473			 * named logfiles here, but we do not as that
1474			 * would require special handling to decide
1475			 * which one was the oldest compared to "new"
1476			 * time based logfiles.
1477			 */
1478			if (verbose)
1479				printf("Ignoring %s which does not "
1480				    "match time format\n", dp->d_name);
1481			continue;
1482		}
1483		if (*s != '\0' && !(strcmp(s, BZCOMPRESS_POSTFIX) == 0 ||
1484			strcmp(s, COMPRESS_POSTFIX) == 0))  {
1485			    if (verbose)
1486				printf("Ignoring %s which has unexpected "
1487				    "extension '%s'\n", dp->d_name, s);
1488			continue;
1489		}
1490
1491		/*
1492		 * We should now have old an old rotated logfile, so
1493		 * add it to the 'list'.
1494		 */
1495		if ((oldlogs[logcnt].t = timegm(&tm)) == -1)
1496			err(1, "Could not convert time string to time value");
1497		if ((oldlogs[logcnt].fname = strdup(dp->d_name)) == NULL)
1498			err(1, "strdup()");
1499		logcnt++;
1500
1501		/*
1502		 * It is very unlikely we ever run out of space in the
1503		 * logfile array from the default size, but lets
1504		 * handle it anyway...
1505		 */
1506		if (logcnt >= max_logcnt) {
1507			max_logcnt *= 4;
1508			/* Detect integer overflow */
1509			if (max_logcnt < logcnt)
1510				errx(1, "Too many old logfiles found");
1511			oldlogs = realloc(oldlogs,
1512			    max_logcnt * sizeof(struct oldlog_entry));
1513			if (oldlogs == NULL)
1514				err(1, "realloc()");
1515		}
1516	}
1517
1518	/* Second, if needed we delete oldest archived logfiles */
1519	if (logcnt > 0 && logcnt >= ent->numlogs && ent->numlogs > 1) {
1520		oldlogs = realloc(oldlogs, logcnt *
1521		    sizeof(struct oldlog_entry));
1522		if (oldlogs == NULL)
1523			err(1, "realloc()");
1524
1525		/*
1526		 * We now sort the logs in the order of newest to
1527		 * oldest.  That way we can simply skip over the
1528		 * number of records we want to keep.
1529		 */
1530		qsort(oldlogs, logcnt, sizeof(struct oldlog_entry),
1531		    oldlog_entry_compare);
1532		for (i = ent->numlogs - 1; i < logcnt; i++) {
1533			if (noaction)
1534				printf("\trm -f %s/%s\n", dir,
1535				    oldlogs[i].fname);
1536			else if (unlinkat(dirfd, oldlogs[i].fname, 0) != 0) {
1537				snprintf(errbuf, sizeof(errbuf),
1538				    "Could not delet old logfile '%s'",
1539				    oldlogs[i].fname);
1540				perror(errbuf);
1541			}
1542		}
1543	} else if (verbose > 1)
1544		printf("No old logs to delete for logfile %s\n", ent->log);
1545
1546	/* Third, cleanup */
1547	closedir(dirp);
1548	for (i = 0; i < logcnt; i++) {
1549		assert(oldlogs[i].fname != NULL);
1550		free(oldlogs[i].fname);
1551	}
1552	free(oldlogs);
1553	free(logfname);
1554	free(dir);
1555}
1556
1557/*
1558 * Only add to the queue if the file hasn't already been added. This is
1559 * done to prevent circular include loops.
1560 */
1561static void
1562add_to_queue(const char *fname, struct ilist *inclist)
1563{
1564	struct include_entry *inc;
1565
1566	STAILQ_FOREACH(inc, inclist, inc_nextp) {
1567		if (strcmp(fname, inc->file) == 0) {
1568			warnx("duplicate include detected: %s", fname);
1569			return;
1570		}
1571	}
1572
1573	inc = malloc(sizeof(struct include_entry));
1574	if (inc == NULL)
1575		err(1, "malloc of inc");
1576	inc->file = strdup(fname);
1577
1578	if (verbose > 2)
1579		printf("\t+ Adding %s to the processing queue.\n", fname);
1580
1581	STAILQ_INSERT_TAIL(inclist, inc, inc_nextp);
1582}
1583
1584static fk_entry
1585do_rotate(const struct conf_entry *ent)
1586{
1587	char dirpart[MAXPATHLEN], namepart[MAXPATHLEN];
1588	char file1[MAXPATHLEN], file2[MAXPATHLEN];
1589	char zfile1[MAXPATHLEN], zfile2[MAXPATHLEN];
1590	char jfile1[MAXPATHLEN];
1591	char datetimestr[30];
1592	int flags, numlogs_c;
1593	fk_entry free_or_keep;
1594	struct sigwork_entry *swork;
1595	struct stat st;
1596	struct tm tm;
1597	time_t now;
1598
1599	flags = ent->flags;
1600	free_or_keep = FREE_ENT;
1601
1602	if (archtodir) {
1603		char *p;
1604
1605		/* build complete name of archive directory into dirpart */
1606		if (*archdirname == '/') {	/* absolute */
1607			strlcpy(dirpart, archdirname, sizeof(dirpart));
1608		} else {	/* relative */
1609			/* get directory part of logfile */
1610			strlcpy(dirpart, ent->log, sizeof(dirpart));
1611			if ((p = rindex(dirpart, '/')) == NULL)
1612				dirpart[0] = '\0';
1613			else
1614				*(p + 1) = '\0';
1615			strlcat(dirpart, archdirname, sizeof(dirpart));
1616		}
1617
1618		/* check if archive directory exists, if not, create it */
1619		if (lstat(dirpart, &st))
1620			createdir(ent, dirpart);
1621
1622		/* get filename part of logfile */
1623		if ((p = rindex(ent->log, '/')) == NULL)
1624			strlcpy(namepart, ent->log, sizeof(namepart));
1625		else
1626			strlcpy(namepart, p + 1, sizeof(namepart));
1627
1628		/* name of oldest log */
1629		(void) snprintf(file1, sizeof(file1), "%s/%s.%d", dirpart,
1630		    namepart, ent->numlogs);
1631	} else {
1632		/*
1633		 * Tell delete_oldest_timelog() we are not using an
1634		 * archive dir.
1635		 */
1636		dirpart[0] = '\0';
1637
1638		/* name of oldest log */
1639		(void) snprintf(file1, sizeof(file1), "%s.%d", ent->log,
1640		    ent->numlogs);
1641	}
1642
1643	/* Delete old logs */
1644	if (timefnamefmt != NULL)
1645		delete_oldest_timelog(ent, dirpart);
1646	else {
1647		/* name of oldest log */
1648		(void) snprintf(zfile1, sizeof(zfile1), "%s%s", file1,
1649		    COMPRESS_POSTFIX);
1650		snprintf(jfile1, sizeof(jfile1), "%s%s", file1,
1651		    BZCOMPRESS_POSTFIX);
1652
1653		if (noaction) {
1654			printf("\trm -f %s\n", file1);
1655			printf("\trm -f %s\n", zfile1);
1656			printf("\trm -f %s\n", jfile1);
1657		} else {
1658			(void) unlink(file1);
1659			(void) unlink(zfile1);
1660			(void) unlink(jfile1);
1661		}
1662	}
1663
1664	if (timefnamefmt != NULL) {
1665		/* If time functions fails we can't really do any sensible */
1666		if (time(&now) == (time_t)-1 ||
1667		    localtime_r(&now, &tm) == NULL)
1668			bzero(&tm, sizeof(tm));
1669
1670		strftime(datetimestr, sizeof(datetimestr), timefnamefmt, &tm);
1671		if (archtodir)
1672			(void) snprintf(file1, sizeof(file1), "%s/%s.%s",
1673			    dirpart, namepart, datetimestr);
1674		else
1675			(void) snprintf(file1, sizeof(file1), "%s.%s",
1676			    ent->log, datetimestr);
1677
1678		/* Don't run the code to move down logs */
1679		numlogs_c = 0;
1680	} else
1681		numlogs_c = ent->numlogs;		/* copy for countdown */
1682
1683	/* Move down log files */
1684	while (numlogs_c--) {
1685
1686		(void) strlcpy(file2, file1, sizeof(file2));
1687
1688		if (archtodir)
1689			(void) snprintf(file1, sizeof(file1), "%s/%s.%d",
1690			    dirpart, namepart, numlogs_c);
1691		else
1692			(void) snprintf(file1, sizeof(file1), "%s.%d",
1693			    ent->log, numlogs_c);
1694
1695		(void) strlcpy(zfile1, file1, sizeof(zfile1));
1696		(void) strlcpy(zfile2, file2, sizeof(zfile2));
1697		if (lstat(file1, &st)) {
1698			(void) strlcat(zfile1, COMPRESS_POSTFIX,
1699			    sizeof(zfile1));
1700			(void) strlcat(zfile2, COMPRESS_POSTFIX,
1701			    sizeof(zfile2));
1702			if (lstat(zfile1, &st)) {
1703				strlcpy(zfile1, file1, sizeof(zfile1));
1704				strlcpy(zfile2, file2, sizeof(zfile2));
1705				strlcat(zfile1, BZCOMPRESS_POSTFIX,
1706				    sizeof(zfile1));
1707				strlcat(zfile2, BZCOMPRESS_POSTFIX,
1708				    sizeof(zfile2));
1709				if (lstat(zfile1, &st))
1710					continue;
1711			}
1712		}
1713		if (noaction)
1714			printf("\tmv %s %s\n", zfile1, zfile2);
1715		else {
1716			/* XXX - Ought to be checking for failure! */
1717			(void)rename(zfile1, zfile2);
1718		}
1719		change_attrs(zfile2, ent);
1720	}
1721
1722	if (ent->numlogs > 0) {
1723		if (noaction) {
1724			/*
1725			 * Note that savelog() may succeed with using link()
1726			 * for the archtodir case, but there is no good way
1727			 * of knowing if it will when doing "noaction", so
1728			 * here we claim that it will have to do a copy...
1729			 */
1730			if (archtodir)
1731				printf("\tcp %s %s\n", ent->log, file1);
1732			else
1733				printf("\tln %s %s\n", ent->log, file1);
1734		} else {
1735			if (!(flags & CE_BINARY)) {
1736				/* Report the trimming to the old log */
1737				log_trim(ent->log, ent);
1738			}
1739			savelog(ent->log, file1);
1740		}
1741		change_attrs(file1, ent);
1742	}
1743
1744	/* Create the new log file and move it into place */
1745	if (noaction)
1746		printf("Start new log...\n");
1747	createlog(ent);
1748
1749	/*
1750	 * Save all signalling and file-compression to be done after log
1751	 * files from all entries have been rotated.  This way any one
1752	 * process will not be sent the same signal multiple times when
1753	 * multiple log files had to be rotated.
1754	 */
1755	swork = NULL;
1756	if (ent->pid_file != NULL)
1757		swork = save_sigwork(ent);
1758	if (ent->numlogs > 0 && (flags & (CE_COMPACT | CE_BZCOMPACT))) {
1759		/*
1760		 * The zipwork_entry will include a pointer to this
1761		 * conf_entry, so the conf_entry should not be freed.
1762		 */
1763		free_or_keep = KEEP_ENT;
1764		save_zipwork(ent, swork, ent->fsize, file1);
1765	}
1766
1767	return (free_or_keep);
1768}
1769
1770static void
1771do_sigwork(struct sigwork_entry *swork)
1772{
1773	struct sigwork_entry *nextsig;
1774	int kres, secs;
1775
1776	if (!(swork->sw_pidok) || swork->sw_pid == 0)
1777		return;			/* no work to do... */
1778
1779	/*
1780	 * If nosignal (-s) was specified, then do not signal any process.
1781	 * Note that a nosignal request triggers a warning message if the
1782	 * rotated logfile needs to be compressed, *unless* -R was also
1783	 * specified.  We assume that an `-sR' request came from a process
1784	 * which writes to the logfile, and as such, we assume that process
1785	 * has already made sure the logfile is not presently in use.  This
1786	 * just sets swork->sw_pidok to a special value, and do_zipwork
1787	 * will print any necessary warning(s).
1788	 */
1789	if (nosignal) {
1790		if (!rotatereq)
1791			swork->sw_pidok = -1;
1792		return;
1793	}
1794
1795	/*
1796	 * Compute the pause between consecutive signals.  Use a longer
1797	 * sleep time if we will be sending two signals to the same
1798	 * deamon or process-group.
1799	 */
1800	secs = 0;
1801	nextsig = SLIST_NEXT(swork, sw_nextp);
1802	if (nextsig != NULL) {
1803		if (swork->sw_pid == nextsig->sw_pid)
1804			secs = 10;
1805		else
1806			secs = 1;
1807	}
1808
1809	if (noaction) {
1810		printf("\tkill -%d %d \t\t# %s\n", swork->sw_signum,
1811		    (int)swork->sw_pid, swork->sw_fname);
1812		if (secs > 0)
1813			printf("\tsleep %d\n", secs);
1814		return;
1815	}
1816
1817	kres = kill(swork->sw_pid, swork->sw_signum);
1818	if (kres != 0) {
1819		/*
1820		 * Assume that "no such process" (ESRCH) is something
1821		 * to warn about, but is not an error.  Presumably the
1822		 * process which writes to the rotated log file(s) is
1823		 * gone, in which case we should have no problem with
1824		 * compressing the rotated log file(s).
1825		 */
1826		if (errno != ESRCH)
1827			swork->sw_pidok = 0;
1828		warn("can't notify %s, pid %d", swork->sw_pidtype,
1829		    (int)swork->sw_pid);
1830	} else {
1831		if (verbose)
1832			printf("Notified %s pid %d = %s\n", swork->sw_pidtype,
1833			    (int)swork->sw_pid, swork->sw_fname);
1834		if (secs > 0) {
1835			if (verbose)
1836				printf("Pause %d second(s) between signals\n",
1837				    secs);
1838			sleep(secs);
1839		}
1840	}
1841}
1842
1843static void
1844do_zipwork(struct zipwork_entry *zwork)
1845{
1846	const char *pgm_name, *pgm_path;
1847	int errsav, fcount, zstatus;
1848	pid_t pidzip, wpid;
1849	char zresult[MAXPATHLEN];
1850
1851	pgm_path = NULL;
1852	strlcpy(zresult, zwork->zw_fname, sizeof(zresult));
1853	if (zwork != NULL && zwork->zw_conf != NULL) {
1854		if (zwork->zw_conf->flags & CE_COMPACT) {
1855			pgm_path = _PATH_GZIP;
1856			strlcat(zresult, COMPRESS_POSTFIX, sizeof(zresult));
1857		} else if (zwork->zw_conf->flags & CE_BZCOMPACT) {
1858			pgm_path = _PATH_BZIP2;
1859			strlcat(zresult, BZCOMPRESS_POSTFIX, sizeof(zresult));
1860		}
1861	}
1862	if (pgm_path == NULL) {
1863		warnx("invalid entry for %s in do_zipwork", zwork->zw_fname);
1864		return;
1865	}
1866	pgm_name = strrchr(pgm_path, '/');
1867	if (pgm_name == NULL)
1868		pgm_name = pgm_path;
1869	else
1870		pgm_name++;
1871
1872	if (zwork->zw_swork != NULL && zwork->zw_swork->sw_pidok <= 0) {
1873		warnx(
1874		    "log %s not compressed because daemon(s) not notified",
1875		    zwork->zw_fname);
1876		change_attrs(zwork->zw_fname, zwork->zw_conf);
1877		return;
1878	}
1879
1880	if (noaction) {
1881		printf("\t%s %s\n", pgm_name, zwork->zw_fname);
1882		change_attrs(zresult, zwork->zw_conf);
1883		return;
1884	}
1885
1886	fcount = 1;
1887	pidzip = fork();
1888	while (pidzip < 0) {
1889		/*
1890		 * The fork failed.  If the failure was due to a temporary
1891		 * problem, then wait a short time and try it again.
1892		 */
1893		errsav = errno;
1894		warn("fork() for `%s %s'", pgm_name, zwork->zw_fname);
1895		if (errsav != EAGAIN || fcount > 5)
1896			errx(1, "Exiting...");
1897		sleep(fcount * 12);
1898		fcount++;
1899		pidzip = fork();
1900	}
1901	if (!pidzip) {
1902		/* The child process executes the compression command */
1903		execl(pgm_path, pgm_path, "-f", zwork->zw_fname, (char *)0);
1904		err(1, "execl(`%s -f %s')", pgm_path, zwork->zw_fname);
1905	}
1906
1907	wpid = waitpid(pidzip, &zstatus, 0);
1908	if (wpid == -1) {
1909		/* XXX - should this be a fatal error? */
1910		warn("%s: waitpid(%d)", pgm_path, pidzip);
1911		return;
1912	}
1913	if (!WIFEXITED(zstatus)) {
1914		warnx("`%s -f %s' did not terminate normally", pgm_name,
1915		    zwork->zw_fname);
1916		return;
1917	}
1918	if (WEXITSTATUS(zstatus)) {
1919		warnx("`%s -f %s' terminated with a non-zero status (%d)",
1920		    pgm_name, zwork->zw_fname, WEXITSTATUS(zstatus));
1921		return;
1922	}
1923
1924	/* Compression was successful, set file attributes on the result. */
1925	change_attrs(zresult, zwork->zw_conf);
1926}
1927
1928/*
1929 * Save information on any process we need to signal.  Any single
1930 * process may need to be sent different signal-values for different
1931 * log files, but usually a single signal-value will cause the process
1932 * to close and re-open all of it's log files.
1933 */
1934static struct sigwork_entry *
1935save_sigwork(const struct conf_entry *ent)
1936{
1937	struct sigwork_entry *sprev, *stmp;
1938	int ndiff;
1939	size_t tmpsiz;
1940
1941	sprev = NULL;
1942	ndiff = 1;
1943	SLIST_FOREACH(stmp, &swhead, sw_nextp) {
1944		ndiff = strcmp(ent->pid_file, stmp->sw_fname);
1945		if (ndiff > 0)
1946			break;
1947		if (ndiff == 0) {
1948			if (ent->sig == stmp->sw_signum)
1949				break;
1950			if (ent->sig > stmp->sw_signum) {
1951				ndiff = 1;
1952				break;
1953			}
1954		}
1955		sprev = stmp;
1956	}
1957	if (stmp != NULL && ndiff == 0)
1958		return (stmp);
1959
1960	tmpsiz = sizeof(struct sigwork_entry) + strlen(ent->pid_file) + 1;
1961	stmp = malloc(tmpsiz);
1962	set_swpid(stmp, ent);
1963	stmp->sw_signum = ent->sig;
1964	strcpy(stmp->sw_fname, ent->pid_file);
1965	if (sprev == NULL)
1966		SLIST_INSERT_HEAD(&swhead, stmp, sw_nextp);
1967	else
1968		SLIST_INSERT_AFTER(sprev, stmp, sw_nextp);
1969	return (stmp);
1970}
1971
1972/*
1973 * Save information on any file we need to compress.  We may see the same
1974 * file multiple times, so check the full list to avoid duplicates.  The
1975 * list itself is sorted smallest-to-largest, because that's the order we
1976 * want to compress the files.  If the partition is very low on disk space,
1977 * then the smallest files are the most likely to compress, and compressing
1978 * them first will free up more space for the larger files.
1979 */
1980static struct zipwork_entry *
1981save_zipwork(const struct conf_entry *ent, const struct sigwork_entry *swork,
1982    int zsize, const char *zipfname)
1983{
1984	struct zipwork_entry *zprev, *ztmp;
1985	int ndiff;
1986	size_t tmpsiz;
1987
1988	/* Compute the size if the caller did not know it. */
1989	if (zsize < 0)
1990		zsize = sizefile(zipfname);
1991
1992	zprev = NULL;
1993	ndiff = 1;
1994	SLIST_FOREACH(ztmp, &zwhead, zw_nextp) {
1995		ndiff = strcmp(zipfname, ztmp->zw_fname);
1996		if (ndiff == 0)
1997			break;
1998		if (zsize > ztmp->zw_fsize)
1999			zprev = ztmp;
2000	}
2001	if (ztmp != NULL && ndiff == 0)
2002		return (ztmp);
2003
2004	tmpsiz = sizeof(struct zipwork_entry) + strlen(zipfname) + 1;
2005	ztmp = malloc(tmpsiz);
2006	ztmp->zw_conf = ent;
2007	ztmp->zw_swork = swork;
2008	ztmp->zw_fsize = zsize;
2009	strcpy(ztmp->zw_fname, zipfname);
2010	if (zprev == NULL)
2011		SLIST_INSERT_HEAD(&zwhead, ztmp, zw_nextp);
2012	else
2013		SLIST_INSERT_AFTER(zprev, ztmp, zw_nextp);
2014	return (ztmp);
2015}
2016
2017/* Send a signal to the pid specified by pidfile */
2018static void
2019set_swpid(struct sigwork_entry *swork, const struct conf_entry *ent)
2020{
2021	FILE *f;
2022	long minok, maxok, rval;
2023	char *endp, *linep, line[BUFSIZ];
2024
2025	minok = MIN_PID;
2026	maxok = MAX_PID;
2027	swork->sw_pidok = 0;
2028	swork->sw_pid = 0;
2029	swork->sw_pidtype = "daemon";
2030	if (ent->flags & CE_SIGNALGROUP) {
2031		/*
2032		 * If we are expected to signal a process-group when
2033		 * rotating this logfile, then the value read in should
2034		 * be the negative of a valid process ID.
2035		 */
2036		minok = -MAX_PID;
2037		maxok = -MIN_PID;
2038		swork->sw_pidtype = "process-group";
2039	}
2040
2041	f = fopen(ent->pid_file, "r");
2042	if (f == NULL) {
2043		if (errno == ENOENT && enforcepid == 0) {
2044			/*
2045			 * Warn if the PID file doesn't exist, but do
2046			 * not consider it an error.  Most likely it
2047			 * means the process has been terminated,
2048			 * so it should be safe to rotate any log
2049			 * files that the process would have been using.
2050			 */
2051			swork->sw_pidok = 1;
2052			warnx("pid file doesn't exist: %s", ent->pid_file);
2053		} else
2054			warn("can't open pid file: %s", ent->pid_file);
2055		return;
2056	}
2057
2058	if (fgets(line, BUFSIZ, f) == NULL) {
2059		/*
2060		 * Warn if the PID file is empty, but do not consider
2061		 * it an error.  Most likely it means the process has
2062		 * has terminated, so it should be safe to rotate any
2063		 * log files that the process would have been using.
2064		 */
2065		if (feof(f) && enforcepid == 0) {
2066			swork->sw_pidok = 1;
2067			warnx("pid file is empty: %s", ent->pid_file);
2068		} else
2069			warn("can't read from pid file: %s", ent->pid_file);
2070		(void)fclose(f);
2071		return;
2072	}
2073	(void)fclose(f);
2074
2075	errno = 0;
2076	linep = line;
2077	while (*linep == ' ')
2078		linep++;
2079	rval = strtol(linep, &endp, 10);
2080	if (*endp != '\0' && !isspacech(*endp)) {
2081		warnx("pid file does not start with a valid number: %s",
2082		    ent->pid_file);
2083	} else if (rval < minok || rval > maxok) {
2084		warnx("bad value '%ld' for process number in %s",
2085		    rval, ent->pid_file);
2086		if (verbose)
2087			warnx("\t(expecting value between %ld and %ld)",
2088			    minok, maxok);
2089	} else {
2090		swork->sw_pidok = 1;
2091		swork->sw_pid = rval;
2092	}
2093
2094	return;
2095}
2096
2097/* Log the fact that the logs were turned over */
2098static int
2099log_trim(const char *logname, const struct conf_entry *log_ent)
2100{
2101	FILE *f;
2102	const char *xtra;
2103
2104	if ((f = fopen(logname, "a")) == NULL)
2105		return (-1);
2106	xtra = "";
2107	if (log_ent->def_cfg)
2108		xtra = " using <default> rule";
2109	if (log_ent->firstcreate)
2110		fprintf(f, "%s %s newsyslog[%d]: logfile first created%s\n",
2111		    daytime, hostname, (int) getpid(), xtra);
2112	else if (log_ent->r_reason != NULL)
2113		fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s%s\n",
2114		    daytime, hostname, (int) getpid(), log_ent->r_reason, xtra);
2115	else
2116		fprintf(f, "%s %s newsyslog[%d]: logfile turned over%s\n",
2117		    daytime, hostname, (int) getpid(), xtra);
2118	if (fclose(f) == EOF)
2119		err(1, "log_trim: fclose");
2120	return (0);
2121}
2122
2123/* Return size in kilobytes of a file */
2124static int
2125sizefile(const char *file)
2126{
2127	struct stat sb;
2128
2129	if (stat(file, &sb) < 0)
2130		return (-1);
2131	return (kbytes(dbtob(sb.st_blocks)));
2132}
2133
2134/* Return the age of old log file (file.0) */
2135static int
2136age_old_log(char *file)
2137{
2138	struct stat sb;
2139	char *endp;
2140	char tmp[MAXPATHLEN + sizeof(".0") + sizeof(COMPRESS_POSTFIX) +
2141		sizeof(BZCOMPRESS_POSTFIX) + 1];
2142
2143	if (archtodir) {
2144		char *p;
2145
2146		/* build name of archive directory into tmp */
2147		if (*archdirname == '/') {	/* absolute */
2148			strlcpy(tmp, archdirname, sizeof(tmp));
2149		} else {	/* relative */
2150			/* get directory part of logfile */
2151			strlcpy(tmp, file, sizeof(tmp));
2152			if ((p = rindex(tmp, '/')) == NULL)
2153				tmp[0] = '\0';
2154			else
2155				*(p + 1) = '\0';
2156			strlcat(tmp, archdirname, sizeof(tmp));
2157		}
2158
2159		strlcat(tmp, "/", sizeof(tmp));
2160
2161		/* get filename part of logfile */
2162		if ((p = rindex(file, '/')) == NULL)
2163			strlcat(tmp, file, sizeof(tmp));
2164		else
2165			strlcat(tmp, p + 1, sizeof(tmp));
2166	} else {
2167		(void) strlcpy(tmp, file, sizeof(tmp));
2168	}
2169
2170	strlcat(tmp, ".0", sizeof(tmp));
2171	if (stat(tmp, &sb) < 0) {
2172		/*
2173		 * A plain '.0' file does not exist.  Try again, first
2174		 * with the added suffix of '.gz', then with an added
2175		 * suffix of '.bz2' instead of '.gz'.
2176		 */
2177		endp = strchr(tmp, '\0');
2178		strlcat(tmp, COMPRESS_POSTFIX, sizeof(tmp));
2179		if (stat(tmp, &sb) < 0) {
2180			*endp = '\0';		/* Remove .gz */
2181			strlcat(tmp, BZCOMPRESS_POSTFIX, sizeof(tmp));
2182			if (stat(tmp, &sb) < 0)
2183				return (-1);
2184		}
2185	}
2186	return ((int)(ptimeget_secs(timenow) - sb.st_mtime + 1800) / 3600);
2187}
2188
2189/* Skip Over Blanks */
2190static char *
2191sob(char *p)
2192{
2193	while (p && *p && isspace(*p))
2194		p++;
2195	return (p);
2196}
2197
2198/* Skip Over Non-Blanks */
2199static char *
2200son(char *p)
2201{
2202	while (p && *p && !isspace(*p))
2203		p++;
2204	return (p);
2205}
2206
2207/* Check if string is actually a number */
2208static int
2209isnumberstr(const char *string)
2210{
2211	while (*string) {
2212		if (!isdigitch(*string++))
2213			return (0);
2214	}
2215	return (1);
2216}
2217
2218/* Check if string contains a glob */
2219static int
2220isglobstr(const char *string)
2221{
2222	char chr;
2223
2224	while ((chr = *string++)) {
2225		if (chr == '*' || chr == '?' || chr == '[')
2226			return (1);
2227	}
2228	return (0);
2229}
2230
2231/*
2232 * Save the active log file under a new name.  A link to the new name
2233 * is the quick-and-easy way to do this.  If that fails (which it will
2234 * if the destination is on another partition), then make a copy of
2235 * the file to the new location.
2236 */
2237static void
2238savelog(char *from, char *to)
2239{
2240	FILE *src, *dst;
2241	int c, res;
2242
2243	res = link(from, to);
2244	if (res == 0)
2245		return;
2246
2247	if ((src = fopen(from, "r")) == NULL)
2248		err(1, "can't fopen %s for reading", from);
2249	if ((dst = fopen(to, "w")) == NULL)
2250		err(1, "can't fopen %s for writing", to);
2251
2252	while ((c = getc(src)) != EOF) {
2253		if ((putc(c, dst)) == EOF)
2254			err(1, "error writing to %s", to);
2255	}
2256
2257	if (ferror(src))
2258		err(1, "error reading from %s", from);
2259	if ((fclose(src)) != 0)
2260		err(1, "can't fclose %s", to);
2261	if ((fclose(dst)) != 0)
2262		err(1, "can't fclose %s", from);
2263}
2264
2265/* create one or more directory components of a path */
2266static void
2267createdir(const struct conf_entry *ent, char *dirpart)
2268{
2269	int res;
2270	char *s, *d;
2271	char mkdirpath[MAXPATHLEN];
2272	struct stat st;
2273
2274	s = dirpart;
2275	d = mkdirpath;
2276
2277	for (;;) {
2278		*d++ = *s++;
2279		if (*s != '/' && *s != '\0')
2280			continue;
2281		*d = '\0';
2282		res = lstat(mkdirpath, &st);
2283		if (res != 0) {
2284			if (noaction) {
2285				printf("\tmkdir %s\n", mkdirpath);
2286			} else {
2287				res = mkdir(mkdirpath, 0755);
2288				if (res != 0)
2289					err(1, "Error on mkdir(\"%s\") for -a",
2290					    mkdirpath);
2291			}
2292		}
2293		if (*s == '\0')
2294			break;
2295	}
2296	if (verbose) {
2297		if (ent->firstcreate)
2298			printf("Created directory '%s' for new %s\n",
2299			    dirpart, ent->log);
2300		else
2301			printf("Created directory '%s' for -a\n", dirpart);
2302	}
2303}
2304
2305/*
2306 * Create a new log file, destroying any currently-existing version
2307 * of the log file in the process.  If the caller wants a backup copy
2308 * of the file to exist, they should call 'link(logfile,logbackup)'
2309 * before calling this routine.
2310 */
2311void
2312createlog(const struct conf_entry *ent)
2313{
2314	int fd, failed;
2315	struct stat st;
2316	char *realfile, *slash, tempfile[MAXPATHLEN];
2317
2318	fd = -1;
2319	realfile = ent->log;
2320
2321	/*
2322	 * If this log file is being created for the first time (-C option),
2323	 * then it may also be true that the parent directory does not exist
2324	 * yet.  Check, and create that directory if it is missing.
2325	 */
2326	if (ent->firstcreate) {
2327		strlcpy(tempfile, realfile, sizeof(tempfile));
2328		slash = strrchr(tempfile, '/');
2329		if (slash != NULL) {
2330			*slash = '\0';
2331			failed = stat(tempfile, &st);
2332			if (failed && errno != ENOENT)
2333				err(1, "Error on stat(%s)", tempfile);
2334			if (failed)
2335				createdir(ent, tempfile);
2336			else if (!S_ISDIR(st.st_mode))
2337				errx(1, "%s exists but is not a directory",
2338				    tempfile);
2339		}
2340	}
2341
2342	/*
2343	 * First create an unused filename, so it can be chown'ed and
2344	 * chmod'ed before it is moved into the real location.  mkstemp
2345	 * will create the file mode=600 & owned by us.  Note that all
2346	 * temp files will have a suffix of '.z<something>'.
2347	 */
2348	strlcpy(tempfile, realfile, sizeof(tempfile));
2349	strlcat(tempfile, ".zXXXXXX", sizeof(tempfile));
2350	if (noaction)
2351		printf("\tmktemp %s\n", tempfile);
2352	else {
2353		fd = mkstemp(tempfile);
2354		if (fd < 0)
2355			err(1, "can't mkstemp logfile %s", tempfile);
2356
2357		/*
2358		 * Add status message to what will become the new log file.
2359		 */
2360		if (!(ent->flags & CE_BINARY)) {
2361			if (log_trim(tempfile, ent))
2362				err(1, "can't add status message to log");
2363		}
2364	}
2365
2366	/* Change the owner/group, if we are supposed to */
2367	if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2368		if (noaction)
2369			printf("\tchown %u:%u %s\n", ent->uid, ent->gid,
2370			    tempfile);
2371		else {
2372			failed = fchown(fd, ent->uid, ent->gid);
2373			if (failed)
2374				err(1, "can't fchown temp file %s", tempfile);
2375		}
2376	}
2377
2378	/* Turn on NODUMP if it was requested in the config-file. */
2379	if (ent->flags & CE_NODUMP) {
2380		if (noaction)
2381			printf("\tchflags nodump %s\n", tempfile);
2382		else {
2383			failed = fchflags(fd, UF_NODUMP);
2384			if (failed) {
2385				warn("log_trim: fchflags(NODUMP)");
2386			}
2387		}
2388	}
2389
2390	/*
2391	 * Note that if the real logfile still exists, and if the call
2392	 * to rename() fails, then "neither the old file nor the new
2393	 * file shall be changed or created" (to quote the standard).
2394	 * If the call succeeds, then the file will be replaced without
2395	 * any window where some other process might find that the file
2396	 * did not exist.
2397	 * XXX - ? It may be that for some error conditions, we could
2398	 *	retry by first removing the realfile and then renaming.
2399	 */
2400	if (noaction) {
2401		printf("\tchmod %o %s\n", ent->permissions, tempfile);
2402		printf("\tmv %s %s\n", tempfile, realfile);
2403	} else {
2404		failed = fchmod(fd, ent->permissions);
2405		if (failed)
2406			err(1, "can't fchmod temp file '%s'", tempfile);
2407		failed = rename(tempfile, realfile);
2408		if (failed)
2409			err(1, "can't mv %s to %s", tempfile, realfile);
2410	}
2411
2412	if (fd >= 0)
2413		close(fd);
2414}
2415
2416/*
2417 * Change the attributes of a given filename to what was specified in
2418 * the newsyslog.conf entry.  This routine is only called for files
2419 * that newsyslog expects that it has created, and thus it is a fatal
2420 * error if this routine finds that the file does not exist.
2421 */
2422static void
2423change_attrs(const char *fname, const struct conf_entry *ent)
2424{
2425	int failed;
2426
2427	if (noaction) {
2428		printf("\tchmod %o %s\n", ent->permissions, fname);
2429
2430		if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1)
2431			printf("\tchown %u:%u %s\n",
2432			    ent->uid, ent->gid, fname);
2433
2434		if (ent->flags & CE_NODUMP)
2435			printf("\tchflags nodump %s\n", fname);
2436		return;
2437	}
2438
2439	failed = chmod(fname, ent->permissions);
2440	if (failed) {
2441		if (errno != EPERM)
2442			err(1, "chmod(%s) in change_attrs", fname);
2443		warn("change_attrs couldn't chmod(%s)", fname);
2444	}
2445
2446	if (ent->uid != (uid_t)-1 || ent->gid != (gid_t)-1) {
2447		failed = chown(fname, ent->uid, ent->gid);
2448		if (failed)
2449			warn("can't chown %s", fname);
2450	}
2451
2452	if (ent->flags & CE_NODUMP) {
2453		failed = chflags(fname, UF_NODUMP);
2454		if (failed)
2455			warn("can't chflags %s NODUMP", fname);
2456	}
2457}
2458