Home | History | Annotate | Line # | Download | only in syslogd
syslogd.c revision 1.66
      1 /*	$NetBSD: syslogd.c,v 1.66 2004/10/08 17:25:52 mycroft Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1983, 1988, 1993, 1994
      5  *	The Regents of the University of California.  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  * 3. Neither the name of the University nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 #include <sys/cdefs.h>
     33 #ifndef lint
     34 __COPYRIGHT("@(#) Copyright (c) 1983, 1988, 1993, 1994\n\
     35 	The Regents of the University of California.  All rights reserved.\n");
     36 #endif /* not lint */
     37 
     38 #ifndef lint
     39 #if 0
     40 static char sccsid[] = "@(#)syslogd.c	8.3 (Berkeley) 4/4/94";
     41 #else
     42 __RCSID("$NetBSD: syslogd.c,v 1.66 2004/10/08 17:25:52 mycroft Exp $");
     43 #endif
     44 #endif /* not lint */
     45 
     46 /*
     47  *  syslogd -- log system messages
     48  *
     49  * This program implements a system log. It takes a series of lines.
     50  * Each line may have a priority, signified as "<n>" as
     51  * the first characters of the line.  If this is
     52  * not present, a default priority is used.
     53  *
     54  * To kill syslogd, send a signal 15 (terminate).  A signal 1 (hup) will
     55  * cause it to reread its configuration file.
     56  *
     57  * Defined Constants:
     58  *
     59  * MAXLINE -- the maximimum line length that can be handled.
     60  * DEFUPRI -- the default priority for user messages
     61  * DEFSPRI -- the default priority for kernel messages
     62  *
     63  * Author: Eric Allman
     64  * extensive changes by Ralph Campbell
     65  * more extensive changes by Eric Allman (again)
     66  */
     67 
     68 #define	MAXLINE		1024		/* maximum line length */
     69 #define	MAXSVLINE	120		/* maximum saved line length */
     70 #define DEFUPRI		(LOG_USER|LOG_NOTICE)
     71 #define DEFSPRI		(LOG_KERN|LOG_CRIT)
     72 #define TIMERINTVL	30		/* interval for checking flush, mark */
     73 #define TTYMSGTIME	1		/* timeout passed to ttymsg */
     74 
     75 #include <sys/param.h>
     76 #include <sys/socket.h>
     77 #include <sys/sysctl.h>
     78 #include <sys/types.h>
     79 #include <sys/un.h>
     80 #include <sys/wait.h>
     81 
     82 #include <netinet/in.h>
     83 
     84 #include <ctype.h>
     85 #include <errno.h>
     86 #include <fcntl.h>
     87 #include <grp.h>
     88 #include <locale.h>
     89 #include <netdb.h>
     90 #include <poll.h>
     91 #include <pwd.h>
     92 #include <signal.h>
     93 #include <stdarg.h>
     94 #include <stdio.h>
     95 #include <stdlib.h>
     96 #include <string.h>
     97 #include <unistd.h>
     98 #include <util.h>
     99 
    100 #include "utmpentry.h"
    101 #include "pathnames.h"
    102 
    103 #define SYSLOG_NAMES
    104 #include <sys/syslog.h>
    105 
    106 #ifdef LIBWRAP
    107 #include <tcpd.h>
    108 
    109 int allow_severity = LOG_AUTH|LOG_INFO;
    110 int deny_severity = LOG_AUTH|LOG_WARNING;
    111 #endif
    112 
    113 char	*ConfFile = _PATH_LOGCONF;
    114 char	ctty[] = _PATH_CONSOLE;
    115 
    116 #define FDMASK(fd)	(1 << (fd))
    117 
    118 #define	dprintf		if (Debug) printf
    119 
    120 #define MAXUNAMES	20	/* maximum number of user names */
    121 
    122 /*
    123  * Flags to logmsg().
    124  */
    125 
    126 #define IGN_CONS	0x001	/* don't print on console */
    127 #define SYNC_FILE	0x002	/* do fsync on file after printing */
    128 #define ADDDATE		0x004	/* add a date to the message */
    129 #define MARK		0x008	/* this message is a mark */
    130 
    131 /*
    132  * This structure represents the files that will have log
    133  * copies printed.
    134  */
    135 
    136 struct filed {
    137 	struct	filed *f_next;		/* next in linked list */
    138 	short	f_type;			/* entry type, see below */
    139 	short	f_file;			/* file descriptor */
    140 	time_t	f_time;			/* time this was last written */
    141 	u_char	f_pmask[LOG_NFACILITIES+1];	/* priority mask */
    142 	union {
    143 		char	f_uname[MAXUNAMES][UT_NAMESIZE+1];
    144 		struct {
    145 			char	f_hname[MAXHOSTNAMELEN+1];
    146 			struct	addrinfo *f_addr;
    147 		} f_forw;		/* forwarding address */
    148 		char	f_fname[MAXPATHLEN];
    149 	} f_un;
    150 	char	f_prevline[MAXSVLINE];		/* last message logged */
    151 	char	f_lasttime[16];			/* time of last occurrence */
    152 	char	f_prevhost[MAXHOSTNAMELEN+1];	/* host from which recd. */
    153 	int	f_prevpri;			/* pri of f_prevline */
    154 	int	f_prevlen;			/* length of f_prevline */
    155 	int	f_prevcount;			/* repetition cnt of prevline */
    156 	int	f_repeatcount;			/* number of "repeated" msgs */
    157 };
    158 
    159 /*
    160  * Intervals at which we flush out "message repeated" messages,
    161  * in seconds after previous message is logged.  After each flush,
    162  * we move to the next interval until we reach the largest.
    163  */
    164 int	repeatinterval[] = { 30, 120, 600 };	/* # of secs before flush */
    165 #define	MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
    166 #define	REPEATTIME(f)	((f)->f_time + repeatinterval[(f)->f_repeatcount])
    167 #define	BACKOFF(f)	{ if (++(f)->f_repeatcount > MAXREPEAT) \
    168 				 (f)->f_repeatcount = MAXREPEAT; \
    169 			}
    170 
    171 /* values for f_type */
    172 #define F_UNUSED	0		/* unused entry */
    173 #define F_FILE		1		/* regular file */
    174 #define F_TTY		2		/* terminal */
    175 #define F_CONSOLE	3		/* console terminal */
    176 #define F_FORW		4		/* remote machine */
    177 #define F_USERS		5		/* list of users */
    178 #define F_WALL		6		/* everyone logged on */
    179 
    180 char	*TypeNames[7] = {
    181 	"UNUSED",	"FILE",		"TTY",		"CONSOLE",
    182 	"FORW",		"USERS",	"WALL"
    183 };
    184 
    185 struct	filed *Files;
    186 struct	filed consfile;
    187 
    188 int	Debug;			/* debug flag */
    189 int	daemonized = 0;		/* we are not daemonized yet */
    190 char	LocalHostName[MAXHOSTNAMELEN+1];	/* our hostname */
    191 char	*LocalDomain;		/* our local domain name */
    192 int	*finet = NULL;		/* Internet datagram sockets */
    193 int	Initialized = 0;	/* set when we have initialized ourselves */
    194 int	MarkInterval = 20 * 60;	/* interval between marks in seconds */
    195 int	MarkSeq = 0;		/* mark sequence number */
    196 int	SecureMode = 0;		/* listen only on unix domain socks */
    197 int	UseNameService = 1;	/* make domain name queries */
    198 int	NumForwards = 0;	/* number of forwarding actions in conf file */
    199 char	**LogPaths;		/* array of pathnames to read messages from */
    200 int	NoRepeat = 0;		/* disable "repeated"; log always */
    201 int	SyncKernel = 0;		/* write kernel messages synchronously */
    202 volatile sig_atomic_t gothup = 0; /* got SIGHUP */
    203 
    204 void	cfline(char *, struct filed *);
    205 char   *cvthname(struct sockaddr_storage *);
    206 int	decode(const char *, CODE *);
    207 void	die(int);
    208 void	domark(int);
    209 void	fprintlog(struct filed *, int, char *);
    210 int	getmsgbufsize(void);
    211 int*	socksetup(int);
    212 void	init(void);
    213 void	logerror(const char *, ...);
    214 void	logmsg(int, char *, char *, int);
    215 void	printline(char *, char *);
    216 void	printsys(char *);
    217 void	sighup(int);
    218 void	reapchild(int);
    219 void	usage(void);
    220 void	wallmsg(struct filed *, struct iovec *);
    221 int	main(int, char *[]);
    222 void	logpath_add(char ***, int *, int *, char *);
    223 void	logpath_fileadd(char ***, int *, int *, char *);
    224 
    225 int
    226 main(int argc, char *argv[])
    227 {
    228 	int ch, *funix, i, j, fklog, len, linesize;
    229 	int *nfinetix, nfklogix, nfunixbaseix, nfds;
    230 	int funixsize = 0, funixmaxsize = 0;
    231 	struct sockaddr_un sunx, fromunix;
    232 	struct sockaddr_storage frominet;
    233 	char *p, *line, **pp;
    234 	struct pollfd *readfds;
    235 	uid_t uid = 0;
    236 	gid_t gid = 0;
    237 	char *user = NULL;
    238 	char *group = NULL;
    239 	char *root = "/";
    240 	char *endp;
    241 	struct group   *gr;
    242 	struct passwd  *pw;
    243 	unsigned long l;
    244 
    245 	(void)setlocale(LC_ALL, "");
    246 
    247 	while ((ch = getopt(argc, argv, "dnsSf:m:p:P:ru:g:t:")) != -1)
    248 		switch(ch) {
    249 		case 'd':		/* debug */
    250 			Debug++;
    251 			break;
    252 		case 'f':		/* configuration file */
    253 			ConfFile = optarg;
    254 			break;
    255 		case 'g':
    256 			group = optarg;
    257 			if (*group == '\0')
    258 				usage();
    259 			break;
    260 		case 'm':		/* mark interval */
    261 			MarkInterval = atoi(optarg) * 60;
    262 			break;
    263 		case 'n':		/* turn off DNS queries */
    264 			UseNameService = 0;
    265 			break;
    266 		case 'p':		/* path */
    267 			logpath_add(&LogPaths, &funixsize,
    268 			    &funixmaxsize, optarg);
    269 			break;
    270 		case 'P':		/* file of paths */
    271 			logpath_fileadd(&LogPaths, &funixsize,
    272 			    &funixmaxsize, optarg);
    273 			break;
    274 		case 'r':		/* disable "repeated" compression */
    275 			NoRepeat++;
    276 			break;
    277 		case 's':		/* no network listen mode */
    278 			SecureMode++;
    279 			break;
    280 		case 'S':
    281 			SyncKernel = 1;
    282 			break;
    283 		case 't':
    284 			root = optarg;
    285 			if (*root == '\0')
    286 				usage();
    287 			break;
    288 		case 'u':
    289 			user = optarg;
    290 			if (*user == '\0')
    291 				usage();
    292 			break;
    293 		default:
    294 			usage();
    295 		}
    296 	if ((argc -= optind) != 0)
    297 		usage();
    298 
    299 	setlinebuf(stdout);
    300 
    301 	if (user != NULL) {
    302 		if (isdigit((unsigned char)*user)) {
    303 			errno = 0;
    304 			endp = NULL;
    305 			l = strtoul(user, &endp, 0);
    306 			if (errno || *endp != '\0')
    307 	    			goto getuser;
    308 			uid = (uid_t)l;
    309 			if (uid != l) {
    310 				errno = 0;
    311 				logerror("UID out of range");
    312 				die(0);
    313 			}
    314 		} else {
    315 getuser:
    316 			if ((pw = getpwnam(user)) != NULL) {
    317 				uid = pw->pw_uid;
    318 			} else {
    319 				errno = 0;
    320 				logerror("Cannot find user `%s'", user);
    321 				die (0);
    322 			}
    323 		}
    324 	}
    325 
    326 	if (group != NULL) {
    327 		if (isdigit((unsigned char)*group)) {
    328 			errno = 0;
    329 			endp = NULL;
    330 			l = strtoul(group, &endp, 0);
    331 			if (errno || *endp != '\0')
    332 	    			goto getgroup;
    333 			gid = (gid_t)l;
    334 			if (gid != l) {
    335 				errno = 0;
    336 				logerror("GID out of range");
    337 				die(0);
    338 			}
    339 		} else {
    340 getgroup:
    341 			if ((gr = getgrnam(group)) != NULL) {
    342 				gid = gr->gr_gid;
    343 			} else {
    344 				errno = 0;
    345 				logerror("Cannot find group `%s'", group);
    346 				die(0);
    347 			}
    348 		}
    349 	}
    350 
    351 	if (access (root, F_OK | R_OK)) {
    352 		logerror("Cannot access `%s'", root);
    353 		die (0);
    354 	}
    355 
    356 	consfile.f_type = F_CONSOLE;
    357 	(void)strlcpy(consfile.f_un.f_fname, ctty,
    358 	    sizeof(consfile.f_un.f_fname));
    359 	(void)gethostname(LocalHostName, sizeof(LocalHostName));
    360 	LocalHostName[sizeof(LocalHostName) - 1] = '\0';
    361 	if ((p = strchr(LocalHostName, '.')) != NULL) {
    362 		*p++ = '\0';
    363 		LocalDomain = p;
    364 	} else
    365 		LocalDomain = "";
    366 	linesize = getmsgbufsize();
    367 	if (linesize < MAXLINE)
    368 		linesize = MAXLINE;
    369 	linesize++;
    370 	line = malloc(linesize);
    371 	if (line == NULL) {
    372 		logerror("Couldn't allocate line buffer");
    373 		die(0);
    374 	}
    375 	(void)signal(SIGTERM, die);
    376 	(void)signal(SIGINT, Debug ? die : SIG_IGN);
    377 	(void)signal(SIGQUIT, Debug ? die : SIG_IGN);
    378 	(void)signal(SIGCHLD, reapchild);
    379 	(void)signal(SIGALRM, domark);
    380 	(void)alarm(TIMERINTVL);
    381 
    382 #ifndef SUN_LEN
    383 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
    384 #endif
    385 	if (funixsize == 0)
    386 		logpath_add(&LogPaths, &funixsize,
    387 		    &funixmaxsize, _PATH_LOG);
    388 	funix = (int *)malloc(sizeof(int) * funixsize);
    389 	if (funix == NULL) {
    390 		logerror("Couldn't allocate funix descriptors");
    391 		die(0);
    392 	}
    393 	for (j = 0, pp = LogPaths; *pp; pp++, j++) {
    394 		dprintf("Making unix dgram socket `%s'\n", *pp);
    395 		unlink(*pp);
    396 		memset(&sunx, 0, sizeof(sunx));
    397 		sunx.sun_family = AF_LOCAL;
    398 		(void)strncpy(sunx.sun_path, *pp, sizeof(sunx.sun_path));
    399 		funix[j] = socket(AF_LOCAL, SOCK_DGRAM, 0);
    400 		if (funix[j] < 0 || bind(funix[j],
    401 		    (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
    402 		    chmod(*pp, 0666) < 0) {
    403 			logerror("Cannot create `%s'", *pp);
    404 			die(0);
    405 		}
    406 		dprintf("Listening on unix dgram socket `%s'\n", *pp);
    407 	}
    408 
    409 	init();
    410 
    411 	if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) < 0) {
    412 		dprintf("Can't open `%s' (%d)\n", _PATH_KLOG, errno);
    413 	} else {
    414 		dprintf("Listening on kernel log `%s'\n", _PATH_KLOG);
    415 	}
    416 
    417 	dprintf("Off & running....\n");
    418 
    419 	(void)signal(SIGHUP, sighup);
    420 
    421 	/* setup pollfd set. */
    422 	readfds = (struct pollfd *)malloc(sizeof(struct pollfd) *
    423 			(funixsize + (finet ? *finet : 0) + 1));
    424 	if (readfds == NULL) {
    425 		logerror("Couldn't allocate pollfds");
    426 		die(0);
    427 	}
    428 	nfds = 0;
    429 	if (fklog >= 0) {
    430 		nfklogix = nfds++;
    431 		readfds[nfklogix].fd = fklog;
    432 		readfds[nfklogix].events = POLLIN | POLLPRI;
    433 	}
    434 	if (finet && !SecureMode) {
    435 		nfinetix = malloc(*finet * sizeof(*nfinetix));
    436 		for (j = 0; j < *finet; j++) {
    437 			nfinetix[j] = nfds++;
    438 			readfds[nfinetix[j]].fd = finet[j+1];
    439 			readfds[nfinetix[j]].events = POLLIN | POLLPRI;
    440 		}
    441 	}
    442 	nfunixbaseix = nfds;
    443 	for (j = 0, pp = LogPaths; *pp; pp++) {
    444 		readfds[nfds].fd = funix[j++];
    445 		readfds[nfds++].events = POLLIN | POLLPRI;
    446 	}
    447 
    448 	/*
    449 	 * All files are open, we can drop privileges and chroot
    450 	 */
    451 	dprintf("Attempt to chroot to `%s'\n", root);
    452 	if (chroot(root)) {
    453 		logerror("Failed to chroot to `%s'", root);
    454 		die(0);
    455 	}
    456 	dprintf("Attempt to set GID/EGID to `%d'\n", gid);
    457 	if (setgid(gid) || setegid(gid)) {
    458 		logerror("Failed to set gid to `%d'", gid);
    459 		die(0);
    460 	}
    461 	dprintf("Attempt to set UID/EUID to `%d'\n", uid);
    462 	if (setuid(uid) || seteuid(uid)) {
    463 		logerror("Failed to set uid to `%d'", uid);
    464 		die(0);
    465 	}
    466 
    467 	/*
    468 	 * We cannot detach from the terminal before we are sure we won't
    469 	 * have a fatal error, because error message would not go to the
    470 	 * terminal and would not be logged because syslogd dies.
    471 	 * All die() calls are behind us, we can call daemon()
    472 	 */
    473 	if (!Debug) {
    474 		(void)daemon(0, 0);
    475 		daemonized = 1;
    476 
    477 		/* tuck my process id away, if i'm not in debug mode */
    478 		pidfile(NULL);
    479 	}
    480 
    481 	for (;;) {
    482 		int rv;
    483 
    484 		rv = poll(readfds, nfds, INFTIM);
    485 		if (rv == 0)
    486 			continue;
    487 		if (rv < 0) {
    488 			if (errno != EINTR)
    489 				logerror("poll() failed");
    490 			if (gothup) {
    491 				init();
    492 				gothup = 0;
    493 			}
    494 			continue;
    495 		}
    496 		dprintf("Got a message (%d)\n", rv);
    497 		if (fklog >= 0 &&
    498 		    (readfds[nfklogix].revents & (POLLIN | POLLPRI))) {
    499 			dprintf("Kernel log active\n");
    500 			i = read(fklog, line, linesize - 1);
    501 			if (i > 0) {
    502 				line[i] = '\0';
    503 				printsys(line);
    504 			} else if (i < 0 && errno != EINTR) {
    505 				logerror("klog failed");
    506 				fklog = -1;
    507 			}
    508 		}
    509 		for (j = 0, pp = LogPaths; *pp; pp++, j++) {
    510 			if ((readfds[nfunixbaseix + j].revents &
    511 			    (POLLIN | POLLPRI)) == 0)
    512 				continue;
    513 
    514 			dprintf("Unix socket (%s) active\n", *pp);
    515 			len = sizeof(fromunix);
    516 			i = recvfrom(funix[j], line, MAXLINE, 0,
    517 			    (struct sockaddr *)&fromunix, &len);
    518 			if (i > 0) {
    519 				line[i] = '\0';
    520 				printline(LocalHostName, line);
    521 			} else if (i < 0 && errno != EINTR) {
    522 				logerror("recvfrom() unix `%s'", *pp);
    523 			}
    524 		}
    525 		if (finet && !SecureMode) {
    526 			for (j = 0; j < *finet; j++) {
    527 		    		if (readfds[nfinetix[j]].revents &
    528 				    (POLLIN | POLLPRI)) {
    529 #ifdef LIBWRAP
    530 					struct request_info req;
    531 #endif
    532 					int reject = 0;
    533 
    534 					dprintf("inet socket active\n");
    535 
    536 #ifdef LIBWRAP
    537 					request_init(&req, RQ_DAEMON, "syslogd",
    538 					    RQ_FILE, finet[j + 1], NULL);
    539 					fromhost(&req);
    540 					reject = !hosts_access(&req);
    541 					if (reject)
    542 						dprintf("access denied\n");
    543 #endif
    544 
    545 					len = sizeof(frominet);
    546 					i = recvfrom(finet[j+1], line, MAXLINE,
    547 					    0, (struct sockaddr *)&frominet,
    548 					    &len);
    549 					if (i == 0 || (i < 0 && errno == EINTR))
    550 						continue;
    551 					else if (i < 0) {
    552 						logerror("recvfrom inet");
    553 						continue;
    554 					}
    555 
    556 					line[i] = '\0';
    557 					if (!reject)
    558 						printline(cvthname(&frominet),
    559 						    line);
    560 				}
    561 			}
    562 		}
    563 	}
    564 }
    565 
    566 void
    567 usage(void)
    568 {
    569 
    570 	(void)fprintf(stderr,
    571 	    "usage: %s [-dnrs] [-f config_file] [-g group] [-m mark_interval]\n"
    572 	    "\t[-P file_list] [-p log_socket [-p log_socket2 ...]]\n"
    573 	    "\t[-t chroot_dir] [-u user]\n", getprogname());
    574 	exit(1);
    575 }
    576 
    577 /*
    578  * given a pointer to an array of char *'s, a pointer to it's current
    579  * size and current allocated max size, and a new char * to add, add
    580  * it, update everything as necessary, possibly allocating a new array
    581  */
    582 void
    583 logpath_add(char ***lp, int *szp, int *maxszp, char *new)
    584 {
    585 	char **nlp;
    586 	int newmaxsz;
    587 
    588 	dprintf("Adding `%s' to the %p logpath list\n", new, *lp);
    589 	if (*szp == *maxszp) {
    590 		if (*maxszp == 0) {
    591 			newmaxsz = 4;	/* start of with enough for now */
    592 			*lp = NULL;
    593 		} else
    594 			newmaxsz = *maxszp * 2;
    595 		nlp = realloc(*lp, sizeof(char *) * (newmaxsz + 1));
    596 		if (nlp == NULL) {
    597 			logerror("Couldn't allocate line buffer");
    598 			die(0);
    599 		}
    600 		*lp = nlp;
    601 		*maxszp = newmaxsz;
    602 	}
    603 	if (((*lp)[(*szp)++] = strdup(new)) == NULL) {
    604 		logerror("Couldn't allocate logpath");
    605 		die(0);
    606 	}
    607 	(*lp)[(*szp)] = NULL;		/* always keep it NULL terminated */
    608 }
    609 
    610 /* do a file of log sockets */
    611 void
    612 logpath_fileadd(char ***lp, int *szp, int *maxszp, char *file)
    613 {
    614 	FILE *fp;
    615 	char *line;
    616 	size_t len;
    617 
    618 	fp = fopen(file, "r");
    619 	if (fp == NULL) {
    620 		logerror("Could not open socket file list `%s'", file);
    621 		die(0);
    622 	}
    623 
    624 	while ((line = fgetln(fp, &len))) {
    625 		line[len - 1] = 0;
    626 		logpath_add(lp, szp, maxszp, line);
    627 	}
    628 	fclose(fp);
    629 }
    630 
    631 /*
    632  * Take a raw input line, decode the message, and print the message
    633  * on the appropriate log files.
    634  */
    635 void
    636 printline(char *hname, char *msg)
    637 {
    638 	int c, pri;
    639 	char *p, *q, line[MAXLINE + 1];
    640 
    641 	/* test for special codes */
    642 	pri = DEFUPRI;
    643 	p = msg;
    644 	if (*p == '<') {
    645 		pri = 0;
    646 		while (isdigit(*++p))
    647 			pri = 10 * pri + (*p - '0');
    648 		if (*p == '>')
    649 			++p;
    650 	}
    651 	if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
    652 		pri = DEFUPRI;
    653 
    654 	/* don't allow users to log kernel messages */
    655 	if (LOG_FAC(pri) == LOG_KERN)
    656 		pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
    657 
    658 	q = line;
    659 
    660 	while ((c = *p++) != '\0' &&
    661 	    q < &line[sizeof(line) - 2]) {
    662 		c &= 0177;
    663 		if (iscntrl(c))
    664 			if (c == '\n')
    665 				*q++ = ' ';
    666 			else if (c == '\t')
    667 				*q++ = '\t';
    668 			else {
    669 				*q++ = '^';
    670 				*q++ = c ^ 0100;
    671 			}
    672 		else
    673 			*q++ = c;
    674 	}
    675 	*q = '\0';
    676 
    677 	logmsg(pri, line, hname, 0);
    678 }
    679 
    680 /*
    681  * Take a raw input line from /dev/klog, split and format similar to syslog().
    682  */
    683 void
    684 printsys(char *msg)
    685 {
    686 	int c, pri, flags;
    687 	char *lp, *p, *q, line[MAXLINE + 1];
    688 
    689 	(void)strlcpy(line, _PATH_UNIX, sizeof(line));
    690 	(void)strlcat(line, ": ", sizeof(line));
    691 	lp = line + strlen(line);
    692 	for (p = msg; *p != '\0'; ) {
    693 		flags = ADDDATE;
    694 		if (SyncKernel)
    695 			flags |= SYNC_FILE;
    696 		pri = DEFSPRI;
    697 		if (*p == '<') {
    698 			pri = 0;
    699 			while (isdigit(*++p))
    700 				pri = 10 * pri + (*p - '0');
    701 			if (*p == '>')
    702 				++p;
    703 		} else {
    704 			/* kernel printf's come out on console */
    705 			flags |= IGN_CONS;
    706 		}
    707 		if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
    708 			pri = DEFSPRI;
    709 		q = lp;
    710 		while (*p != '\0' && (c = *p++) != '\n' &&
    711 		    q < &line[MAXLINE])
    712 			*q++ = c;
    713 		*q = '\0';
    714 		logmsg(pri, line, LocalHostName, flags);
    715 	}
    716 }
    717 
    718 time_t	now;
    719 
    720 /*
    721  * Log a message to the appropriate log files, users, etc. based on
    722  * the priority.
    723  */
    724 void
    725 logmsg(int pri, char *msg, char *from, int flags)
    726 {
    727 	struct filed *f;
    728 	int fac, msglen, omask, prilev;
    729 	char *timestamp;
    730 
    731 	dprintf("logmsg: pri 0%o, flags 0x%x, from %s, msg %s\n",
    732 	    pri, flags, from, msg);
    733 
    734 	omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
    735 
    736 	/*
    737 	 * Check to see if msg looks non-standard.
    738 	 */
    739 	msglen = strlen(msg);
    740 	if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
    741 	    msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
    742 		flags |= ADDDATE;
    743 
    744 	(void)time(&now);
    745 	if (flags & ADDDATE)
    746 		timestamp = ctime(&now) + 4;
    747 	else {
    748 		timestamp = msg;
    749 		msg += 16;
    750 		msglen -= 16;
    751 	}
    752 
    753 	/* extract facility and priority level */
    754 	if (flags & MARK)
    755 		fac = LOG_NFACILITIES;
    756 	else
    757 		fac = LOG_FAC(pri);
    758 	prilev = LOG_PRI(pri);
    759 
    760 	/* log the message to the particular outputs */
    761 	if (!Initialized) {
    762 		f = &consfile;
    763 		f->f_file = open(ctty, O_WRONLY, 0);
    764 
    765 		if (f->f_file >= 0) {
    766 			fprintlog(f, flags, msg);
    767 			(void)close(f->f_file);
    768 		}
    769 		(void)sigsetmask(omask);
    770 		return;
    771 	}
    772 	for (f = Files; f; f = f->f_next) {
    773 		/* skip messages that are incorrect priority */
    774 		if (f->f_pmask[fac] < prilev ||
    775 		    f->f_pmask[fac] == INTERNAL_NOPRI)
    776 			continue;
    777 
    778 		if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
    779 			continue;
    780 
    781 		/* don't output marks to recently written files */
    782 		if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
    783 			continue;
    784 
    785 		/*
    786 		 * suppress duplicate lines to this file unless NoRepeat
    787 		 */
    788 		if ((flags & MARK) == 0 && msglen == f->f_prevlen &&
    789 		    !NoRepeat &&
    790 		    !strcmp(msg, f->f_prevline) &&
    791 		    !strcmp(from, f->f_prevhost)) {
    792 			(void)strncpy(f->f_lasttime, timestamp, 15);
    793 			f->f_prevcount++;
    794 			dprintf("Msg repeated %d times, %ld sec of %d\n",
    795 			    f->f_prevcount, (long)(now - f->f_time),
    796 			    repeatinterval[f->f_repeatcount]);
    797 			/*
    798 			 * If domark would have logged this by now,
    799 			 * flush it now (so we don't hold isolated messages),
    800 			 * but back off so we'll flush less often
    801 			 * in the future.
    802 			 */
    803 			if (now > REPEATTIME(f)) {
    804 				fprintlog(f, flags, (char *)NULL);
    805 				BACKOFF(f);
    806 			}
    807 		} else {
    808 			/* new line, save it */
    809 			if (f->f_prevcount)
    810 				fprintlog(f, 0, (char *)NULL);
    811 			f->f_repeatcount = 0;
    812 			f->f_prevpri = pri;
    813 			(void)strncpy(f->f_lasttime, timestamp, 15);
    814 			(void)strncpy(f->f_prevhost, from,
    815 					sizeof(f->f_prevhost));
    816 			if (msglen < MAXSVLINE) {
    817 				f->f_prevlen = msglen;
    818 				(void)strlcpy(f->f_prevline, msg,
    819 				    sizeof(f->f_prevline));
    820 				fprintlog(f, flags, (char *)NULL);
    821 			} else {
    822 				f->f_prevline[0] = 0;
    823 				f->f_prevlen = 0;
    824 				fprintlog(f, flags, msg);
    825 			}
    826 		}
    827 	}
    828 	(void)sigsetmask(omask);
    829 }
    830 
    831 void
    832 fprintlog(struct filed *f, int flags, char *msg)
    833 {
    834 	struct iovec iov[6];
    835 	struct iovec *v;
    836 	struct addrinfo *r;
    837 	int j, l, lsent;
    838 	char line[MAXLINE + 1], repbuf[80], greetings[200];
    839 
    840 	v = iov;
    841 	if (f->f_type == F_WALL) {
    842 		v->iov_base = greetings;
    843 		v->iov_len = snprintf(greetings, sizeof greetings,
    844 		    "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
    845 		    f->f_prevhost, ctime(&now));
    846 		v++;
    847 		v->iov_base = "";
    848 		v->iov_len = 0;
    849 		v++;
    850 	} else {
    851 		v->iov_base = f->f_lasttime;
    852 		v->iov_len = 15;
    853 		v++;
    854 		v->iov_base = " ";
    855 		v->iov_len = 1;
    856 		v++;
    857 	}
    858 	v->iov_base = f->f_prevhost;
    859 	v->iov_len = strlen(v->iov_base);
    860 	v++;
    861 	v->iov_base = " ";
    862 	v->iov_len = 1;
    863 	v++;
    864 
    865 	if (msg) {
    866 		v->iov_base = msg;
    867 		v->iov_len = strlen(msg);
    868 	} else if (f->f_prevcount > 1) {
    869 		v->iov_base = repbuf;
    870 		v->iov_len = snprintf(repbuf, sizeof repbuf,
    871 		    "last message repeated %d times", f->f_prevcount);
    872 	} else {
    873 		v->iov_base = f->f_prevline;
    874 		v->iov_len = f->f_prevlen;
    875 	}
    876 	v++;
    877 
    878 	dprintf("Logging to %s", TypeNames[f->f_type]);
    879 	f->f_time = now;
    880 
    881 	switch (f->f_type) {
    882 	case F_UNUSED:
    883 		dprintf("\n");
    884 		break;
    885 
    886 	case F_FORW:
    887 		dprintf(" %s\n", f->f_un.f_forw.f_hname);
    888 			/*
    889 			 * check for local vs remote messages
    890 			 * (from FreeBSD PR#bin/7055)
    891 			 */
    892 		if (strcmp(f->f_prevhost, LocalHostName)) {
    893 			l = snprintf(line, sizeof(line) - 1,
    894 				     "<%d>%.15s [%s]: %s",
    895 				     f->f_prevpri, (char *) iov[0].iov_base,
    896 				     f->f_prevhost, (char *) iov[4].iov_base);
    897 		} else {
    898 			l = snprintf(line, sizeof(line) - 1, "<%d>%.15s %s",
    899 				     f->f_prevpri, (char *) iov[0].iov_base,
    900 				     (char *) iov[4].iov_base);
    901 		}
    902 		if (l > MAXLINE)
    903 			l = MAXLINE;
    904 		if (finet) {
    905 			for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
    906 				for (j = 0; j < *finet; j++) {
    907 #if 0
    908 					/*
    909 					 * should we check AF first, or just
    910 					 * trial and error? FWD
    911 					 */
    912 					if (r->ai_family ==
    913 					    address_family_of(finet[j+1]))
    914 #endif
    915 					lsent = sendto(finet[j+1], line, l, 0,
    916 					    r->ai_addr, r->ai_addrlen);
    917 					if (lsent == l)
    918 						break;
    919 				}
    920 			}
    921 			if (lsent != l) {
    922 				f->f_type = F_UNUSED;
    923 				logerror("sendto() failed");
    924 			}
    925 		}
    926 		break;
    927 
    928 	case F_CONSOLE:
    929 		if (flags & IGN_CONS) {
    930 			dprintf(" (ignored)\n");
    931 			break;
    932 		}
    933 		/* FALLTHROUGH */
    934 
    935 	case F_TTY:
    936 	case F_FILE:
    937 		dprintf(" %s\n", f->f_un.f_fname);
    938 		if (f->f_type != F_FILE) {
    939 			v->iov_base = "\r\n";
    940 			v->iov_len = 2;
    941 		} else {
    942 			v->iov_base = "\n";
    943 			v->iov_len = 1;
    944 		}
    945 	again:
    946 		if (writev(f->f_file, iov, 6) < 0) {
    947 			int e = errno;
    948 			(void)close(f->f_file);
    949 			/*
    950 			 * Check for errors on TTY's due to loss of tty
    951 			 */
    952 			if ((e == EIO || e == EBADF) && f->f_type != F_FILE) {
    953 				f->f_file = open(f->f_un.f_fname,
    954 				    O_WRONLY|O_APPEND, 0);
    955 				if (f->f_file < 0) {
    956 					f->f_type = F_UNUSED;
    957 					logerror(f->f_un.f_fname);
    958 				} else
    959 					goto again;
    960 			} else {
    961 				f->f_type = F_UNUSED;
    962 				errno = e;
    963 				logerror(f->f_un.f_fname);
    964 			}
    965 		} else if (flags & SYNC_FILE)
    966 			(void)fsync(f->f_file);
    967 		break;
    968 
    969 	case F_USERS:
    970 	case F_WALL:
    971 		dprintf("\n");
    972 		v->iov_base = "\r\n";
    973 		v->iov_len = 2;
    974 		wallmsg(f, iov);
    975 		break;
    976 	}
    977 	f->f_prevcount = 0;
    978 }
    979 
    980 /*
    981  *  WALLMSG -- Write a message to the world at large
    982  *
    983  *	Write the specified message to either the entire
    984  *	world, or a list of approved users.
    985  */
    986 void
    987 wallmsg(struct filed *f, struct iovec *iov)
    988 {
    989 	static int reenter;			/* avoid calling ourselves */
    990 	int i;
    991 	char *p;
    992 	static struct utmpentry *ohead = NULL;
    993 	struct utmpentry *ep;
    994 
    995 	if (reenter++)
    996 		return;
    997 
    998 	(void)getutentries(NULL, &ep);
    999 	if (ep != ohead) {
   1000 		freeutentries(ohead);
   1001 		ohead = ep;
   1002 	}
   1003 	/* NOSTRICT */
   1004 	for (; ep; ep = ep->next) {
   1005 		if (f->f_type == F_WALL) {
   1006 			if ((p = ttymsg(iov, 6, ep->line, TTYMSGTIME))
   1007 			    != NULL) {
   1008 				errno = 0;	/* already in msg */
   1009 				logerror(p);
   1010 			}
   1011 			continue;
   1012 		}
   1013 		/* should we send the message to this user? */
   1014 		for (i = 0; i < MAXUNAMES; i++) {
   1015 			if (!f->f_un.f_uname[i][0])
   1016 				break;
   1017 			if (strcmp(f->f_un.f_uname[i], ep->name) == 0) {
   1018 				if ((p = ttymsg(iov, 6, ep->line, TTYMSGTIME))
   1019 				    != NULL) {
   1020 					errno = 0;	/* already in msg */
   1021 					logerror(p);
   1022 				}
   1023 				break;
   1024 			}
   1025 		}
   1026 	}
   1027 	reenter = 0;
   1028 }
   1029 
   1030 void
   1031 sighup(int signo)
   1032 {
   1033 
   1034 	gothup = 1;
   1035 }
   1036 
   1037 void
   1038 reapchild(int signo)
   1039 {
   1040 	union wait status;
   1041 
   1042 	while (wait3((int *)&status, WNOHANG, (struct rusage *)NULL) > 0)
   1043 		;
   1044 }
   1045 
   1046 /*
   1047  * Return a printable representation of a host address.
   1048  */
   1049 char *
   1050 cvthname(struct sockaddr_storage *f)
   1051 {
   1052 	int error;
   1053 	char *p;
   1054 	const int niflag = NI_DGRAM;
   1055 	static char host[NI_MAXHOST], ip[NI_MAXHOST];
   1056 
   1057 	error = getnameinfo((struct sockaddr*)f, ((struct sockaddr*)f)->sa_len,
   1058 			ip, sizeof ip, NULL, 0, NI_NUMERICHOST|niflag);
   1059 
   1060 	dprintf("cvthname(%s)\n", ip);
   1061 
   1062 	if (error) {
   1063 		dprintf("Malformed from address %s\n", gai_strerror(error));
   1064 		return ("???");
   1065 	}
   1066 
   1067 	if (!UseNameService)
   1068 		return (ip);
   1069 
   1070 	error = getnameinfo((struct sockaddr*)f, ((struct sockaddr*)f)->sa_len,
   1071 			host, sizeof host, NULL, 0, niflag);
   1072 	if (error) {
   1073 		dprintf("Host name for your address (%s) unknown\n", ip);
   1074 		return (ip);
   1075 	}
   1076 	if ((p = strchr(host, '.')) && strcmp(p + 1, LocalDomain) == 0)
   1077 		*p = '\0';
   1078 	return (host);
   1079 }
   1080 
   1081 void
   1082 domark(int signo)
   1083 {
   1084 	struct filed *f;
   1085 
   1086 	now = time((time_t *)NULL);
   1087 	MarkSeq += TIMERINTVL;
   1088 	if (MarkSeq >= MarkInterval) {
   1089 		logmsg(LOG_INFO, "-- MARK --", LocalHostName, ADDDATE|MARK);
   1090 		MarkSeq = 0;
   1091 	}
   1092 
   1093 	for (f = Files; f; f = f->f_next) {
   1094 		if (f->f_prevcount && now >= REPEATTIME(f)) {
   1095 			dprintf("Flush %s: repeated %d times, %d sec.\n",
   1096 			    TypeNames[f->f_type], f->f_prevcount,
   1097 			    repeatinterval[f->f_repeatcount]);
   1098 			fprintlog(f, 0, (char *)NULL);
   1099 			BACKOFF(f);
   1100 		}
   1101 	}
   1102 	(void)alarm(TIMERINTVL);
   1103 }
   1104 
   1105 /*
   1106  * Print syslogd errors some place.
   1107  */
   1108 void
   1109 logerror(const char *fmt, ...)
   1110 {
   1111 	va_list ap;
   1112 	char tmpbuf[BUFSIZ];
   1113 	char buf[BUFSIZ];
   1114 
   1115 	va_start(ap, fmt);
   1116 
   1117 	(void)vsnprintf(tmpbuf, sizeof(tmpbuf), fmt, ap);
   1118 
   1119 	va_end(ap);
   1120 
   1121 	if (errno)
   1122 		(void)snprintf(buf, sizeof(buf), "syslogd: %s: %s",
   1123 		    tmpbuf, strerror(errno));
   1124 	else
   1125 		(void)snprintf(buf, sizeof(buf), "syslogd: %s", tmpbuf);
   1126 
   1127 	if (daemonized)
   1128 		logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
   1129 	if (!daemonized && Debug)
   1130 		dprintf("%s\n", buf);
   1131 	if (!daemonized && !Debug)
   1132 		printf("%s\n", buf);
   1133 
   1134 	return;
   1135 }
   1136 
   1137 void
   1138 die(int signo)
   1139 {
   1140 	struct filed *f;
   1141 	char **p;
   1142 
   1143 	for (f = Files; f != NULL; f = f->f_next) {
   1144 		/* flush any pending output */
   1145 		if (f->f_prevcount)
   1146 			fprintlog(f, 0, (char *)NULL);
   1147 	}
   1148 	errno = 0;
   1149 	if (signo)
   1150 		logerror("Exiting on signal %d", signo);
   1151 	else
   1152 		logerror("Fatal error, exiting");
   1153 	for (p = LogPaths; p && *p; p++)
   1154 		unlink(*p);
   1155 	exit(0);
   1156 }
   1157 
   1158 /*
   1159  *  INIT -- Initialize syslogd from configuration table
   1160  */
   1161 void
   1162 init(void)
   1163 {
   1164 	int i;
   1165 	FILE *cf;
   1166 	struct filed *f, *next, **nextp;
   1167 	char *p;
   1168 	char cline[LINE_MAX];
   1169 
   1170 	dprintf("init\n");
   1171 
   1172 	/*
   1173 	 *  Close all open log files.
   1174 	 */
   1175 	Initialized = 0;
   1176 	for (f = Files; f != NULL; f = next) {
   1177 		/* flush any pending output */
   1178 		if (f->f_prevcount)
   1179 			fprintlog(f, 0, (char *)NULL);
   1180 
   1181 		switch (f->f_type) {
   1182 		case F_FILE:
   1183 		case F_TTY:
   1184 		case F_CONSOLE:
   1185 			(void)close(f->f_file);
   1186 			break;
   1187 		case F_FORW:
   1188 			if (f->f_un.f_forw.f_addr)
   1189 				freeaddrinfo(f->f_un.f_forw.f_addr);
   1190 			break;
   1191 		}
   1192 		next = f->f_next;
   1193 		free((char *)f);
   1194 	}
   1195 	Files = NULL;
   1196 	nextp = &Files;
   1197 
   1198 	/*
   1199 	 *  Close all open sockets
   1200 	 */
   1201 
   1202 	if (finet) {
   1203 		for (i = 0; i < *finet; i++) {
   1204 			if (close(finet[i+1]) < 0) {
   1205 				logerror("close() failed");
   1206 				die(0);
   1207 			}
   1208 		}
   1209 	}
   1210 
   1211 	/*
   1212 	 *  Reset counter of forwarding actions
   1213 	 */
   1214 
   1215 	NumForwards=0;
   1216 
   1217 	/* open the configuration file */
   1218 	if ((cf = fopen(ConfFile, "r")) == NULL) {
   1219 		dprintf("Cannot open `%s'\n", ConfFile);
   1220 		*nextp = (struct filed *)calloc(1, sizeof(*f));
   1221 		cfline("*.ERR\t/dev/console", *nextp);
   1222 		(*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
   1223 		cfline("*.PANIC\t*", (*nextp)->f_next);
   1224 		Initialized = 1;
   1225 		return;
   1226 	}
   1227 
   1228 	/*
   1229 	 *  Foreach line in the conf table, open that file.
   1230 	 */
   1231 	f = NULL;
   1232 	while (fgets(cline, sizeof(cline), cf) != NULL) {
   1233 		/*
   1234 		 * check for end-of-section, comments, strip off trailing
   1235 		 * spaces and newline character.
   1236 		 */
   1237 		for (p = cline; isspace(*p); ++p)
   1238 			continue;
   1239 		if (*p == '\0' || *p == '#')
   1240 			continue;
   1241 		for (p = strchr(cline, '\0'); isspace(*--p);)
   1242 			continue;
   1243 		*++p = '\0';
   1244 		f = (struct filed *)calloc(1, sizeof(*f));
   1245 		*nextp = f;
   1246 		nextp = &f->f_next;
   1247 		cfline(cline, f);
   1248 	}
   1249 
   1250 	/* close the configuration file */
   1251 	(void)fclose(cf);
   1252 
   1253 	Initialized = 1;
   1254 
   1255 	if (Debug) {
   1256 		for (f = Files; f; f = f->f_next) {
   1257 			for (i = 0; i <= LOG_NFACILITIES; i++)
   1258 				if (f->f_pmask[i] == INTERNAL_NOPRI)
   1259 					printf("X ");
   1260 				else
   1261 					printf("%d ", f->f_pmask[i]);
   1262 			printf("%s: ", TypeNames[f->f_type]);
   1263 			switch (f->f_type) {
   1264 			case F_FILE:
   1265 			case F_TTY:
   1266 			case F_CONSOLE:
   1267 				printf("%s", f->f_un.f_fname);
   1268 				break;
   1269 
   1270 			case F_FORW:
   1271 				printf("%s", f->f_un.f_forw.f_hname);
   1272 				break;
   1273 
   1274 			case F_USERS:
   1275 				for (i = 0;
   1276 				    i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
   1277 					printf("%s, ", f->f_un.f_uname[i]);
   1278 				break;
   1279 			}
   1280 			printf("\n");
   1281 		}
   1282 	}
   1283 
   1284 	finet = socksetup(PF_UNSPEC);
   1285 	if (finet) {
   1286 		if (SecureMode) {
   1287 			for (i = 0; i < *finet; i++) {
   1288 				if (shutdown(finet[i+1], SHUT_RD) < 0) {
   1289 					logerror("shutdown() failed");
   1290 					die(0);
   1291 				}
   1292 			}
   1293 		} else
   1294 			dprintf("Listening on inet and/or inet6 socket\n");
   1295 		dprintf("Sending on inet and/or inet6 socket\n");
   1296 	}
   1297 
   1298 	logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
   1299 	dprintf("syslogd: restarted\n");
   1300 }
   1301 
   1302 /*
   1303  * Crack a configuration file line
   1304  */
   1305 void
   1306 cfline(char *line, struct filed *f)
   1307 {
   1308 	struct addrinfo hints, *res;
   1309 	int    error, i, pri;
   1310 	char   *bp, *p, *q;
   1311 	char   buf[MAXLINE];
   1312 	int    sp_err;
   1313 
   1314 	dprintf("cfline(%s)\n", line);
   1315 
   1316 	errno = 0;	/* keep strerror() stuff out of logerror messages */
   1317 
   1318 	/* clear out file entry */
   1319 	memset(f, 0, sizeof(*f));
   1320 	for (i = 0; i <= LOG_NFACILITIES; i++)
   1321 		f->f_pmask[i] = INTERNAL_NOPRI;
   1322 
   1323 	/*
   1324 	 * There should not be any space before the log facility.
   1325 	 * Check this is okay, complain and fix if it is not.
   1326 	 */
   1327 	q = line;
   1328 	if (isblank((unsigned char)*line)) {
   1329 		errno = 0;
   1330 		logerror(
   1331 		    "Warning: `%s' space or tab before the log facility",
   1332 		    line);
   1333 		/* Fix: strip all spaces/tabs before the log facility */
   1334 		while (*q++ && isblank((unsigned char)*q));
   1335 		line = q;
   1336 	}
   1337 
   1338 	/*
   1339 	 * q is now at the first char of the log facility
   1340 	 * There should be at least one tab after the log facility
   1341 	 * Check this is okay, and complain and fix if it is not.
   1342 	 */
   1343 	q = line + strlen(line);
   1344 	while (!isblank((unsigned char)*q) && (q != line))
   1345 		q--;
   1346 	if ((q == line) && strlen(line)) {
   1347 		/* No tabs or space in a non empty line: complain */
   1348 		errno = 0;
   1349 		logerror(
   1350 		    "Error: `%s' log facility or log target missing",
   1351 		    line);
   1352 	}
   1353 
   1354 	/* q is at the end of the blank between the two fields */
   1355 	sp_err = 0;
   1356 	while (isblank((unsigned char)*q) && (q != line))
   1357 		if (*q-- == ' ')
   1358 			sp_err = 1;
   1359 
   1360 	if (sp_err) {
   1361 		/*
   1362 		 * A space somewhere between the log facility
   1363 		 * and the log target: complain
   1364 		 */
   1365 		errno = 0;
   1366 		logerror(
   1367 		    "Warning: `%s' space found where tab is expected",
   1368 		    line);
   1369 		/* ... and fix the problem: replace all spaces by tabs */
   1370 		while (*++q && isblank((unsigned char)*q))
   1371 			if (*q == ' ')
   1372 				*q='\t';
   1373 	}
   1374 
   1375 	/* scan through the list of selectors */
   1376 	for (p = line; *p && *p != '\t';) {
   1377 
   1378 		/* find the end of this facility name list */
   1379 		for (q = p; *q && *q != '\t' && *q++ != '.'; )
   1380 			continue;
   1381 
   1382 		/* collect priority name */
   1383 		for (bp = buf; *q && !strchr("\t,;", *q); )
   1384 			*bp++ = *q++;
   1385 		*bp = '\0';
   1386 
   1387 		/* skip cruft */
   1388 		while (strchr(", ;", *q))
   1389 			q++;
   1390 
   1391 		/* decode priority name */
   1392 		if (*buf == '*')
   1393 			pri = LOG_PRIMASK + 1;
   1394 		else {
   1395 			pri = decode(buf, prioritynames);
   1396 			if (pri < 0) {
   1397 				errno = 0;
   1398 				logerror("Unknown priority name `%s'", buf);
   1399 				return;
   1400 			}
   1401 		}
   1402 
   1403 		/* scan facilities */
   1404 		while (*p && !strchr("\t.;", *p)) {
   1405 			for (bp = buf; *p && !strchr("\t,;.", *p); )
   1406 				*bp++ = *p++;
   1407 			*bp = '\0';
   1408 			if (*buf == '*')
   1409 				for (i = 0; i < LOG_NFACILITIES; i++)
   1410 					f->f_pmask[i] = pri;
   1411 			else {
   1412 				i = decode(buf, facilitynames);
   1413 				if (i < 0) {
   1414 					errno = 0;
   1415 					logerror("Unknown facility name `%s'",
   1416 					    buf);
   1417 					return;
   1418 				}
   1419 				f->f_pmask[i >> 3] = pri;
   1420 			}
   1421 			while (*p == ',' || *p == ' ')
   1422 				p++;
   1423 		}
   1424 
   1425 		p = q;
   1426 	}
   1427 
   1428 	/* skip to action part */
   1429 	sp_err = 0;
   1430 	while ((*p == '\t') || (*p == ' '))
   1431 		p++;
   1432 
   1433 	switch (*p)
   1434 	{
   1435 	case '@':
   1436 		(void)strlcpy(f->f_un.f_forw.f_hname, ++p,
   1437 		    sizeof(f->f_un.f_forw.f_hname));
   1438 		memset(&hints, 0, sizeof(hints));
   1439 		hints.ai_family = AF_UNSPEC;
   1440 		hints.ai_socktype = SOCK_DGRAM;
   1441 		hints.ai_protocol = 0;
   1442 		error = getaddrinfo(f->f_un.f_forw.f_hname, "syslog", &hints,
   1443 		    &res);
   1444 		if (error) {
   1445 			logerror(gai_strerror(error));
   1446 			break;
   1447 		}
   1448 		f->f_un.f_forw.f_addr = res;
   1449 		f->f_type = F_FORW;
   1450 		NumForwards++;
   1451 		break;
   1452 
   1453 	case '/':
   1454 		(void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
   1455 		if ((f->f_file = open(p, O_WRONLY|O_APPEND, 0)) < 0) {
   1456 			f->f_type = F_UNUSED;
   1457 			logerror(p);
   1458 			break;
   1459 		}
   1460 		if (isatty(f->f_file))
   1461 			f->f_type = F_TTY;
   1462 		else
   1463 			f->f_type = F_FILE;
   1464 		if (strcmp(p, ctty) == 0)
   1465 			f->f_type = F_CONSOLE;
   1466 		break;
   1467 
   1468 	case '*':
   1469 		f->f_type = F_WALL;
   1470 		break;
   1471 
   1472 	default:
   1473 		for (i = 0; i < MAXUNAMES && *p; i++) {
   1474 			for (q = p; *q && *q != ','; )
   1475 				q++;
   1476 			(void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
   1477 			if ((q - p) > UT_NAMESIZE)
   1478 				f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
   1479 			else
   1480 				f->f_un.f_uname[i][q - p] = '\0';
   1481 			while (*q == ',' || *q == ' ')
   1482 				q++;
   1483 			p = q;
   1484 		}
   1485 		f->f_type = F_USERS;
   1486 		break;
   1487 	}
   1488 }
   1489 
   1490 
   1491 /*
   1492  *  Decode a symbolic name to a numeric value
   1493  */
   1494 int
   1495 decode(const char *name, CODE *codetab)
   1496 {
   1497 	CODE *c;
   1498 	char *p, buf[40];
   1499 
   1500 	if (isdigit(*name))
   1501 		return (atoi(name));
   1502 
   1503 	for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
   1504 		if (isupper(*name))
   1505 			*p = tolower(*name);
   1506 		else
   1507 			*p = *name;
   1508 	}
   1509 	*p = '\0';
   1510 	for (c = codetab; c->c_name; c++)
   1511 		if (!strcmp(buf, c->c_name))
   1512 			return (c->c_val);
   1513 
   1514 	return (-1);
   1515 }
   1516 
   1517 /*
   1518  * Retrieve the size of the kernel message buffer, via sysctl.
   1519  */
   1520 int
   1521 getmsgbufsize(void)
   1522 {
   1523 	int msgbufsize, mib[2];
   1524 	size_t size;
   1525 
   1526 	mib[0] = CTL_KERN;
   1527 	mib[1] = KERN_MSGBUFSIZE;
   1528 	size = sizeof msgbufsize;
   1529 	if (sysctl(mib, 2, &msgbufsize, &size, NULL, 0) == -1) {
   1530 		dprintf("Couldn't get kern.msgbufsize\n");
   1531 		return (0);
   1532 	}
   1533 	return (msgbufsize);
   1534 }
   1535 
   1536 int *
   1537 socksetup(int af)
   1538 {
   1539 	struct addrinfo hints, *res, *r;
   1540 	int error, maxs, *s, *socks;
   1541 	const int on = 1;
   1542 
   1543 	if(SecureMode && !NumForwards)
   1544 		return(NULL);
   1545 
   1546 	memset(&hints, 0, sizeof(hints));
   1547 	hints.ai_flags = AI_PASSIVE;
   1548 	hints.ai_family = af;
   1549 	hints.ai_socktype = SOCK_DGRAM;
   1550 	error = getaddrinfo(NULL, "syslog", &hints, &res);
   1551 	if (error) {
   1552 		logerror(gai_strerror(error));
   1553 		errno = 0;
   1554 		die(0);
   1555 	}
   1556 
   1557 	/* Count max number of sockets we may open */
   1558 	for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
   1559 		continue;
   1560 	socks = malloc((maxs+1) * sizeof(int));
   1561 	if (!socks) {
   1562 		logerror("Couldn't allocate memory for sockets");
   1563 		die(0);
   1564 	}
   1565 
   1566 	*socks = 0;   /* num of sockets counter at start of array */
   1567 	s = socks + 1;
   1568 	for (r = res; r; r = r->ai_next) {
   1569 		*s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
   1570 		if (*s < 0) {
   1571 			logerror("socket() failed");
   1572 			continue;
   1573 		}
   1574 		if (r->ai_family == AF_INET6 && setsockopt(*s, IPPROTO_IPV6,
   1575 		    IPV6_V6ONLY, &on, sizeof(on)) < 0) {
   1576 			logerror("setsockopt(IPV6_V6ONLY) failed");
   1577 			close(*s);
   1578 			continue;
   1579 		}
   1580 		if (!SecureMode && bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
   1581 			logerror("bind() failed");
   1582 			close (*s);
   1583 			continue;
   1584 		}
   1585 
   1586 		*socks = *socks + 1;
   1587 		s++;
   1588 	}
   1589 
   1590 	if (*socks == 0) {
   1591 		free (socks);
   1592 		if(Debug)
   1593 			return(NULL);
   1594 		else
   1595 			die(0);
   1596 	}
   1597 	if (res)
   1598 		freeaddrinfo(res);
   1599 
   1600 	return(socks);
   1601 }
   1602