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