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