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