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