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