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