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