xref: /titanic_44/usr/src/cmd/logadm/main.c (revision 9dd0f810214fdc8e1af881a9a5c4b6927629ff9e)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  *
25  * logadm/main.c -- main routines for logadm
26  *
27  * this program is 90% argument processing, 10% actions...
28  */
29 
30 #pragma ident	"%Z%%M%	%I%	%E% SMI"
31 
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <unistd.h>
35 #include <strings.h>
36 #include <libintl.h>
37 #include <locale.h>
38 #include <sys/types.h>
39 #include <sys/stat.h>
40 #include <sys/wait.h>
41 #include <sys/filio.h>
42 #include <time.h>
43 #include "err.h"
44 #include "lut.h"
45 #include "fn.h"
46 #include "opts.h"
47 #include "conf.h"
48 #include "glob.h"
49 #include "kw.h"
50 
51 /* forward declarations for functions in this file */
52 static void usage(const char *msg);
53 static void commajoin(const char *lhs, void *rhs, void *arg);
54 static void doaftercmd(const char *lhs, void *rhs, void *arg);
55 static void dologname(struct fn *fnp, struct opts *clopts);
56 static boolean_t rotatelog(struct fn *fnp, struct opts *opts);
57 static void rotateto(struct fn *fnp, struct opts *opts, int n,
58     struct fn *recentlog, boolean_t isgz);
59 static void do_delayed_gzip(const char *lhs, void *rhs, void *arg);
60 static void expirefiles(struct fn *fnp, struct opts *opts);
61 static void dorm(struct opts *opts, const char *msg, struct fn *fnp);
62 static void docmd(struct opts *opts, const char *msg, const char *cmd,
63     const char *arg1, const char *arg2, const char *arg3);
64 
65 /* our configuration file, unless otherwise specified by -f */
66 static char *Default_conffile = "/etc/logadm.conf";
67 
68 /* default pathnames to the commands we invoke */
69 static char *Sh = "/bin/sh";
70 static char *Mv = "/bin/mv";
71 static char *Cp = "/bin/cp";
72 static char *Rm = "/bin/rm";
73 static char *Touch = "/bin/touch";
74 static char *Chmod = "/bin/chmod";
75 static char *Chown = "/bin/chown";
76 static char *Gzip = "/bin/gzip";
77 static char *Mkdir = "/bin/mkdir";
78 
79 /* return from time(0), gathered early on to avoid slewed timestamps */
80 time_t Now;
81 
82 /* list of before commands that have been executed */
83 static struct lut *Beforecmds;
84 
85 /* list of after commands to execute before exiting */
86 static struct lut *Aftercmds;
87 
88 /* list of conffile entry names that are considered "done" */
89 static struct lut *Donenames;
90 
91 /* A list of names of files to be gzipped */
92 static struct lut *Gzipnames = NULL;
93 
94 /* table that drives argument parsing */
95 static struct optinfo Opttable[] = {
96 	{ "e", OPTTYPE_STRING,	NULL,			OPTF_CLI|OPTF_CONF },
97 	{ "f", OPTTYPE_STRING,	NULL,			OPTF_CLI },
98 	{ "h", OPTTYPE_BOOLEAN,	NULL,			OPTF_CLI },
99 	{ "l", OPTTYPE_BOOLEAN, NULL,			OPTF_CLI|OPTF_CONF },
100 	{ "N", OPTTYPE_BOOLEAN,	NULL,			OPTF_CLI|OPTF_CONF },
101 	{ "n", OPTTYPE_BOOLEAN,	NULL,			OPTF_CLI },
102 	{ "r", OPTTYPE_BOOLEAN,	NULL,			OPTF_CLI },
103 	{ "V", OPTTYPE_BOOLEAN,	NULL,			OPTF_CLI },
104 	{ "v", OPTTYPE_BOOLEAN,	NULL,			OPTF_CLI },
105 	{ "w", OPTTYPE_STRING,	NULL,			OPTF_CLI },
106 	{ "p", OPTTYPE_INT,	opts_parse_seconds,	OPTF_CLI|OPTF_CONF },
107 	{ "P", OPTTYPE_INT,	opts_parse_ctime,	OPTF_CLI|OPTF_CONF },
108 	{ "s", OPTTYPE_INT,	opts_parse_bytes,	OPTF_CLI|OPTF_CONF },
109 	{ "a", OPTTYPE_STRING,	NULL,			OPTF_CLI|OPTF_CONF },
110 	{ "b", OPTTYPE_STRING,	NULL,			OPTF_CLI|OPTF_CONF },
111 	{ "c", OPTTYPE_BOOLEAN, NULL,			OPTF_CLI|OPTF_CONF },
112 	{ "g", OPTTYPE_STRING,	NULL,			OPTF_CLI|OPTF_CONF },
113 	{ "m", OPTTYPE_INT,	opts_parse_atopi,	OPTF_CLI|OPTF_CONF },
114 	{ "M", OPTTYPE_STRING,	NULL,			OPTF_CLI|OPTF_CONF },
115 	{ "o", OPTTYPE_STRING,	NULL,			OPTF_CLI|OPTF_CONF },
116 	{ "R", OPTTYPE_STRING,	NULL,			OPTF_CLI|OPTF_CONF },
117 	{ "t", OPTTYPE_STRING,	NULL,			OPTF_CLI|OPTF_CONF },
118 	{ "z", OPTTYPE_INT,	opts_parse_atopi,	OPTF_CLI|OPTF_CONF },
119 	{ "A", OPTTYPE_INT,	opts_parse_seconds,	OPTF_CLI|OPTF_CONF },
120 	{ "C", OPTTYPE_INT,	opts_parse_atopi,	OPTF_CLI|OPTF_CONF },
121 	{ "E", OPTTYPE_STRING,	NULL,			OPTF_CLI|OPTF_CONF },
122 	{ "S", OPTTYPE_INT,	opts_parse_bytes,	OPTF_CLI|OPTF_CONF },
123 	{ "T", OPTTYPE_STRING,	NULL,			OPTF_CLI|OPTF_CONF },
124 };
125 
126 /*
127  * only the "fhnVv" options are allowed in the first form of this command,
128  * so this defines the list of options that are an error in they appear
129  * in the first form.  In other words, it is not allowed to run logadm
130  * with any of these options unless at least one logname is also provided.
131  */
132 #define	OPTIONS_NOT_FIRST_FORM	"eNrwpPsabcglmoRtzACEST"
133 
134 /* text that we spew with the -h flag */
135 #define	HELP1 \
136 "Usage: logadm [options]\n"\
137 "       (processes all entries in /etc/logadm.conf or conffile given by -f)\n"\
138 "   or: logadm [options] logname...\n"\
139 "       (processes the given lognames)\n"\
140 "\n"\
141 "General options:\n"\
142 "        -e mailaddr     mail errors to given address\n"\
143 "        -f conffile     use conffile instead of /etc/logadm.conf\n"\
144 "        -h              display help\n"\
145 "        -N              not an error if log file nonexistent\n"\
146 "        -n              show actions, don't perform them\n"\
147 "        -r              remove logname entry from conffile\n"\
148 "        -V              ensure conffile entries exist, correct\n"\
149 "        -v              print info about actions happening\n"\
150 "        -w entryname    write entry to config file\n"\
151 "\n"\
152 "Options which control when a logfile is rotated:\n"\
153 "(default is: -s1b -p1w if no -s or -p)\n"\
154 "        -p period       only rotate if period passed since last rotate\n"\
155 "        -P timestamp    used to store rotation date in conffile\n"\
156 "        -s size         only rotate if given size or greater\n"\
157 "\n"
158 #define	HELP2 \
159 "Options which control how a logfile is rotated:\n"\
160 "(default is: -t '$file.$n', owner/group/mode taken from log file)\n"\
161 "        -a cmd          execute cmd after taking actions\n"\
162 "        -b cmd          execute cmd before taking actions\n"\
163 "        -c              copy & truncate logfile, don't rename\n"\
164 "        -g group        new empty log file group\n"\
165 "        -l              rotate log file with local time rather than UTC\n"\
166 "        -m mode         new empty log file mode\n"\
167 "        -M cmd          execute cmd to rotate the log file\n"\
168 "        -o owner        new empty log file owner\n"\
169 "        -R cmd          run cmd on file after rotate\n"\
170 "        -t template     template for naming old logs\n"\
171 "        -z count        gzip old logs except most recent count\n"\
172 "\n"\
173 "Options which control the expiration of old logfiles:\n"\
174 "(default is: -C10 if no -A, -C, or -S)\n"\
175 "        -A age          expire logs older than age\n"\
176 "        -C count        expire old logs until count remain\n"\
177 "        -E cmd          run cmd on file to expire\n"\
178 "        -S size         expire until space used is below size \n"\
179 "        -T pattern      pattern for finding old logs\n"
180 
181 /*
182  * main -- where it all begins
183  */
184 /*ARGSUSED*/
185 int
186 main(int argc, char *argv[])
187 {
188 	struct opts *clopts;		/* from parsing command line */
189 	const char *conffile;		/* our configuration file */
190 	struct fn_list *lognames;	/* list of lognames we're processing */
191 	struct fn *fnp;
192 	char *val;
193 	char *buf;
194 
195 	(void) setlocale(LC_ALL, "");
196 
197 #if !defined(TEXT_DOMAIN)
198 #define	TEXT_DOMAIN "SYS_TEST"	/* only used if Makefiles don't define it */
199 #endif
200 
201 	(void) textdomain(TEXT_DOMAIN);
202 
203 	/* we only print times into the conffile, so make them uniform */
204 	(void) setlocale(LC_TIME, "C");
205 
206 	/* give our name to error routines & skip it for arg parsing */
207 	err_init(*argv++);
208 	(void) setlinebuf(stdout);
209 
210 	if (putenv("PATH=/bin"))
211 		err(EF_SYS, "putenv PATH");
212 	if (putenv("TZ=UTC"))
213 		err(EF_SYS, "putenv TZ");
214 	tzset();
215 
216 	(void) umask(0);
217 
218 	Now = time(0);
219 
220 	/* check for (undocumented) debugging environment variables */
221 	if (val = getenv("_LOGADM_DEFAULT_CONFFILE"))
222 		Default_conffile = val;
223 	if (val = getenv("_LOGADM_DEBUG"))
224 		Debug = atoi(val);
225 	if (val = getenv("_LOGADM_SH"))
226 		Sh = val;
227 	if (val = getenv("_LOGADM_MV"))
228 		Mv = val;
229 	if (val = getenv("_LOGADM_CP"))
230 		Cp = val;
231 	if (val = getenv("_LOGADM_RM"))
232 		Rm = val;
233 	if (val = getenv("_LOGADM_TOUCH"))
234 		Touch = val;
235 	if (val = getenv("_LOGADM_CHMOD"))
236 		Chmod = val;
237 	if (val = getenv("_LOGADM_CHOWN"))
238 		Chown = val;
239 	if (val = getenv("_LOGADM_GZIP"))
240 		Gzip = val;
241 	if (val = getenv("_LOGADM_MKDIR"))
242 		Mkdir = val;
243 
244 	opts_init(Opttable, sizeof (Opttable) / sizeof (struct optinfo));
245 
246 	/* parse command line arguments */
247 	if (SETJMP)
248 		usage("bailing out due to command line errors");
249 	else
250 		clopts = opts_parse(argv, OPTF_CLI);
251 
252 	if (Debug) {
253 		(void) fprintf(stderr, "command line opts:");
254 		opts_print(clopts, stderr, NULL);
255 		(void) fprintf(stderr, "\n");
256 	}
257 
258 	/*
259 	 * There are many moods of logadm:
260 	 *
261 	 *	1. "-h" for help was given.  We spew a canned help
262 	 *	   message and exit, regardless of any other options given.
263 	 *
264 	 *	2. "-r" or "-w" asking us to write to the conffile.  Lots
265 	 *	   of argument checking, then we make the change to conffile
266 	 *	   and exit.  (-r processing actually happens in dologname().)
267 	 *
268 	 *	3. "-V" to search/verify the conffile was given.  We do
269 	 *	   the appropriate run through the conffile and exit.
270 	 *	   (-V processing actually happens in dologname().)
271 	 *
272 	 *	4. No lognames were given, so we're being asked to go through
273 	 *	   every entry in conffile.  We verify that only the options
274 	 *	   that make sense for this form of the command are present
275 	 *	   and fall into the main processing loop below.
276 	 *
277 	 *	5. lognames were given, so we fall into the main processing
278 	 *	   loop below to work our way through them.
279 	 *
280 	 * The last two cases are where the option processing gets more
281 	 * complex.  Each time around the main processing loop, we're
282 	 * in one of these cases:
283 	 *
284 	 *	A. No cmdargs were found (we're in case 4), the entry
285 	 *	   in conffile supplies no log file names, so the entry
286 	 *	   name itself is the logfile name (or names, if it globs
287 	 *	   to multiple file names).
288 	 *
289 	 *	B. No cmdargs were found (we're in case 4), the entry
290 	 *	   in conffile gives log file names that we then loop
291 	 *	   through and rotate/expire.  In this case, the entry
292 	 *	   name is specifically NOT one of the log file names.
293 	 *
294 	 *	C. We're going through the cmdargs (we're in case 5),
295 	 *	   the entry in conffile either doesn't exist or it exists
296 	 *	   but supplies no log file names, so the cmdarg itself
297 	 *	   is the log file name.
298 	 *
299 	 *	D. We're going through the cmdargs (we're in case 5),
300 	 *	   a matching entry in conffile supplies log file names
301 	 *	   that we then loop through and rotate/expire.  In this
302 	 *	   case the entry name is specifically NOT one of the log
303 	 *	   file names.
304 	 *
305 	 * As we're doing all this, any options given on the command line
306 	 * override any found in the conffile, and we apply the defaults
307 	 * for rotation conditions and expiration conditions, etc. at the
308 	 * last opportunity, when we're sure they haven't been overridden
309 	 * by an option somewhere along the way.
310 	 *
311 	 */
312 
313 	/* help option overrides anything else */
314 	if (opts_count(clopts, "h")) {
315 		(void) fputs(HELP1, stderr);
316 		(void) fputs(HELP2, stderr);
317 		err_done(0);
318 		/*NOTREACHED*/
319 	}
320 
321 	/* detect illegal option combinations */
322 	if (opts_count(clopts, "rwV") > 1)
323 		usage("Only one of -r, -w, or -V may be used at a time.");
324 	if (opts_count(clopts, "cM") > 1)
325 		usage("Only one of -c or -M may be used at a time.");
326 
327 	/* arrange for error output to be mailed if clopts includes -e */
328 	if (opts_count(clopts, "e"))
329 		err_mailto(opts_optarg(clopts, "e"));
330 
331 	/* this implements the default conffile */
332 	if ((conffile = opts_optarg(clopts, "f")) == NULL)
333 		conffile = Default_conffile;
334 	if (opts_count(clopts, "v"))
335 		(void) out("# loading %s\n", conffile);
336 	conf_open(conffile, opts_count(clopts, "Vn") == 0);
337 
338 	/* handle conffile write option */
339 	if (opts_count(clopts, "w")) {
340 		if (Debug)
341 			(void) fprintf(stderr,
342 			    "main: add/replace conffile entry: <%s>\n",
343 			    opts_optarg(clopts, "w"));
344 		conf_replace(opts_optarg(clopts, "w"), clopts);
345 		conf_close(clopts);
346 		err_done(0);
347 		/*NOTREACHED*/
348 	}
349 
350 	/*
351 	 * lognames is either a list supplied on the command line,
352 	 * or every entry in the conffile if none were supplied.
353 	 */
354 	lognames = opts_cmdargs(clopts);
355 	if (fn_list_empty(lognames)) {
356 		/*
357 		 * being asked to do all entries in conffile
358 		 *
359 		 * check to see if any options were given that only
360 		 * make sense when lognames are given specifically
361 		 * on the command line.
362 		 */
363 		if (opts_count(clopts, OPTIONS_NOT_FIRST_FORM))
364 			usage("some options require logname argument");
365 		if (Debug)
366 			(void) fprintf(stderr,
367 			    "main: run all entries in conffile\n");
368 		lognames = conf_entries();
369 	}
370 
371 	/* foreach logname... */
372 	fn_list_rewind(lognames);
373 	while ((fnp = fn_list_next(lognames)) != NULL) {
374 		buf = fn_s(fnp);
375 		if (buf != NULL && lut_lookup(Donenames, buf) != NULL) {
376 			if (Debug)
377 				(void) fprintf(stderr,
378 				    "main: logname already done: <%s>\n",
379 				    buf);
380 			continue;
381 		}
382 		if (buf != NULL && SETJMP)
383 			err(EF_FILE, "bailing out on logname \"%s\" "
384 			    "due to errors", buf);
385 		else
386 			dologname(fnp, clopts);
387 	}
388 
389 	/* execute any after commands */
390 	lut_walk(Aftercmds, doaftercmd, clopts);
391 
392 	/* execute any gzip commands */
393 	lut_walk(Gzipnames, do_delayed_gzip, clopts);
394 	lut_free(Gzipnames, free);
395 	Gzipnames = NULL;
396 
397 	/* write out any conffile changes */
398 	conf_close(clopts);
399 
400 	err_done(0);
401 	/*NOTREACHED*/
402 	return (0);	/* for lint's little mind */
403 }
404 
405 /* spew a message, then a usage message, then exit */
406 static void
407 usage(const char *msg)
408 {
409 	if (msg)
410 		err(0, "%s\nUse \"logadm -h\" for help.", msg);
411 	else
412 		err(EF_RAW, "Use \"logadm -h\" for help.\n");
413 }
414 
415 /* helper function used by doaftercmd() to join mail addrs with commas */
416 /*ARGSUSED1*/
417 static void
418 commajoin(const char *lhs, void *rhs, void *arg)
419 {
420 	struct fn *fnp = (struct fn *)arg;
421 	char *buf;
422 
423 	buf = fn_s(fnp);
424 	if (buf != NULL && *buf)
425 		fn_putc(fnp, ',');
426 	fn_puts(fnp, lhs);
427 }
428 
429 /* helper function used by main() to run "after" commands */
430 static void
431 doaftercmd(const char *lhs, void *rhs, void *arg)
432 {
433 	struct opts *opts = (struct opts *)arg;
434 	struct lut *addrs = (struct lut *)rhs;
435 
436 	if (addrs) {
437 		struct fn *fnp = fn_new(NULL);
438 
439 		/*
440 		 * addrs contains list of email addrs that should get
441 		 * the error output when this after command is executed.
442 		 */
443 		lut_walk(addrs, commajoin, fnp);
444 		err_mailto(fn_s(fnp));
445 	}
446 
447 	docmd(opts, "-a cmd", Sh, "-c", lhs, NULL);
448 }
449 
450 /* perform delayed gzip */
451 
452 static void
453 do_delayed_gzip(const char *lhs, void *rhs, void *arg)
454 {
455 	struct opts *opts = (struct opts *)arg;
456 
457 	if (rhs == NULL) {
458 		if (Debug) {
459 			(void) fprintf(stderr, "do_delayed_gzip: not gzipping "
460 				"expired file <%s>\n", lhs);
461 		}
462 		return;
463 	}
464 	docmd(opts, "compress old log (-z flag)", Gzip, "-f", lhs, NULL);
465 }
466 
467 
468 /* main logname processing */
469 static void
470 dologname(struct fn *fnp, struct opts *clopts)
471 {
472 	const char *logname = fn_s(fnp);
473 	struct opts *cfopts;
474 	struct opts *allopts;
475 	struct fn_list *logfiles;
476 	struct fn_list *globbedfiles;
477 	struct fn *nextfnp;
478 
479 	/* look up options set by config file */
480 	cfopts = conf_opts(logname);
481 
482 	if (opts_count(clopts, "v"))
483 		(void) out("# processing logname: %s\n", logname);
484 
485 	if (Debug) {
486 		if (logname != NULL)
487 			(void) fprintf(stderr, "dologname: logname <%s>\n",
488 			    logname);
489 		(void) fprintf(stderr, "conffile opts:");
490 		opts_print(cfopts, stderr, NULL);
491 		(void) fprintf(stderr, "\n");
492 	}
493 
494 	/* handle conffile lookup option */
495 	if (opts_count(clopts, "V")) {
496 		/* lookup an entry in conffile */
497 		if (Debug)
498 			(void) fprintf(stderr,
499 			    "dologname: lookup conffile entry\n");
500 		if (conf_lookup(logname)) {
501 			opts_printword(logname, stdout);
502 			opts_print(cfopts, stdout, NULL);
503 			(void) out("\n");
504 		} else
505 			err_exitcode(1);
506 		return;
507 	}
508 
509 	/* handle conffile removal option */
510 	if (opts_count(clopts, "r")) {
511 		if (Debug)
512 			(void) fprintf(stderr,
513 			    "dologname: remove conffile entry\n");
514 		if (conf_lookup(logname))
515 			conf_replace(logname, NULL);
516 		else
517 			err_exitcode(1);
518 		return;
519 	}
520 
521 	/* generate combined options */
522 	allopts = opts_merge(cfopts, clopts);
523 
524 	/* arrange for error output to be mailed if allopts includes -e */
525 	if (opts_count(allopts, "e"))
526 		err_mailto(opts_optarg(allopts, "e"));
527 	else
528 		err_mailto(NULL);
529 
530 	/* this implements the default rotation rules */
531 	if (opts_count(allopts, "sp") == 0) {
532 		if (opts_count(clopts, "v"))
533 			(void) out(
534 			    "#     using default rotate rules: -s1b -p1w\n");
535 		(void) opts_set(allopts, "s", "1b");
536 		(void) opts_set(allopts, "p", "1w");
537 	}
538 
539 	/* this implements the default expiration rules */
540 	if (opts_count(allopts, "ACS") == 0) {
541 		if (opts_count(clopts, "v"))
542 			(void) out("#     using default expire rule: -C10\n");
543 		(void) opts_set(allopts, "C", "10");
544 	}
545 
546 	/* this implements the default template */
547 	if (opts_count(allopts, "t") == 0) {
548 		if (opts_count(clopts, "v"))
549 			(void) out("#     using default template: $file.$n\n");
550 		(void) opts_set(allopts, "t", "$file.$n");
551 	}
552 
553 	if (Debug) {
554 		(void) fprintf(stderr, "merged opts:");
555 		opts_print(allopts, stderr, NULL);
556 		(void) fprintf(stderr, "\n");
557 	}
558 
559 	/*
560 	 * if the conffile entry supplied log file names, then
561 	 * logname is NOT one of the log file names (it was just
562 	 * the entry name in conffile).
563 	 */
564 	logfiles = opts_cmdargs(cfopts);
565 	if (Debug) {
566 		char *buf;
567 		(void) fprintf(stderr, "dologname: logfiles from cfopts:\n");
568 		fn_list_rewind(logfiles);
569 		while ((nextfnp = fn_list_next(logfiles)) != NULL)
570 			buf = fn_s(nextfnp);
571 			if (buf != NULL)
572 				(void) fprintf(stderr, "    <%s>\n", buf);
573 	}
574 	if (fn_list_empty(logfiles))
575 		globbedfiles = glob_glob(fnp);
576 	else
577 		globbedfiles = glob_glob_list(logfiles);
578 
579 	/* go through the list produced by glob expansion */
580 	fn_list_rewind(globbedfiles);
581 	while ((nextfnp = fn_list_next(globbedfiles)) != NULL)
582 		if (rotatelog(nextfnp, allopts))
583 			expirefiles(nextfnp, allopts);
584 
585 	fn_list_free(globbedfiles);
586 	opts_free(allopts);
587 }
588 
589 
590 /* absurdly long buffer lengths for holding user/group/mode strings */
591 #define	TIMESTRMAX	100
592 #define	MAXATTR		100
593 
594 /* rotate a log file if necessary, returns true if ok to go on to expire step */
595 static boolean_t
596 rotatelog(struct fn *fnp, struct opts *opts)
597 {
598 	char *fname = fn_s(fnp);
599 	struct stat stbuf;
600 	char nowstr[TIMESTRMAX];
601 	struct fn *recentlog = fn_new(NULL);	/* for -R cmd */
602 	char ownerbuf[MAXATTR];
603 	char groupbuf[MAXATTR];
604 	char modebuf[MAXATTR];
605 	const char *owner;
606 	const char *group;
607 	const char *mode;
608 
609 	if (Debug && fname != NULL)
610 		(void) fprintf(stderr, "rotatelog: fname <%s>\n", fname);
611 
612 	if (opts_count(opts, "p") && opts_optarg_int(opts, "p") == OPTP_NEVER)
613 		return (B_TRUE);	/* "-p never" forced no rotate */
614 
615 	/* prepare the keywords */
616 	kw_init(fnp, NULL);
617 	if (Debug > 1) {
618 		(void) fprintf(stderr, "rotatelog keywords:\n");
619 		kw_print(stderr);
620 	}
621 
622 	if (lstat(fname, &stbuf) < 0) {
623 		if (opts_count(opts, "N"))
624 			return (1);
625 		err(EF_WARN|EF_SYS, "%s", fname);
626 		return (B_FALSE);
627 	}
628 
629 	if ((stbuf.st_mode & S_IFMT) == S_IFLNK) {
630 		err(EF_WARN, "%s is a symlink", fname);
631 		return (B_FALSE);
632 	}
633 
634 	if ((stbuf.st_mode & S_IFMT) != S_IFREG) {
635 		err(EF_WARN, "%s is not a regular file", fname);
636 		return (B_FALSE);
637 	}
638 
639 	/* see if size condition is present, and return if not met */
640 	if (opts_count(opts, "s") && stbuf.st_size < opts_optarg_int(opts, "s"))
641 		return (B_TRUE);
642 
643 	/* see if age condition is present, and return if not met */
644 	if (opts_count(opts, "p")) {
645 		off_t when = opts_optarg_int(opts, "p");
646 		struct opts *cfopts;
647 
648 		/* unless rotate forced by "-p now", see if period has passed */
649 		if (when != OPTP_NOW) {
650 			/*
651 			 * "when" holds the number of seconds that must have
652 			 * passed since the last time this log was rotated.
653 			 * of course, running logadm can take a little time
654 			 * (typically a second or two, but longer if the
655 			 * conffile has lots of stuff in it) and that amount
656 			 * of time is variable, depending on system load, etc.
657 			 * so we want to allow a little "slop" in the value of
658 			 * "when".  this way, if a log should be rotated every
659 			 * week, and the number of seconds passed is really a
660 			 * few seconds short of a week, we'll go ahead and
661 			 * rotate the log as expected.
662 			 *
663 			 */
664 			if (when >= 60 * 60)
665 				when -= 59;
666 
667 			/*
668 			 * last rotation is recorded as argument to -P,
669 			 * but if logname isn't the same as log file name
670 			 * then the timestamp would be recorded on a
671 			 * separate line in the conf file.  so if we
672 			 * haven't seen a -P already, we check to see if
673 			 * it is part of a specific entry for the log
674 			 * file name.  this handles the case where the
675 			 * logname is "apache", it supplies a log file
676 			 * name like "/var/apache/logs/[a-z]*_log",
677 			 * which expands to multiple file names.  if one
678 			 * of the file names is "/var/apache/logs/access_log"
679 			 * the the -P will be attached to a line with that
680 			 * logname in the conf file.
681 			 */
682 			if (opts_count(opts, "P")) {
683 				off_t last = opts_optarg_int(opts, "P");
684 
685 				/* return if not enough time has passed */
686 				if (Now - last < when)
687 					return (B_TRUE);
688 			} else if ((cfopts = conf_opts(fname)) != NULL &&
689 			    opts_count(cfopts, "P")) {
690 				off_t last = opts_optarg_int(cfopts, "P");
691 
692 				/*
693 				 * just checking this means this entry
694 				 * is now "done" if we're going through
695 				 * the entire conffile
696 				 */
697 				Donenames = lut_add(Donenames, fname, "1");
698 
699 				/* return if not enough time has passed */
700 				if (Now - last < when)
701 					return (B_TRUE);
702 			}
703 		}
704 	}
705 
706 	if (Debug)
707 		(void) fprintf(stderr, "rotatelog: conditions met\n");
708 	if (opts_count(opts, "l")) {
709 		/* Change the time zone to local time zone */
710 		if (putenv("TZ="))
711 			err(EF_SYS, "putenv TZ");
712 		tzset();
713 		Now = time(0);
714 
715 		/* rename the log file */
716 		rotateto(fnp, opts, 0, recentlog, B_FALSE);
717 
718 		/* Change the time zone to UTC */
719 		if (putenv("TZ=UTC"))
720 			err(EF_SYS, "putenv TZ");
721 		tzset();
722 		Now = time(0);
723 	} else {
724 		/* rename the log file */
725 		rotateto(fnp, opts, 0, recentlog, B_FALSE);
726 	}
727 
728 	/* determine owner, group, mode for empty log file */
729 	if (opts_count(opts, "o"))
730 		(void) strlcpy(ownerbuf, opts_optarg(opts, "o"), MAXATTR);
731 	else {
732 		(void) snprintf(ownerbuf, MAXATTR, "%ld", stbuf.st_uid);
733 	}
734 	owner = ownerbuf;
735 	if (opts_count(opts, "g"))
736 		group = opts_optarg(opts, "g");
737 	else {
738 		(void) snprintf(groupbuf, MAXATTR, "%ld", stbuf.st_gid);
739 		group = groupbuf;
740 	}
741 	(void) strlcat(ownerbuf, ":", MAXATTR - strlen(ownerbuf));
742 	(void) strlcat(ownerbuf, group, MAXATTR - strlen(ownerbuf));
743 	if (opts_count(opts, "m"))
744 		mode = opts_optarg(opts, "m");
745 	else {
746 		(void) snprintf(modebuf, MAXATTR,
747 		    "%03lo", stbuf.st_mode & 0777);
748 		mode = modebuf;
749 	}
750 
751 	/* create the empty log file */
752 	docmd(opts, NULL, Touch, fname, NULL, NULL);
753 	docmd(opts, NULL, Chown, owner, fname, NULL);
754 	docmd(opts, NULL, Chmod, mode, fname, NULL);
755 
756 	/* execute post-rotation command */
757 	if (opts_count(opts, "R")) {
758 		struct fn *rawcmd = fn_new(opts_optarg(opts, "R"));
759 		struct fn *cmd = fn_new(NULL);
760 
761 		kw_init(recentlog, NULL);
762 		(void) kw_expand(rawcmd, cmd, 0, B_FALSE);
763 		docmd(opts, "-R cmd", Sh, "-c", fn_s(cmd), NULL);
764 		fn_free(rawcmd);
765 		fn_free(cmd);
766 	}
767 	fn_free(recentlog);
768 
769 	/*
770 	 * add "after" command to list of after commands.  we also record
771 	 * the email address, if any, where the error output of the after
772 	 * command should be sent.  if the after command is already on
773 	 * our list, add the email addr to the list the email addrs for
774 	 * that command (the after command will only be executed once,
775 	 * so the error output gets mailed to every address we've come
776 	 * across associated with this command).
777 	 */
778 	if (opts_count(opts, "a")) {
779 		const char *cmd = opts_optarg(opts, "a");
780 		struct lut *addrs = (struct lut *)lut_lookup(Aftercmds, cmd);
781 		if (opts_count(opts, "e"))
782 			addrs = lut_add(addrs, opts_optarg(opts, "e"), NULL);
783 		Aftercmds = lut_add(Aftercmds, opts_optarg(opts, "a"), addrs);
784 	}
785 
786 	/* record the rotation date */
787 	(void) strftime(nowstr, sizeof (nowstr),
788 	    "%a %b %e %T %Y", gmtime(&Now));
789 	if (opts_count(opts, "v") && fname != NULL)
790 		(void) out("#     recording rotation date %s for %s\n",
791 		    nowstr, fname);
792 	conf_set(fname, "P", STRDUP(nowstr));
793 	Donenames = lut_add(Donenames, fname, "1");
794 	return (B_TRUE);
795 }
796 
797 /* rotate files "up" according to current template */
798 static void
799 rotateto(struct fn *fnp, struct opts *opts, int n, struct fn *recentlog,
800     boolean_t isgz)
801 {
802 	struct fn *template = fn_new(opts_optarg(opts, "t"));
803 	struct fn *newfile = fn_new(NULL);
804 	struct fn *dirname;
805 	int hasn;
806 	struct stat stbuf;
807 	char *buf1;
808 	char *buf2;
809 
810 	/* expand template to figure out new filename */
811 	hasn = kw_expand(template, newfile, n, isgz);
812 
813 	buf1 = fn_s(fnp);
814 	buf2 = fn_s(newfile);
815 
816 	if (Debug)
817 		if (buf1 != NULL && buf2 != NULL) {
818 			(void) fprintf(stderr, "rotateto: %s -> %s (%d)\n",
819 			    buf1, buf2, n);
820 		}
821 	/* if filename is there already, rotate "up" */
822 	if (hasn && lstat(buf2, &stbuf) != -1)
823 		rotateto(newfile, opts, n + 1, recentlog, isgz);
824 	else if (hasn && opts_count(opts, "z")) {
825 		struct fn *gzfnp = fn_dup(newfile);
826 		/*
827 		 * since we're compressing old files, see if we
828 		 * about to rotate into one.
829 		 */
830 		fn_puts(gzfnp, ".gz");
831 		if (lstat(fn_s(gzfnp), &stbuf) != -1)
832 			rotateto(gzfnp, opts, n + 1, recentlog, B_TRUE);
833 		fn_free(gzfnp);
834 	}
835 
836 	/* first time through run "before" cmd if not run already */
837 	if (n == 0 && opts_count(opts, "b")) {
838 		const char *cmd = opts_optarg(opts, "b");
839 
840 		if (lut_lookup(Beforecmds, cmd) == NULL) {
841 			docmd(opts, "-b cmd", Sh, "-c", cmd, NULL);
842 			Beforecmds = lut_add(Beforecmds, cmd, "1");
843 		}
844 	}
845 
846 	/* ensure destination directory exists */
847 	dirname = fn_dirname(newfile);
848 	docmd(opts, "verify directory exists", Mkdir, "-p",
849 	    fn_s(dirname), NULL);
850 	fn_free(dirname);
851 
852 	/* do the rename */
853 	if (opts_count(opts, "c")) {
854 		docmd(opts, "rotate log file via copy (-c flag)",
855 		    Cp, "-fp", fn_s(fnp), fn_s(newfile));
856 		docmd(opts, "truncate log file (-c flag)",
857 		    Cp, "-f", "/dev/null", fn_s(fnp));
858 	} else if (n == 0 && opts_count(opts, "M")) {
859 		struct fn *rawcmd = fn_new(opts_optarg(opts, "M"));
860 		struct fn *cmd = fn_new(NULL);
861 
862 		/* use specified command to mv the log file */
863 		kw_init(fnp, newfile);
864 		(void) kw_expand(rawcmd, cmd, 0, B_FALSE);
865 		docmd(opts, "-M cmd", Sh, "-c", fn_s(cmd), NULL);
866 		fn_free(rawcmd);
867 		fn_free(cmd);
868 	} else
869 		/* common case: we call "mv" to handle the actual rename */
870 		docmd(opts, "rotate log file", Mv, "-f",
871 		    fn_s(fnp), fn_s(newfile));
872 
873 	/* first time through, gather interesting info for caller */
874 	if (n == 0)
875 		fn_renew(recentlog, fn_s(newfile));
876 }
877 
878 /* expire phase of logname processing */
879 static void
880 expirefiles(struct fn *fnp, struct opts *opts)
881 {
882 	char *fname = fn_s(fnp);
883 	struct fn *template;
884 	struct fn *pattern;
885 	struct fn_list *files;
886 	struct fn *nextfnp;
887 	off_t count;
888 	off_t size;
889 
890 	if (Debug && fname != NULL)
891 		(void) fprintf(stderr, "expirefiles: fname <%s>\n", fname);
892 
893 	/* return if no potential expire conditions */
894 	if (opts_count(opts, "zAS") == 0 && opts_optarg_int(opts, "C") == 0)
895 		return;
896 
897 	kw_init(fnp, NULL);
898 	if (Debug > 1) {
899 		(void) fprintf(stderr, "expirefiles keywords:\n");
900 		kw_print(stderr);
901 	}
902 
903 	/* see if pattern was supplied by user */
904 	if (opts_count(opts, "T")) {
905 		template = fn_new(opts_optarg(opts, "T"));
906 		pattern = glob_to_reglob(template);
907 	} else {
908 		/* nope, generate pattern based on rotation template */
909 		template = fn_new(opts_optarg(opts, "t"));
910 		pattern = fn_new(NULL);
911 		(void) kw_expand(template, pattern, -1,
912 		    opts_count(opts, "z") != 0);
913 	}
914 
915 	/* match all old log files (hopefully not any others as well!) */
916 	files = glob_reglob(pattern);
917 
918 	if (Debug) {
919 		char *buf;
920 
921 		buf = fn_s(pattern);
922 		if (buf != NULL) {
923 			(void) fprintf(stderr, "expirefiles: pattern <%s>\n",
924 			    buf);
925 		}
926 		fn_list_rewind(files);
927 		while ((nextfnp = fn_list_next(files)) != NULL)
928 			buf = fn_s(nextfnp);
929 			if (buf != NULL)
930 				(void) fprintf(stderr, "    <%s>\n", buf);
931 	}
932 
933 	/* see if count causes expiration */
934 	if ((count = opts_optarg_int(opts, "C")) > 0) {
935 		int needexpire = fn_list_count(files) - count;
936 
937 		if (Debug)
938 			(void) fprintf(stderr, "expirefiles: needexpire %d\n",
939 			    needexpire);
940 
941 		while (needexpire > 0 &&
942 		    ((nextfnp = fn_list_popoldest(files)) != NULL)) {
943 			dorm(opts, "expire by count rule", nextfnp);
944 			fn_free(nextfnp);
945 			needexpire--;
946 		}
947 	}
948 
949 	/* see if total size causes expiration */
950 	if (opts_count(opts, "S") && (size = opts_optarg_int(opts, "S")) > 0) {
951 		while (fn_list_totalsize(files) > size &&
952 		    ((nextfnp = fn_list_popoldest(files)) != NULL)) {
953 			dorm(opts, "expire by size rule", nextfnp);
954 			fn_free(nextfnp);
955 		}
956 	}
957 
958 	/* see if age causes expiration */
959 	if (opts_count(opts, "A")) {
960 		int mtime = (int)time(0) - (int)opts_optarg_int(opts, "A");
961 
962 		while ((nextfnp = fn_list_popoldest(files)) != NULL) {
963 			if (fn_getstat(nextfnp)->st_mtime < mtime) {
964 				dorm(opts, "expire by age rule", nextfnp);
965 				fn_free(nextfnp);
966 			} else {
967 				fn_free(nextfnp);
968 				break;
969 			}
970 		}
971 	}
972 
973 	/* record old log files to be gzip'ed according to -z count */
974 	if (opts_count(opts, "z")) {
975 		int zcount = (int)opts_optarg_int(opts, "z");
976 		int fcount = fn_list_count(files);
977 
978 		while (fcount > zcount &&
979 		    (nextfnp = fn_list_popoldest(files)) != NULL) {
980 			if (!fn_isgz(nextfnp)) {
981 				/*
982 				 * Don't gzip the old log file yet -
983 				 * it takes too long. Just remember that we
984 				 * need to gzip.
985 				 */
986 				if (Debug) {
987 					(void) fprintf(stderr,
988 					    "will compress %s count %d\n",
989 					    fn_s(nextfnp), fcount);
990 				}
991 				Gzipnames = lut_add(Gzipnames,
992 						fn_s(nextfnp), "1");
993 			}
994 			fn_free(nextfnp);
995 			fcount--;
996 		}
997 	}
998 
999 	fn_free(template);
1000 	fn_list_free(files);
1001 }
1002 
1003 /* execute a command to remove an expired log file */
1004 static void
1005 dorm(struct opts *opts, const char *msg, struct fn *fnp)
1006 {
1007 	if (opts_count(opts, "E")) {
1008 		struct fn *rawcmd = fn_new(opts_optarg(opts, "E"));
1009 		struct fn *cmd = fn_new(NULL);
1010 
1011 		/* user supplied cmd, expand $file */
1012 		kw_init(fnp, NULL);
1013 		(void) kw_expand(rawcmd, cmd, 0, B_FALSE);
1014 		docmd(opts, msg, Sh, "-c", fn_s(cmd), NULL);
1015 		fn_free(rawcmd);
1016 		fn_free(cmd);
1017 	} else
1018 		docmd(opts, msg, Rm, "-f", fn_s(fnp), NULL);
1019 	Gzipnames = lut_add(Gzipnames, fn_s(fnp), NULL);
1020 }
1021 
1022 /* execute a command, producing -n and -v output as necessary */
1023 static void
1024 docmd(struct opts *opts, const char *msg, const char *cmd,
1025     const char *arg1, const char *arg2, const char *arg3)
1026 {
1027 	int pid;
1028 	int errpipe[2];
1029 
1030 	/* print info about command if necessary */
1031 	if (opts_count(opts, "vn")) {
1032 		const char *simplecmd;
1033 
1034 		if ((simplecmd = strrchr(cmd, '/')) == NULL)
1035 			simplecmd = cmd;
1036 		else
1037 			simplecmd++;
1038 		(void) out("%s", simplecmd);
1039 		if (arg1)
1040 			(void) out(" %s", arg1);
1041 		if (arg2)
1042 			(void) out(" %s", arg2);
1043 		if (arg3)
1044 			(void) out(" %s", arg3);
1045 		if (msg)
1046 			(void) out(" # %s", msg);
1047 		(void) out("\n");
1048 	}
1049 
1050 	if (opts_count(opts, "n"))
1051 		return;		/* -n means don't really do it */
1052 
1053 	/*
1054 	 * run the cmd and see if it failed.  this function is *not* a
1055 	 * generic command runner -- we depend on some knowledge we
1056 	 * have about the commands we run.  first of all, we expect
1057 	 * errors to spew something to stderr, and that something is
1058 	 * typically short enough to fit into a pipe so we can wait()
1059 	 * for the command to complete and then fetch the error text
1060 	 * from the pipe.  we also expect the exit codes to make sense.
1061 	 * notice also that we only allow a command name which is an
1062 	 * absolute pathname, and two args must be supplied (the
1063 	 * second may be NULL, or they may both be NULL).
1064 	 */
1065 	if (pipe(errpipe) < 0)
1066 		err(EF_SYS, "pipe");
1067 
1068 	if ((pid = fork()) < 0)
1069 		err(EF_SYS, "fork");
1070 	else if (pid) {
1071 		int wstat;
1072 		int count;
1073 
1074 		/* parent */
1075 		(void) close(errpipe[1]);
1076 		if (waitpid(pid, &wstat, 0) < 0)
1077 			err(EF_SYS, "waitpid");
1078 
1079 		/* check for stderr output */
1080 		if (ioctl(errpipe[0], FIONREAD, &count) >= 0 && count) {
1081 			err(EF_WARN, "command failed: %s%s%s%s%s%s%s",
1082 				cmd,
1083 				(arg1) ? " " : "",
1084 				(arg1) ? arg1 : "",
1085 				(arg2) ? " " : "",
1086 				(arg2) ? arg2 : "",
1087 				(arg3) ? " " : "",
1088 				(arg3) ? arg3 : "");
1089 			err_fromfd(errpipe[0]);
1090 		} else if (WIFSIGNALED(wstat))
1091 			err(EF_WARN,
1092 			    "command died, signal %d: %s%s%s%s%s%s%s",
1093 				WTERMSIG(wstat),
1094 				cmd,
1095 				(arg1) ? " " : "",
1096 				(arg1) ? arg1 : "",
1097 				(arg2) ? " " : "",
1098 				(arg2) ? arg2 : "",
1099 				(arg3) ? " " : "",
1100 				(arg3) ? arg3 : "");
1101 		else if (WIFEXITED(wstat) && WEXITSTATUS(wstat))
1102 			err(EF_WARN,
1103 			    "command error, exit %d: %s%s%s%s%s%s%s",
1104 				WEXITSTATUS(wstat),
1105 				cmd,
1106 				(arg1) ? " " : "",
1107 				(arg1) ? arg1 : "",
1108 				(arg2) ? " " : "",
1109 				(arg2) ? arg2 : "",
1110 				(arg3) ? " " : "",
1111 				(arg3) ? arg3 : "");
1112 
1113 		(void) close(errpipe[0]);
1114 	} else {
1115 		/* child */
1116 		(void) dup2(errpipe[1], fileno(stderr));
1117 		(void) close(errpipe[0]);
1118 		(void) execl(cmd, cmd, arg1, arg2, arg3, 0);
1119 		perror(cmd);
1120 		_exit(1);
1121 	}
1122 }
1123