Home | History | Annotate | Line # | Download | only in newsyslog
newsyslog.c revision 1.37
      1 /*	$NetBSD: newsyslog.c,v 1.37 2000/08/22 16:23:15 tron Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1999, 2000 Andrew Doran <ad (at) NetBSD.org>
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
     17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     26  * SUCH DAMAGE.
     27  *
     28  */
     29 
     30 /*
     31  * This file contains changes from the Open Software Foundation.
     32  */
     33 
     34 /*
     35  * Copyright 1988, 1989 by the Massachusetts Institute of Technology
     36  *
     37  * Permission to use, copy, modify, and distribute this software
     38  * and its documentation for any purpose and without fee is
     39  * hereby granted, provided that the above copyright notice
     40  * appear in all copies and that both that copyright notice and
     41  * this permission notice appear in supporting documentation,
     42  * and that the names of M.I.T. and the M.I.T. S.I.P.B. not be
     43  * used in advertising or publicity pertaining to distribution
     44  * of the software without specific, written prior permission.
     45  * M.I.T. and the M.I.T. S.I.P.B. make no representations about
     46  * the suitability of this software for any purpose.  It is
     47  * provided "as is" without express or implied warranty.
     48  *
     49  */
     50 
     51 /*
     52  * newsyslog(8) - a program to roll over log files provided that specified
     53  * critera are met, optionally preserving a number of historical log files.
     54  */
     55 
     56 #include <sys/cdefs.h>
     57 #ifndef lint
     58 __RCSID("$NetBSD: newsyslog.c,v 1.37 2000/08/22 16:23:15 tron Exp $");
     59 #endif /* not lint */
     60 
     61 #include <sys/types.h>
     62 #include <sys/time.h>
     63 #include <sys/stat.h>
     64 #include <sys/param.h>
     65 #include <sys/wait.h>
     66 
     67 #include <ctype.h>
     68 #include <fcntl.h>
     69 #include <grp.h>
     70 #include <pwd.h>
     71 #include <signal.h>
     72 #include <stdio.h>
     73 #include <stdlib.h>
     74 #include <stdarg.h>
     75 #include <string.h>
     76 #include <time.h>
     77 #include <unistd.h>
     78 #include <errno.h>
     79 #include <err.h>
     80 #include <util.h>
     81 #include <paths.h>
     82 
     83 #include "pathnames.h"
     84 
     85 #define	PRHDRINFO(x)	((void)(verbose ? printf x : 0))
     86 #define	PRINFO(x)	((void)(verbose ? printf("  ") + printf x : 0))
     87 
     88 #define	CE_COMPRESS	0x01	/* Compress the achived log files */
     89 #define	CE_BINARY	0x02	/* Logfile is a binary file/non-syslog */
     90 #define	CE_NOSIGNAL	0x04	/* Don't send a signal when trimmed */
     91 #define	CE_CREATE	0x08	/* Create log file if none exists */
     92 #define	CE_PLAIN0	0x10	/* Do not compress zero'th history file */
     93 
     94 struct conf_entry {
     95 	uid_t	uid;			/* Owner of log */
     96 	gid_t	gid;			/* Group of log */
     97 	mode_t	mode;			/* File permissions */
     98 	int	numhist;		/* Number of historical logs to keep */
     99 	size_t	maxsize;		/* Maximum log size */
    100 	int	maxage;			/* Hours between log trimming */
    101 	time_t	trimat;			/* Specific trim time */
    102 	int	flags;			/* Flags (CE_*) */
    103 	int	signum;			/* Signal to send */
    104 	char	pidfile[MAXPATHLEN];	/* File containing PID to signal */
    105 	char	logfile[MAXPATHLEN];	/* Path to log file */
    106 };
    107 
    108 int     verbose = 0;			/* Be verbose */
    109 int	noaction = 0;			/* Take no action */
    110 char    hostname[MAXHOSTNAMELEN + 1];	/* Hostname, stripped of domain */
    111 uid_t	myeuid;				/* EUID we are running with */
    112 
    113 int	getsig(const char *);
    114 int	isnumber(const char *);
    115 int	main(int, char **);
    116 int	parse_cfgline(struct conf_entry *, FILE *, size_t *);
    117 time_t	parse_iso8601(char *);
    118 time_t	parse_dwm(char *);
    119 int	parse_userspec(const char *, struct passwd **, struct group **);
    120 pid_t	readpidfile(const char *);
    121 void	usage(void);
    122 
    123 void	log_compress(struct conf_entry *, const char *);
    124 void	log_create(struct conf_entry *);
    125 void	log_examine(struct conf_entry *, int);
    126 void	log_trim(struct conf_entry *);
    127 void	log_trimmed(struct conf_entry *);
    128 
    129 /*
    130  * Program entry point.
    131  */
    132 int
    133 main(int argc, char **argv)
    134 {
    135 	struct conf_entry log;
    136 	FILE *fd;
    137 	char *p, *cfile;
    138 	int c, needroot, i, force;
    139 	size_t lineno;
    140 
    141 	force = 0;
    142 	needroot = 1;
    143 	cfile = _PATH_NEWSYSLOGCONF;
    144 
    145 	gethostname(hostname, sizeof (hostname));
    146 	hostname[sizeof (hostname) - 1] = '\0';
    147 
    148 	/* Truncate domain. */
    149 	if ((p = strchr(hostname, '.')) != NULL)
    150 		*p = '\0';
    151 
    152 	/* Parse command line options. */
    153 	while ((c = getopt(argc, argv, "f:nrvF")) != -1) {
    154 		switch (c) {
    155 		case 'f':
    156 			cfile = optarg;
    157 			break;
    158 		case 'n':
    159 			noaction = 1;
    160 			verbose = 1;
    161 			break;
    162 		case 'r':
    163 			needroot = 0;
    164 			break;
    165 		case 'v':
    166 			verbose = 1;
    167 			break;
    168 		case 'F':
    169 			force = 1;
    170 			break;
    171 		default:
    172 			usage();
    173 			/* NOTREACHED */
    174 		}
    175 	}
    176 
    177 	myeuid = geteuid();
    178 	if (needroot && myeuid != 0)
    179 		errx(EXIT_FAILURE, "must be run as root");
    180 
    181 	argc -= optind;
    182 	argv += optind;
    183 
    184 	if (strcmp(cfile, "-") == 0)
    185 		fd = stdin;
    186 	else if ((fd = fopen(cfile, "rt")) == NULL)
    187 		err(EXIT_FAILURE, "%s", cfile);
    188 
    189 	for (lineno = 0; !parse_cfgline(&log, fd, &lineno);) {
    190 		/*
    191 		 * If specific log files were specified, touch only
    192 		 * those.
    193 		 */
    194 		if (argc != 0) {
    195 			for (i = 0; i < argc; i++)
    196 				if (strcmp(log.logfile, argv[i]) == 0)
    197 					break;
    198 			if (i == argc)
    199 				continue;
    200 		}
    201 		log_examine(&log, force);
    202 	}
    203 
    204 	if (fd != stdin)
    205 		fclose(fd);
    206 
    207 	exit(EXIT_SUCCESS);
    208 	/* NOTREACHED */
    209 }
    210 
    211 /*
    212  * Parse a single line from the configuration file.
    213  */
    214 int
    215 parse_cfgline(struct conf_entry *log, FILE *fd, size_t *_lineno)
    216 {
    217 	char *line, *q, **ap, *argv[10];
    218 	struct passwd *pw;
    219 	struct group *gr;
    220 	int nf, lineno, i, rv;
    221 
    222 	rv = -1;
    223 	line = NULL;
    224 
    225 	/* Place the white-space separated fields into an array. */
    226 	do {
    227 		if (line != NULL)
    228 			free(line);
    229 		if ((line = fparseln(fd, NULL, _lineno, NULL, 0)) == NULL)
    230 			return (rv);
    231 		lineno = (int)*_lineno;
    232 
    233 		for (ap = argv, nf = 0; (*ap = strsep(&line, " \t")) != NULL;)
    234 			if (**ap != '\0') {
    235 				if (++nf == sizeof (argv) / sizeof (argv[0])) {
    236 					warnx("config line %d: "
    237 					    "too many fields", lineno);
    238 					goto bad;
    239 				}
    240 				ap++;
    241 			}
    242 	} while (nf == 0);
    243 
    244 	if (nf < 6)
    245 		errx(EXIT_FAILURE, "config line %d: too few fields", lineno);
    246 
    247 	memset(log, 0, sizeof (*log));
    248 
    249 	/* logfile_name */
    250 	ap = argv;
    251 	strlcpy(log->logfile, *ap++, sizeof (log->logfile));
    252 	if (log->logfile[0] != '/')
    253 		errx(EXIT_FAILURE,
    254 		    "config line %d: logfile must have a full path", lineno);
    255 
    256 	/* owner:group */
    257 	if (strchr(*ap, ':') != NULL || strchr(*ap, '.') != NULL) {
    258 		if (parse_userspec(*ap++, &pw, &gr)) {
    259 			warnx("config line %d: unknown user/group", lineno);
    260 			goto bad;
    261 		}
    262 
    263 		/*
    264 		 * We may only change the file's owner as non-root.
    265 		 */
    266 		if (myeuid != 0) {
    267 			if (pw->pw_uid != myeuid)
    268 				errx(EXIT_FAILURE, "config line %d: user:group "
    269 				    "as non-root must match current user",
    270 				    lineno);
    271 			log->uid = (uid_t)-1;
    272 		} else
    273 			log->uid = pw->pw_uid;
    274 		log->gid = gr->gr_gid;
    275 		if (nf < 7)
    276 			errx(EXIT_FAILURE, "config line %d: too few fields",
    277 			    lineno);
    278 	} else if (myeuid != 0) {
    279 		log->uid = (uid_t)-1;
    280 		log->gid = getegid();
    281 	}
    282 
    283 	/* mode */
    284 	if (sscanf(*ap++, "%o", &i) != 1) {
    285 		warnx("config line %d: bad permissions", lineno);
    286 		goto bad;
    287 	}
    288 	log->mode = (mode_t)i;
    289 
    290 	/* count */
    291 	if (sscanf(*ap++, "%d", &log->numhist) != 1) {
    292 		warnx("config line %d: bad log count", lineno);
    293 		goto bad;
    294 	}
    295 
    296 	/* size */
    297 	if (isdigit(**ap)) {
    298 		log->maxsize = (int)strtol(*ap, &q, 0);
    299 		if (*q != '\0') {
    300 			warnx("config line %d: bad log size", lineno);
    301 			goto bad;
    302 		}
    303 	} else if (**ap == '*')
    304 		log->maxsize = (size_t)-1;
    305 	else {
    306 		warnx("config line %d: bad log size", lineno);
    307 		goto bad;
    308 	}
    309 	ap++;
    310 
    311 	/* when */
    312 	log->maxage = -1;
    313 	log->trimat = (time_t)-1;
    314 	q = *ap++;
    315 
    316 	if (strcmp(q, "*") != 0) {
    317 		if (isdigit(*q))
    318 			log->maxage = (int)strtol(q, &q, 10);
    319 
    320 		/*
    321 		 * One class of periodic interval specification can follow a
    322 		 * maximum age specification.  Handle it.
    323 		 */
    324 		if (*q == '@') {
    325 			log->trimat = parse_iso8601(q + 1);
    326 			if (log->trimat == (time_t)-1) {
    327 				warnx("config line %d: bad trim time", lineno);
    328 				goto bad;
    329 			}
    330 		} else if (*q == '$') {
    331 			if ((log->trimat = parse_dwm(q + 1)) == (time_t)-1) {
    332 				warnx("config line %d: bad trim time", lineno);
    333 				goto bad;
    334 			}
    335 		} else if (log->maxage == -1) {
    336 			warnx("config line %d: bad log age", lineno);
    337 			goto bad;
    338 		}
    339 	}
    340 
    341 	/* flags */
    342 	log->flags = 0;
    343 	for (q = *ap++; q != NULL && *q != '\0'; q++) {
    344 		switch (tolower(*q)) {
    345 		case 'b':
    346 			log->flags |= CE_BINARY;
    347 			break;
    348 		case 'c':
    349 			log->flags |= CE_CREATE;
    350 			break;
    351 		case 'n':
    352 			log->flags |= CE_NOSIGNAL;
    353 			break;
    354 		case 'p':
    355 			log->flags |= CE_PLAIN0;
    356 			break;
    357 		case 'z':
    358 			log->flags |= CE_COMPRESS;
    359 			break;
    360 		case '-':
    361 			break;
    362 		default:
    363 			warnx("config line %d: bad flags", lineno);
    364 			goto bad;
    365 		}
    366 	}
    367 
    368 	/* path_to_pidfile */
    369 	if (*ap != NULL && **ap == '/')
    370 		strlcpy(log->pidfile, *ap++, sizeof (log->pidfile));
    371 	else
    372 		log->pidfile[0] = '\0';
    373 
    374 	/* sigtype */
    375 	if (*ap != NULL && (log->signum = getsig(*ap++)) < 0) {
    376 		warnx("config line %d: bad signal type", lineno);
    377 		goto bad;
    378 	} else
    379 		log->signum = SIGHUP;
    380 
    381 	rv = 0;
    382 
    383 bad:
    384 	free(line);
    385 	return (rv);
    386 }
    387 
    388 /*
    389  * Examine a log file.  If the trim conditions are met, call log_trim() to
    390  * trim the log file.
    391  */
    392 void
    393 log_examine(struct conf_entry *log, int force)
    394 {
    395 	struct stat sb;
    396 	size_t size;
    397 	int age, trim;
    398 	char tmp[MAXPATHLEN];
    399 	const char *reason;
    400 	time_t now;
    401 
    402 	now = time(NULL);
    403 
    404 	PRHDRINFO(("\n%s <%d%s>: ", log->logfile, log->numhist,
    405 	    (log->flags & CE_COMPRESS) != 0 ? "Z" : ""));
    406 
    407 	/*
    408 	 * stat() the logfile.  If it doesn't exist and the `c' flag has
    409 	 * been specified, create it.  If it doesn't exist and the `c' flag
    410 	 * hasn't been specified, give up.
    411 	 */
    412 	if (stat(log->logfile, &sb) < 0) {
    413 		if (errno == ENOENT && (log->flags & CE_CREATE) != 0) {
    414 			PRHDRINFO(("creating; "));
    415 			if (!noaction)
    416 				log_create(log);
    417 			else {
    418 				PRHDRINFO(("can't proceed with `-n'\n"));
    419 				return;
    420 			}
    421 			if (stat(log->logfile, &sb))
    422 				err(EXIT_FAILURE, "%s", log->logfile);
    423 		} else if (errno == ENOENT) {
    424 			PRHDRINFO(("does not exist --> skip log\n"));
    425 			return;
    426 		} else if (errno != 0)
    427 			err(EXIT_FAILURE, "%s", log->logfile);
    428 	}
    429 
    430 	/* Size of the log file in kB. */
    431 	size = ((size_t)sb.st_blocks * S_BLKSIZE) >> 10;
    432 
    433 	/*
    434 	 * Get the age (expressed in hours) of the current log file with
    435 	 * respect to the newest historical log file.
    436 	 */
    437 	strlcpy(tmp, log->logfile, sizeof (tmp));
    438 	strlcat(tmp, ".0", sizeof (tmp));
    439 	if (stat(tmp, &sb) < 0) {
    440 		strlcat(tmp, ".gz", sizeof (tmp));
    441 		if (stat(tmp, &sb) < 0)
    442 			age = -1;
    443 		else
    444 			age = (int)(now - sb.st_mtime + 1800) / 3600;
    445 	} else
    446 		age = (int)(now - sb.st_mtime + 1800) / 3600;
    447 
    448 	/*
    449 	 * Examine the set of given trim conditions and if any one is met,
    450 	 * trim the log.
    451 	 *
    452 	 * Note: if `maxage' or `trimat' is used as a trim condition, we
    453 	 * need at least one historical log file to determine the `age' of
    454 	 * the active log file.  WRT `trimat', we will trim up to one hour
    455 	 * after the specific trim time has passed - we need to know if
    456 	 * we've trimmed to meet that condition with a previous invocation
    457 	 * of newsyslog(8).
    458 	 */
    459 	if (log->maxage >= 0 && (age >= log->maxage || age < 0)) {
    460 		trim = 1;
    461 		reason = "log age > interval";
    462 	} else if (size >= log->maxsize) {
    463 		trim = 1;
    464 		reason = "log size > size";
    465 	} else if (log->trimat != (time_t)-1 && now >= log->trimat &&
    466 		   age > 1 && difftime(now, log->trimat) < 60 * 60) {
    467 		trim = 1;
    468 		reason = "specific trim time";
    469 	} else {
    470 		trim = force;
    471 		reason = "trim forced";
    472 	}
    473 
    474 	if (trim) {
    475 		PRHDRINFO(("--> trim log (%s)\n", reason));
    476 		log_trim(log);
    477 	} else
    478 		PRHDRINFO(("--> skip log (trim conditions not met)\n"));
    479 }
    480 
    481 /*
    482  * Trim the specified log file.
    483  */
    484 void
    485 log_trim(struct conf_entry *log)
    486 {
    487 	char file1[MAXPATHLEN], file2[MAXPATHLEN];
    488 	int i;
    489 	struct stat st;
    490 	pid_t pid;
    491 
    492 	/* Remove oldest historical log. */
    493 	snprintf(file1, sizeof (file1), "%s.%d", log->logfile,
    494 	    log->numhist - 1);
    495 
    496 	PRINFO(("rm -f %s\n", file1));
    497 	if (!noaction)
    498 		unlink(file1);
    499 	strlcat(file1, ".gz", sizeof (file1));
    500 	PRINFO(("rm -f %s\n", file1));
    501 	if (!noaction)
    502 		unlink(file1);
    503 
    504 	/* Move down log files. */
    505 	for (i = log->numhist - 1; i != 0; i--) {
    506 		snprintf(file1, sizeof (file1), "%s.%d", log->logfile, i - 1);
    507 		snprintf(file2, sizeof (file2), "%s.%d", log->logfile, i);
    508 
    509 		if (lstat(file1, &st) != 0) {
    510 			strlcat(file1, ".gz", sizeof (file1));
    511 			strlcat(file2, ".gz", sizeof (file2));
    512 			if (lstat(file1, &st) != 0)
    513 				continue;
    514 		}
    515 
    516 		PRINFO(("mv %s %s\n", file1, file2));
    517 		if (!noaction)
    518 			if (rename(file1, file2))
    519 				err(EXIT_FAILURE, "%s", file1);
    520 		PRINFO(("chmod %o %s\n", log->mode, file2));
    521 		if (!noaction)
    522 			if (chmod(file2, log->mode))
    523 				err(EXIT_FAILURE, "%s", file2);
    524 		PRINFO(("chown %d:%d %s\n", log->uid, log->gid,
    525 		    file2));
    526 		if (!noaction)
    527 			if (chown(file2, log->uid, log->gid))
    528 				err(EXIT_FAILURE, "%s", file2);
    529 	}
    530 
    531 	/*
    532 	 * If a historical log file isn't compressed, and 'z' has been
    533 	 * specified, compress it.  (This is convenient, but is also needed
    534 	 * if 'p' has been specified.)  It should be noted that gzip(1)
    535 	 * preserves file ownership and file mode.
    536 	 */
    537 	for (i = (log->flags & CE_PLAIN0) != 0; i < log->numhist; i++) {
    538 		snprintf(file1, sizeof (file1), "%s.%d", log->logfile, i);
    539 		if (lstat(file1, &st) != 0)
    540 			continue;
    541 		snprintf(file2, sizeof (file2), "%s.gz", file1);
    542 		if (lstat(file2, &st) == 0)
    543 			continue;
    544 		log_compress(log, file1);
    545 	}
    546 
    547 	log_trimmed(log);
    548 
    549 	/* Create the historical log file if we're maintaining history. */
    550 	if (log->numhist == 0) {
    551 		PRINFO(("rm -f %s\n", log->logfile));
    552 		if (!noaction)
    553 			if (unlink(log->logfile))
    554 				err(EXIT_FAILURE, "%s", log->logfile);
    555 	} else {
    556 		snprintf(file1, sizeof (file1), "%s.0", log->logfile);
    557 		PRINFO(("mv %s %s\n", log->logfile, file1));
    558 		if (!noaction)
    559 			if (rename(log->logfile, file1))
    560 				err(EXIT_FAILURE, "%s", log->logfile);
    561 	}
    562 
    563 	PRINFO(("(create new log)\n"));
    564 	log_create(log);
    565 	log_trimmed(log);
    566 
    567 	/* Set the correct permissions on the log. */
    568 	PRINFO(("chmod %o %s\n", log->mode, log->logfile));
    569 	if (!noaction)
    570 		if (chmod(log->logfile, log->mode))
    571 			err(EXIT_FAILURE, "%s", log->logfile);
    572 
    573 	/* Do we need to signal a daemon? */
    574 	if ((log->flags & CE_NOSIGNAL) == 0) {
    575 		if (log->pidfile[0] != '\0')
    576 			pid = readpidfile(log->pidfile);
    577 		else
    578 			pid = readpidfile(_PATH_SYSLOGDPID);
    579 
    580 		if (pid != (pid_t)-1) {
    581 			PRINFO(("kill -%s %lu\n",
    582 			    sys_signame[log->signum], (u_long)pid));
    583 			if (!noaction)
    584 				if (kill(pid, log->signum))
    585 					warn("kill");
    586 		}
    587 	}
    588 
    589 	/* If the newest historical log is to be compressed, do it here. */
    590 	if ((log->flags & (CE_PLAIN0 | CE_COMPRESS)) == CE_COMPRESS) {
    591 		snprintf(file1, sizeof (file1), "%s.0", log->logfile);
    592 		log_compress(log, file1);
    593 	}
    594 }
    595 
    596 /*
    597  * Write an entry to the log file recording the fact that it was trimmed.
    598  */
    599 void
    600 log_trimmed(struct conf_entry *log)
    601 {
    602 	FILE *fd;
    603 	time_t now;
    604 	char *daytime;
    605 
    606 	if ((log->flags & CE_BINARY) != 0)
    607 		return;
    608 	PRINFO(("(append rotation notice to %s)\n", log->logfile));
    609 	if (noaction)
    610 		return;
    611 
    612 	if ((fd = fopen(log->logfile, "at")) == NULL)
    613 		err(EXIT_FAILURE, "%s", log->logfile);
    614 
    615 	now = time(NULL);
    616 	daytime = ctime(&now) + 4;
    617 	daytime[15] = '\0';
    618 
    619 	fprintf(fd, "%s %s newsyslog[%lu]: log file turned over\n", daytime,
    620 	    hostname, (u_long)getpid());
    621 	fclose(fd);
    622 }
    623 
    624 /*
    625  * Create a new log file.
    626  */
    627 void
    628 log_create(struct conf_entry *log)
    629 {
    630 	int fd;
    631 
    632 	if (noaction)
    633 		return;
    634 
    635 	if ((fd = creat(log->logfile, log->mode)) < 0)
    636 		err(EXIT_FAILURE, "%s", log->logfile);
    637 	if (fchown(fd, log->uid, log->gid) < 0)
    638 		err(EXIT_FAILURE, "%s", log->logfile);
    639 	close(fd);
    640 }
    641 
    642 /*
    643  * Fork off gzip(1) to compress a log file.  This routine takes an
    644  * additional string argument (the name of the file to compress): it is also
    645  * used to compress historical log files other than the newest.
    646  */
    647 void
    648 log_compress(struct conf_entry *log, const char *fn)
    649 {
    650 	char tmp[MAXPATHLEN];
    651 
    652 	PRINFO(("gzip %s\n", fn));
    653 	if (!noaction) {
    654 		pid_t pid;
    655 		int status;
    656 
    657 		if ((pid = vfork()) < 0)
    658 			err(EXIT_FAILURE, "vfork");
    659 		else if (pid == 0) {
    660 			execl(_PATH_GZIP, "gzip", "-f", fn, NULL);
    661 			_exit(EXIT_FAILURE);
    662 		}
    663 		while (waitpid(pid, &status, 0) != pid);
    664 
    665 		if (!WIFEXITED(status) || (WEXITSTATUS(status) != 0))
    666 			errx(EXIT_FAILURE, "gzip failed");
    667 	}
    668 
    669 	snprintf(tmp, sizeof (tmp), "%s.gz", fn);
    670 	PRINFO(("chown %d:%d %s\n", log->uid, log->gid, tmp));
    671 	if (!noaction)
    672 		if (chown(tmp, log->uid, log->gid))
    673 			err(EXIT_FAILURE, "%s", tmp);
    674 }
    675 
    676 /*
    677  * Display program usage information.
    678  */
    679 void
    680 usage(void)
    681 {
    682 
    683 	fprintf(stderr,
    684 	    "usage: newsyslog [-nrvF] [-f config-file] [file ...]\n");
    685 	exit(EXIT_FAILURE);
    686 }
    687 
    688 /*
    689  * Return non-zero if a string represents a decimal value.
    690  */
    691 int
    692 isnumber(const char *string)
    693 {
    694 
    695 	while (isdigit(*string))
    696 		string++;
    697 
    698 	return (*string == '\0');
    699 }
    700 
    701 /*
    702  * Given a signal name, attempt to find the corresponding signal number.
    703  */
    704 int
    705 getsig(const char *sig)
    706 {
    707 	char *p;
    708 	int n;
    709 
    710 	if (isnumber(sig)) {
    711 		n = (int)strtol(sig, &p, 0);
    712 		if (p != '\0' || n < 0 || n >= NSIG)
    713 			return (-1);
    714 		return (n);
    715 	}
    716 
    717 	if (strncasecmp(sig, "SIG", 3) == 0)
    718 		sig += 3;
    719 	for (n = 1; n < NSIG; n++)
    720 		if (strcasecmp(sys_signame[n], sig) == 0)
    721 			return (n);
    722 	return (-1);
    723 }
    724 
    725 /*
    726  * Given a path to a PID file, return the PID contained within.
    727  */
    728 pid_t
    729 readpidfile(const char *file)
    730 {
    731 	FILE *fd;
    732 	char line[BUFSIZ];
    733 	pid_t pid;
    734 
    735 #ifdef notyet
    736 	if (file[0] != '/')
    737 		snprintf(tmp, sizeof (tmp), "%s%s", _PATH_VARRUN, file);
    738 	else
    739 		strlcpy(tmp, file, sizeof (tmp));
    740 #endif
    741 
    742 	if ((fd = fopen(file, "rt")) == NULL) {
    743 		warn("%s", file);
    744 		return (-1);
    745 	}
    746 
    747 	if (fgets(line, sizeof (line) - 1, fd) != NULL) {
    748 		line[sizeof (line) - 1] = '\0';
    749 		pid = (pid_t)strtol(line, NULL, 0);
    750 	} else {
    751 		warnx("unable to read %s", file);
    752 		pid = (pid_t)-1;
    753 	}
    754 
    755 	fclose(fd);
    756 	return (pid);
    757 }
    758 
    759 /*
    760  * Parse a user:group specification.
    761  *
    762  * XXX This is over the top for newsyslog(8).  It should be moved to libutil.
    763  */
    764 int
    765 parse_userspec(const char *name, struct passwd **pw, struct group **gr)
    766 {
    767 	char buf[MAXLOGNAME * 2 + 2], *group;
    768 
    769 	strlcpy(buf, name, sizeof (buf));
    770 	*gr = NULL;
    771 
    772 	/*
    773 	 * Before attempting to use '.' as a separator, see if the whole
    774 	 * string resolves as a user name.
    775 	 */
    776 	if ((*pw = getpwnam(buf)) != NULL) {
    777 		*gr = getgrgid((*pw)->pw_gid);
    778 		return (0);
    779 	}
    780 
    781 	/* Split the user and group name. */
    782 	if ((group = strchr(buf, ':')) != NULL ||
    783 	    (group = strchr(buf, '.')) != NULL)
    784 		*group++ = '\0';
    785 
    786 	if (isnumber(buf))
    787 		*pw = getpwuid((uid_t)atoi(buf));
    788 	else
    789 		*pw = getpwnam(buf);
    790 
    791 	/*
    792 	 * Find the group.  If a group wasn't specified, use the user's
    793 	 * `natural' group.  We get to this point even if no user was found.
    794 	 * This is to allow the caller to get a better idea of what went
    795 	 * wrong, if anything.
    796 	 */
    797 	if (group == NULL || *group == '\0') {
    798 		if (*pw == NULL)
    799 			return (-1);
    800 		*gr = getgrgid((*pw)->pw_gid);
    801 	} else if (isnumber(group))
    802 		*gr = getgrgid((gid_t)atoi(group));
    803 	else
    804 		*gr = getgrnam(group);
    805 
    806 	return (*pw != NULL && *gr != NULL ? 0 : -1);
    807 }
    808 
    809 /*
    810  * Parse a cyclic time specification, the format is as follows:
    811  *
    812  *	[Dhh] or [Wd[Dhh]] or [Mdd[Dhh]]
    813  *
    814  * to rotate a log file cyclic at
    815  *
    816  *	- every day (D) within a specific hour (hh)	(hh = 0...23)
    817  *	- once a week (W) at a specific day (d)     OR	(d = 0..6, 0 = Sunday)
    818  *	- once a month (M) at a specific day (d)	(d = 1..31,l|L)
    819  *
    820  * We don't accept a timezone specification; missing fields are defaulted to
    821  * the current date but time zero.
    822  */
    823 time_t
    824 parse_dwm(char *s)
    825 {
    826 	char *t;
    827 	struct tm tm, *tmp;
    828 	u_long ul;
    829 	time_t now;
    830 	static int mtab[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    831 	int wmseen, dseen, nd, save;
    832 
    833 	wmseen = 0;
    834 	dseen = 0;
    835 
    836 	now = time(NULL);
    837 	tmp = localtime(&now);
    838 	tm = *tmp;
    839 
    840 	/* Set no. of days per month */
    841 	nd = mtab[tm.tm_mon];
    842 
    843 	if (tm.tm_mon == 1 &&
    844 	    ((tm.tm_year + 1900) % 4 == 0) &&
    845 	    ((tm.tm_year + 1900) % 100 != 0) &&
    846 	    ((tm.tm_year + 1900) % 400 == 0))
    847 		nd++;	/* leap year, 29 days in february */
    848 	tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
    849 
    850 	for (;;) {
    851 		switch (*s) {
    852 		case 'D':
    853 			if (dseen)
    854 				return ((time_t)-1);
    855 			dseen++;
    856 			s++;
    857 			ul = strtoul(s, &t, 10);
    858 			if (ul < 0 || ul > 23)
    859 				return ((time_t)-1);
    860 			tm.tm_hour = ul;
    861 			break;
    862 
    863 		case 'W':
    864 			if (wmseen)
    865 				return (-1);
    866 			wmseen++;
    867 			s++;
    868 			ul = strtoul(s, &t, 10);
    869 			if (ul < 0 || ul > 6)
    870 				return (-1);
    871 			if (ul != tm.tm_wday) {
    872 				if (ul < tm.tm_wday) {
    873 					save = 6 - tm.tm_wday;
    874 					save += (ul + 1);
    875 				} else
    876 					save = ul - tm.tm_wday;
    877 				tm.tm_mday += save;
    878 
    879 				if (tm.tm_mday > nd) {
    880 					tm.tm_mon++;
    881 					tm.tm_mday = tm.tm_mday - nd;
    882 				}
    883 			}
    884 			break;
    885 
    886 		case 'M':
    887 			if (wmseen)
    888 				return (-1);
    889 			wmseen++;
    890 			s++;
    891 			if (tolower(*s) == 'l') {
    892 				tm.tm_mday = nd;
    893 				s++;
    894 				t = s;
    895 			} else {
    896 				ul = strtoul(s, &t, 10);
    897 				if (ul < 1 || ul > 31)
    898 					return (-1);
    899 
    900 				if (ul > nd)
    901 					return (-1);
    902 				tm.tm_mday = ul;
    903 			}
    904 			break;
    905 
    906 		default:
    907 			return (-1);
    908 			break;
    909 		}
    910 
    911 		if (*t == '\0' || isspace(*t))
    912 			break;
    913 		else
    914 			s = t;
    915 	}
    916 
    917 	return (mktime(&tm));
    918 }
    919 
    920 /*
    921  * Parse a limited subset of ISO 8601.  The specific format is as follows:
    922  *
    923  * [CC[YY[MM[DD]]]][THH[MM[SS]]]	(where `T' is the literal letter)
    924  *
    925  * We don't accept a timezone specification; missing fields (including
    926  * timezone) are defaulted to the current date but time zero.
    927  */
    928 time_t
    929 parse_iso8601(char *s)
    930 {
    931 	char *t;
    932 	struct tm tm, *tmp;
    933 	u_long ul;
    934 	time_t now;
    935 
    936 	now = time(NULL);
    937 	tmp = localtime(&now);
    938 	tm = *tmp;
    939 
    940 	tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
    941 
    942 	ul = strtoul(s, &t, 10);
    943 	if (*t != '\0' && *t != 'T')
    944 		return ((time_t)-1);
    945 
    946 	/*
    947 	 * Now t points either to the end of the string (if no time was
    948 	 * provided) or to the letter `T' which separates date and time in
    949 	 * ISO 8601.  The pointer arithmetic is the same for either case.
    950 	 */
    951 	switch (t - s) {
    952 	case 8:
    953 		tm.tm_year = ((ul / 1000000) - 19) * 100;
    954 		ul = ul % 1000000;
    955 		/* FALLTHROUGH */
    956 	case 6:
    957 		tm.tm_year = tm.tm_year - (tm.tm_year % 100);
    958 		tm.tm_year += ul / 10000;
    959 		ul = ul % 10000;
    960 		/* FALLTHROUGH */
    961 	case 4:
    962 		tm.tm_mon = (ul / 100) - 1;
    963 		ul = ul % 100;
    964 		/* FALLTHROUGH */
    965 	case 2:
    966 		tm.tm_mday = ul;
    967 		/* FALLTHROUGH */
    968 	case 0:
    969 		break;
    970 	default:
    971 		return ((time_t)-1);
    972 	}
    973 
    974 	/* Sanity check */
    975 	if (tm.tm_year < 70 || tm.tm_mon < 0 || tm.tm_mon > 12 ||
    976 	    tm.tm_mday < 1 || tm.tm_mday > 31)
    977 		return ((time_t)-1);
    978 
    979 	if (*t != '\0') {
    980 		s = ++t;
    981 		ul = strtoul(s, &t, 10);
    982 		if (*t != '\0' && !isspace(*t))
    983 			return ((time_t)-1);
    984 
    985 		switch (t - s) {
    986 		case 6:
    987 			tm.tm_sec = ul % 100;
    988 			ul /= 100;
    989 			/* FALLTHROUGH */
    990 		case 4:
    991 			tm.tm_min = ul % 100;
    992 			ul /= 100;
    993 			/* FALLTHROUGH */
    994 		case 2:
    995 			tm.tm_hour = ul;
    996 			/* FALLTHROUGH */
    997 		case 0:
    998 			break;
    999 		default:
   1000 			return ((time_t)-1);
   1001 		}
   1002 
   1003 		/* Sanity check */
   1004 		if (tm.tm_sec < 0 || tm.tm_sec > 60 || tm.tm_min < 0 ||
   1005 		    tm.tm_min > 59 || tm.tm_hour < 0 || tm.tm_hour > 23)
   1006 			return ((time_t)-1);
   1007 	}
   1008 
   1009 	return (mktime(&tm));
   1010 }
   1011