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