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