xref: /illumos-gate/usr/src/cmd/logadm/main.c (revision 48011479)
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 2007 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 
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 	char *buf;
420 
421 	buf = fn_s(fnp);
422 	if (buf != NULL && *buf)
423 		fn_putc(fnp, ',');
424 	fn_puts(fnp, lhs);
425 }
426 
427 /* helper function used by main() to run "after" commands */
428 static void
429 doaftercmd(const char *lhs, void *rhs, void *arg)
430 {
431 	struct opts *opts = (struct opts *)arg;
432 	struct lut *addrs = (struct lut *)rhs;
433 
434 	if (addrs) {
435 		struct fn *fnp = fn_new(NULL);
436 
437 		/*
438 		 * addrs contains list of email addrs that should get
439 		 * the error output when this after command is executed.
440 		 */
441 		lut_walk(addrs, commajoin, fnp);
442 		err_mailto(fn_s(fnp));
443 	}
444 
445 	docmd(opts, "-a cmd", Sh, "-c", lhs, NULL);
446 }
447 
448 /* perform delayed gzip */
449 
450 static void
451 do_delayed_gzip(const char *lhs, void *rhs, void *arg)
452 {
453 	struct opts *opts = (struct opts *)arg;
454 
455 	if (rhs == NULL) {
456 		if (Debug) {
457 			(void) fprintf(stderr, "do_delayed_gzip: not gzipping "
458 				"expired file <%s>\n", lhs);
459 		}
460 		return;
461 	}
462 	docmd(opts, "compress old log (-z flag)", Gzip, "-f", lhs, NULL);
463 }
464 
465 
466 /* main logname processing */
467 static void
468 dologname(struct fn *fnp, struct opts *clopts)
469 {
470 	const char *logname = fn_s(fnp);
471 	struct opts *cfopts;
472 	struct opts *allopts;
473 	struct fn_list *logfiles;
474 	struct fn_list *globbedfiles;
475 	struct fn *nextfnp;
476 
477 	/* look up options set by config file */
478 	cfopts = conf_opts(logname);
479 
480 	if (opts_count(clopts, "v"))
481 		(void) out("# processing logname: %s\n", logname);
482 
483 	if (Debug) {
484 		if (logname != NULL)
485 			(void) fprintf(stderr, "dologname: logname <%s>\n",
486 			    logname);
487 		(void) fprintf(stderr, "conffile opts:");
488 		opts_print(cfopts, stderr, NULL);
489 		(void) fprintf(stderr, "\n");
490 	}
491 
492 	/* handle conffile lookup option */
493 	if (opts_count(clopts, "V")) {
494 		/* lookup an entry in conffile */
495 		if (Debug)
496 			(void) fprintf(stderr,
497 			    "dologname: lookup conffile entry\n");
498 		if (conf_lookup(logname)) {
499 			opts_printword(logname, stdout);
500 			opts_print(cfopts, stdout, NULL);
501 			(void) out("\n");
502 		} else
503 			err_exitcode(1);
504 		return;
505 	}
506 
507 	/* handle conffile removal option */
508 	if (opts_count(clopts, "r")) {
509 		if (Debug)
510 			(void) fprintf(stderr,
511 			    "dologname: remove conffile entry\n");
512 		if (conf_lookup(logname))
513 			conf_replace(logname, NULL);
514 		else
515 			err_exitcode(1);
516 		return;
517 	}
518 
519 	/* generate combined options */
520 	allopts = opts_merge(cfopts, clopts);
521 
522 	/* arrange for error output to be mailed if allopts includes -e */
523 	if (opts_count(allopts, "e"))
524 		err_mailto(opts_optarg(allopts, "e"));
525 	else
526 		err_mailto(NULL);
527 
528 	/* this implements the default rotation rules */
529 	if (opts_count(allopts, "sp") == 0) {
530 		if (opts_count(clopts, "v"))
531 			(void) out(
532 			    "#     using default rotate rules: -s1b -p1w\n");
533 		(void) opts_set(allopts, "s", "1b");
534 		(void) opts_set(allopts, "p", "1w");
535 	}
536 
537 	/* this implements the default expiration rules */
538 	if (opts_count(allopts, "ACS") == 0) {
539 		if (opts_count(clopts, "v"))
540 			(void) out("#     using default expire rule: -C10\n");
541 		(void) opts_set(allopts, "C", "10");
542 	}
543 
544 	/* this implements the default template */
545 	if (opts_count(allopts, "t") == 0) {
546 		if (opts_count(clopts, "v"))
547 			(void) out("#     using default template: $file.$n\n");
548 		(void) opts_set(allopts, "t", "$file.$n");
549 	}
550 
551 	if (Debug) {
552 		(void) fprintf(stderr, "merged opts:");
553 		opts_print(allopts, stderr, NULL);
554 		(void) fprintf(stderr, "\n");
555 	}
556 
557 	/*
558 	 * if the conffile entry supplied log file names, then
559 	 * logname is NOT one of the log file names (it was just
560 	 * the entry name in conffile).
561 	 */
562 	logfiles = opts_cmdargs(cfopts);
563 	if (Debug) {
564 		char *buf;
565 		(void) fprintf(stderr, "dologname: logfiles from cfopts:\n");
566 		fn_list_rewind(logfiles);
567 		while ((nextfnp = fn_list_next(logfiles)) != NULL)
568 			buf = fn_s(nextfnp);
569 			if (buf != NULL)
570 				(void) fprintf(stderr, "    <%s>\n", buf);
571 	}
572 	if (fn_list_empty(logfiles))
573 		globbedfiles = glob_glob(fnp);
574 	else
575 		globbedfiles = glob_glob_list(logfiles);
576 
577 	/* go through the list produced by glob expansion */
578 	fn_list_rewind(globbedfiles);
579 	while ((nextfnp = fn_list_next(globbedfiles)) != NULL)
580 		if (rotatelog(nextfnp, allopts))
581 			expirefiles(nextfnp, allopts);
582 
583 	fn_list_free(globbedfiles);
584 	opts_free(allopts);
585 }
586 
587 
588 /* absurdly long buffer lengths for holding user/group/mode strings */
589 #define	TIMESTRMAX	100
590 #define	MAXATTR		100
591 
592 /* rotate a log file if necessary, returns true if ok to go on to expire step */
593 static boolean_t
594 rotatelog(struct fn *fnp, struct opts *opts)
595 {
596 	char *fname = fn_s(fnp);
597 	struct stat stbuf;
598 	char nowstr[TIMESTRMAX];
599 	struct fn *recentlog = fn_new(NULL);	/* for -R cmd */
600 	char ownerbuf[MAXATTR];
601 	char groupbuf[MAXATTR];
602 	char modebuf[MAXATTR];
603 	const char *owner;
604 	const char *group;
605 	const char *mode;
606 
607 	if (Debug && fname != NULL)
608 		(void) fprintf(stderr, "rotatelog: fname <%s>\n", fname);
609 
610 	if (opts_count(opts, "p") && opts_optarg_int(opts, "p") == OPTP_NEVER)
611 		return (B_TRUE);	/* "-p never" forced no rotate */
612 
613 	/* prepare the keywords */
614 	kw_init(fnp, NULL);
615 	if (Debug > 1) {
616 		(void) fprintf(stderr, "rotatelog keywords:\n");
617 		kw_print(stderr);
618 	}
619 
620 	if (lstat(fname, &stbuf) < 0) {
621 		if (opts_count(opts, "N"))
622 			return (1);
623 		err(EF_WARN|EF_SYS, "%s", fname);
624 		return (B_FALSE);
625 	}
626 
627 	if ((stbuf.st_mode & S_IFMT) == S_IFLNK) {
628 		err(EF_WARN, "%s is a symlink", fname);
629 		return (B_FALSE);
630 	}
631 
632 	if ((stbuf.st_mode & S_IFMT) != S_IFREG) {
633 		err(EF_WARN, "%s is not a regular file", fname);
634 		return (B_FALSE);
635 	}
636 
637 	/* see if size condition is present, and return if not met */
638 	if (opts_count(opts, "s") && stbuf.st_size < opts_optarg_int(opts, "s"))
639 		return (B_TRUE);
640 
641 	/* see if age condition is present, and return if not met */
642 	if (opts_count(opts, "p")) {
643 		off_t when = opts_optarg_int(opts, "p");
644 		struct opts *cfopts;
645 
646 		/* unless rotate forced by "-p now", see if period has passed */
647 		if (when != OPTP_NOW) {
648 			/*
649 			 * "when" holds the number of seconds that must have
650 			 * passed since the last time this log was rotated.
651 			 * of course, running logadm can take a little time
652 			 * (typically a second or two, but longer if the
653 			 * conffile has lots of stuff in it) and that amount
654 			 * of time is variable, depending on system load, etc.
655 			 * so we want to allow a little "slop" in the value of
656 			 * "when".  this way, if a log should be rotated every
657 			 * week, and the number of seconds passed is really a
658 			 * few seconds short of a week, we'll go ahead and
659 			 * rotate the log as expected.
660 			 *
661 			 */
662 			if (when >= 60 * 60)
663 				when -= 59;
664 
665 			/*
666 			 * last rotation is recorded as argument to -P,
667 			 * but if logname isn't the same as log file name
668 			 * then the timestamp would be recorded on a
669 			 * separate line in the conf file.  so if we
670 			 * haven't seen a -P already, we check to see if
671 			 * it is part of a specific entry for the log
672 			 * file name.  this handles the case where the
673 			 * logname is "apache", it supplies a log file
674 			 * name like "/var/apache/logs/[a-z]*_log",
675 			 * which expands to multiple file names.  if one
676 			 * of the file names is "/var/apache/logs/access_log"
677 			 * the the -P will be attached to a line with that
678 			 * logname in the conf file.
679 			 */
680 			if (opts_count(opts, "P")) {
681 				off_t last = opts_optarg_int(opts, "P");
682 
683 				/* return if not enough time has passed */
684 				if (Now - last < when)
685 					return (B_TRUE);
686 			} else if ((cfopts = conf_opts(fname)) != NULL &&
687 			    opts_count(cfopts, "P")) {
688 				off_t last = opts_optarg_int(cfopts, "P");
689 
690 				/*
691 				 * just checking this means this entry
692 				 * is now "done" if we're going through
693 				 * the entire conffile
694 				 */
695 				Donenames = lut_add(Donenames, fname, "1");
696 
697 				/* return if not enough time has passed */
698 				if (Now - last < when)
699 					return (B_TRUE);
700 			}
701 		}
702 	}
703 
704 	if (Debug)
705 		(void) fprintf(stderr, "rotatelog: conditions met\n");
706 	if (opts_count(opts, "l")) {
707 		/* Change the time zone to local time zone */
708 		if (putenv("TZ="))
709 			err(EF_SYS, "putenv TZ");
710 		tzset();
711 		Now = time(0);
712 
713 		/* rename the log file */
714 		rotateto(fnp, opts, 0, recentlog, B_FALSE);
715 
716 		/* Change the time zone to UTC */
717 		if (putenv("TZ=UTC"))
718 			err(EF_SYS, "putenv TZ");
719 		tzset();
720 		Now = time(0);
721 	} else {
722 		/* rename the log file */
723 		rotateto(fnp, opts, 0, recentlog, B_FALSE);
724 	}
725 
726 	/* determine owner, group, mode for empty log file */
727 	if (opts_count(opts, "o"))
728 		(void) strlcpy(ownerbuf, opts_optarg(opts, "o"), MAXATTR);
729 	else {
730 		(void) snprintf(ownerbuf, MAXATTR, "%ld", stbuf.st_uid);
731 	}
732 	owner = ownerbuf;
733 	if (opts_count(opts, "g"))
734 		group = opts_optarg(opts, "g");
735 	else {
736 		(void) snprintf(groupbuf, MAXATTR, "%ld", stbuf.st_gid);
737 		group = groupbuf;
738 	}
739 	(void) strlcat(ownerbuf, ":", MAXATTR - strlen(ownerbuf));
740 	(void) strlcat(ownerbuf, group, MAXATTR - strlen(ownerbuf));
741 	if (opts_count(opts, "m"))
742 		mode = opts_optarg(opts, "m");
743 	else {
744 		(void) snprintf(modebuf, MAXATTR,
745 		    "%03lo", stbuf.st_mode & 0777);
746 		mode = modebuf;
747 	}
748 
749 	/* create the empty log file */
750 	docmd(opts, NULL, Touch, fname, NULL, NULL);
751 	docmd(opts, NULL, Chown, owner, fname, NULL);
752 	docmd(opts, NULL, Chmod, mode, fname, NULL);
753 
754 	/* execute post-rotation command */
755 	if (opts_count(opts, "R")) {
756 		struct fn *rawcmd = fn_new(opts_optarg(opts, "R"));
757 		struct fn *cmd = fn_new(NULL);
758 
759 		kw_init(recentlog, NULL);
760 		(void) kw_expand(rawcmd, cmd, 0, B_FALSE);
761 		docmd(opts, "-R cmd", Sh, "-c", fn_s(cmd), NULL);
762 		fn_free(rawcmd);
763 		fn_free(cmd);
764 	}
765 	fn_free(recentlog);
766 
767 	/*
768 	 * add "after" command to list of after commands.  we also record
769 	 * the email address, if any, where the error output of the after
770 	 * command should be sent.  if the after command is already on
771 	 * our list, add the email addr to the list the email addrs for
772 	 * that command (the after command will only be executed once,
773 	 * so the error output gets mailed to every address we've come
774 	 * across associated with this command).
775 	 */
776 	if (opts_count(opts, "a")) {
777 		const char *cmd = opts_optarg(opts, "a");
778 		struct lut *addrs = (struct lut *)lut_lookup(Aftercmds, cmd);
779 		if (opts_count(opts, "e"))
780 			addrs = lut_add(addrs, opts_optarg(opts, "e"), NULL);
781 		Aftercmds = lut_add(Aftercmds, opts_optarg(opts, "a"), addrs);
782 	}
783 
784 	/* record the rotation date */
785 	(void) strftime(nowstr, sizeof (nowstr),
786 	    "%a %b %e %T %Y", gmtime(&Now));
787 	if (opts_count(opts, "v") && fname != NULL)
788 		(void) out("#     recording rotation date %s for %s\n",
789 		    nowstr, fname);
790 	conf_set(fname, "P", STRDUP(nowstr));
791 	Donenames = lut_add(Donenames, fname, "1");
792 	return (B_TRUE);
793 }
794 
795 /* rotate files "up" according to current template */
796 static void
797 rotateto(struct fn *fnp, struct opts *opts, int n, struct fn *recentlog,
798     boolean_t isgz)
799 {
800 	struct fn *template = fn_new(opts_optarg(opts, "t"));
801 	struct fn *newfile = fn_new(NULL);
802 	struct fn *dirname;
803 	int hasn;
804 	struct stat stbuf;
805 	char *buf1;
806 	char *buf2;
807 
808 	/* expand template to figure out new filename */
809 	hasn = kw_expand(template, newfile, n, isgz);
810 
811 	buf1 = fn_s(fnp);
812 	buf2 = fn_s(newfile);
813 
814 	if (Debug)
815 		if (buf1 != NULL && buf2 != NULL) {
816 			(void) fprintf(stderr, "rotateto: %s -> %s (%d)\n",
817 			    buf1, buf2, n);
818 		}
819 	/* if filename is there already, rotate "up" */
820 	if (hasn && lstat(buf2, &stbuf) != -1)
821 		rotateto(newfile, opts, n + 1, recentlog, isgz);
822 	else if (hasn && opts_count(opts, "z")) {
823 		struct fn *gzfnp = fn_dup(newfile);
824 		/*
825 		 * since we're compressing old files, see if we
826 		 * about to rotate into one.
827 		 */
828 		fn_puts(gzfnp, ".gz");
829 		if (lstat(fn_s(gzfnp), &stbuf) != -1)
830 			rotateto(gzfnp, opts, n + 1, recentlog, B_TRUE);
831 		fn_free(gzfnp);
832 	}
833 
834 	/* first time through run "before" cmd if not run already */
835 	if (n == 0 && opts_count(opts, "b")) {
836 		const char *cmd = opts_optarg(opts, "b");
837 
838 		if (lut_lookup(Beforecmds, cmd) == NULL) {
839 			docmd(opts, "-b cmd", Sh, "-c", cmd, NULL);
840 			Beforecmds = lut_add(Beforecmds, cmd, "1");
841 		}
842 	}
843 
844 	/* ensure destination directory exists */
845 	dirname = fn_dirname(newfile);
846 	docmd(opts, "verify directory exists", Mkdir, "-p",
847 	    fn_s(dirname), NULL);
848 	fn_free(dirname);
849 
850 	/* do the rename */
851 	if (opts_count(opts, "c")) {
852 		docmd(opts, "rotate log file via copy (-c flag)",
853 		    Cp, "-fp", fn_s(fnp), fn_s(newfile));
854 		docmd(opts, "truncate log file (-c flag)",
855 		    Cp, "-f", "/dev/null", fn_s(fnp));
856 	} else if (n == 0 && opts_count(opts, "M")) {
857 		struct fn *rawcmd = fn_new(opts_optarg(opts, "M"));
858 		struct fn *cmd = fn_new(NULL);
859 
860 		/* use specified command to mv the log file */
861 		kw_init(fnp, newfile);
862 		(void) kw_expand(rawcmd, cmd, 0, B_FALSE);
863 		docmd(opts, "-M cmd", Sh, "-c", fn_s(cmd), NULL);
864 		fn_free(rawcmd);
865 		fn_free(cmd);
866 	} else
867 		/* common case: we call "mv" to handle the actual rename */
868 		docmd(opts, "rotate log file", Mv, "-f",
869 		    fn_s(fnp), fn_s(newfile));
870 
871 	/* first time through, gather interesting info for caller */
872 	if (n == 0)
873 		fn_renew(recentlog, fn_s(newfile));
874 }
875 
876 /* expire phase of logname processing */
877 static void
878 expirefiles(struct fn *fnp, struct opts *opts)
879 {
880 	char *fname = fn_s(fnp);
881 	struct fn *template;
882 	struct fn *pattern;
883 	struct fn_list *files;
884 	struct fn *nextfnp;
885 	off_t count;
886 	off_t size;
887 
888 	if (Debug && fname != NULL)
889 		(void) fprintf(stderr, "expirefiles: fname <%s>\n", fname);
890 
891 	/* return if no potential expire conditions */
892 	if (opts_count(opts, "zAS") == 0 && opts_optarg_int(opts, "C") == 0)
893 		return;
894 
895 	kw_init(fnp, NULL);
896 	if (Debug > 1) {
897 		(void) fprintf(stderr, "expirefiles keywords:\n");
898 		kw_print(stderr);
899 	}
900 
901 	/* see if pattern was supplied by user */
902 	if (opts_count(opts, "T")) {
903 		template = fn_new(opts_optarg(opts, "T"));
904 		pattern = glob_to_reglob(template);
905 	} else {
906 		/* nope, generate pattern based on rotation template */
907 		template = fn_new(opts_optarg(opts, "t"));
908 		pattern = fn_new(NULL);
909 		(void) kw_expand(template, pattern, -1,
910 		    opts_count(opts, "z") != 0);
911 	}
912 
913 	/* match all old log files (hopefully not any others as well!) */
914 	files = glob_reglob(pattern);
915 
916 	if (Debug) {
917 		char *buf;
918 
919 		buf = fn_s(pattern);
920 		if (buf != NULL) {
921 			(void) fprintf(stderr, "expirefiles: pattern <%s>\n",
922 			    buf);
923 		}
924 		fn_list_rewind(files);
925 		while ((nextfnp = fn_list_next(files)) != NULL)
926 			buf = fn_s(nextfnp);
927 			if (buf != NULL)
928 				(void) fprintf(stderr, "    <%s>\n", buf);
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_list_addfn(files, nextfnp);
966 				break;
967 			}
968 		}
969 	}
970 
971 	/* record old log files to be gzip'ed according to -z count */
972 	if (opts_count(opts, "z")) {
973 		int zcount = (int)opts_optarg_int(opts, "z");
974 		int fcount = fn_list_count(files);
975 
976 		while (fcount > zcount &&
977 		    (nextfnp = fn_list_popoldest(files)) != NULL) {
978 			if (!fn_isgz(nextfnp)) {
979 				/*
980 				 * Don't gzip the old log file yet -
981 				 * it takes too long. Just remember that we
982 				 * need to gzip.
983 				 */
984 				if (Debug) {
985 					(void) fprintf(stderr,
986 					    "will compress %s count %d\n",
987 					    fn_s(nextfnp), fcount);
988 				}
989 				Gzipnames = lut_add(Gzipnames,
990 						fn_s(nextfnp), "1");
991 			}
992 			fn_free(nextfnp);
993 			fcount--;
994 		}
995 	}
996 
997 	fn_free(template);
998 	fn_list_free(files);
999 }
1000 
1001 /* execute a command to remove an expired log file */
1002 static void
1003 dorm(struct opts *opts, const char *msg, struct fn *fnp)
1004 {
1005 	if (opts_count(opts, "E")) {
1006 		struct fn *rawcmd = fn_new(opts_optarg(opts, "E"));
1007 		struct fn *cmd = fn_new(NULL);
1008 
1009 		/* user supplied cmd, expand $file */
1010 		kw_init(fnp, NULL);
1011 		(void) kw_expand(rawcmd, cmd, 0, B_FALSE);
1012 		docmd(opts, msg, Sh, "-c", fn_s(cmd), NULL);
1013 		fn_free(rawcmd);
1014 		fn_free(cmd);
1015 	} else
1016 		docmd(opts, msg, Rm, "-f", fn_s(fnp), NULL);
1017 	Gzipnames = lut_add(Gzipnames, fn_s(fnp), NULL);
1018 }
1019 
1020 /* execute a command, producing -n and -v output as necessary */
1021 static void
1022 docmd(struct opts *opts, const char *msg, const char *cmd,
1023     const char *arg1, const char *arg2, const char *arg3)
1024 {
1025 	int pid;
1026 	int errpipe[2];
1027 
1028 	/* print info about command if necessary */
1029 	if (opts_count(opts, "vn")) {
1030 		const char *simplecmd;
1031 
1032 		if ((simplecmd = strrchr(cmd, '/')) == NULL)
1033 			simplecmd = cmd;
1034 		else
1035 			simplecmd++;
1036 		(void) out("%s", simplecmd);
1037 		if (arg1)
1038 			(void) out(" %s", arg1);
1039 		if (arg2)
1040 			(void) out(" %s", arg2);
1041 		if (arg3)
1042 			(void) out(" %s", arg3);
1043 		if (msg)
1044 			(void) out(" # %s", msg);
1045 		(void) out("\n");
1046 	}
1047 
1048 	if (opts_count(opts, "n"))
1049 		return;		/* -n means don't really do it */
1050 
1051 	/*
1052 	 * run the cmd and see if it failed.  this function is *not* a
1053 	 * generic command runner -- we depend on some knowledge we
1054 	 * have about the commands we run.  first of all, we expect
1055 	 * errors to spew something to stderr, and that something is
1056 	 * typically short enough to fit into a pipe so we can wait()
1057 	 * for the command to complete and then fetch the error text
1058 	 * from the pipe.  we also expect the exit codes to make sense.
1059 	 * notice also that we only allow a command name which is an
1060 	 * absolute pathname, and two args must be supplied (the
1061 	 * second may be NULL, or they may both be NULL).
1062 	 */
1063 	if (pipe(errpipe) < 0)
1064 		err(EF_SYS, "pipe");
1065 
1066 	if ((pid = fork()) < 0)
1067 		err(EF_SYS, "fork");
1068 	else if (pid) {
1069 		int wstat;
1070 		int count;
1071 
1072 		/* parent */
1073 		(void) close(errpipe[1]);
1074 		if (waitpid(pid, &wstat, 0) < 0)
1075 			err(EF_SYS, "waitpid");
1076 
1077 		/* check for stderr output */
1078 		if (ioctl(errpipe[0], FIONREAD, &count) >= 0 && count) {
1079 			err(EF_WARN, "command failed: %s%s%s%s%s%s%s",
1080 				cmd,
1081 				(arg1) ? " " : "",
1082 				(arg1) ? arg1 : "",
1083 				(arg2) ? " " : "",
1084 				(arg2) ? arg2 : "",
1085 				(arg3) ? " " : "",
1086 				(arg3) ? arg3 : "");
1087 			err_fromfd(errpipe[0]);
1088 		} else if (WIFSIGNALED(wstat))
1089 			err(EF_WARN,
1090 			    "command died, signal %d: %s%s%s%s%s%s%s",
1091 				WTERMSIG(wstat),
1092 				cmd,
1093 				(arg1) ? " " : "",
1094 				(arg1) ? arg1 : "",
1095 				(arg2) ? " " : "",
1096 				(arg2) ? arg2 : "",
1097 				(arg3) ? " " : "",
1098 				(arg3) ? arg3 : "");
1099 		else if (WIFEXITED(wstat) && WEXITSTATUS(wstat))
1100 			err(EF_WARN,
1101 			    "command error, exit %d: %s%s%s%s%s%s%s",
1102 				WEXITSTATUS(wstat),
1103 				cmd,
1104 				(arg1) ? " " : "",
1105 				(arg1) ? arg1 : "",
1106 				(arg2) ? " " : "",
1107 				(arg2) ? arg2 : "",
1108 				(arg3) ? " " : "",
1109 				(arg3) ? arg3 : "");
1110 
1111 		(void) close(errpipe[0]);
1112 	} else {
1113 		/* child */
1114 		(void) dup2(errpipe[1], fileno(stderr));
1115 		(void) close(errpipe[0]);
1116 		(void) execl(cmd, cmd, arg1, arg2, arg3, 0);
1117 		perror(cmd);
1118 		_exit(1);
1119 	}
1120 }
1121