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