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