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