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