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