xref: /dragonfly/usr.sbin/syslogd/syslogd.c (revision 655933d6)
1 /*
2  * Copyright (c) 1983, 1988, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * @(#)syslogd.c	8.3 (Berkeley) 4/4/94
30  * $FreeBSD: head/usr.sbin/syslogd/syslogd.c 258077 2013-11-13 01:04:02Z ian $
31  */
32 
33 /*
34  *  syslogd -- log system messages
35  *
36  * This program implements a system log. It takes a series of lines.
37  * Each line may have a priority, signified as "<n>" as
38  * the first characters of the line.  If this is
39  * not present, a default priority is used.
40  *
41  * To kill syslogd, send a signal 15 (terminate).  A signal 1 (hup) will
42  * cause it to reread its configuration file.
43  *
44  * Defined Constants:
45  *
46  * MAXLINE -- the maximum line length that can be handled.
47  * DEFUPRI -- the default priority for user messages
48  * DEFSPRI -- the default priority for kernel messages
49  *
50  * Author: Eric Allman
51  * extensive changes by Ralph Campbell
52  * more extensive changes by Eric Allman (again)
53  * Extension to log by program name as well as facility and priority
54  *   by Peter da Silva.
55  * -u and -v by Harlan Stenn.
56  * Priority comparison code by Harlan Stenn.
57  */
58 
59 #define	MAXLINE		1024		/* maximum line length */
60 #define	MAXSVLINE	120		/* maximum saved line length */
61 #define	DEFUPRI		(LOG_USER|LOG_NOTICE)
62 #define	DEFSPRI		(LOG_KERN|LOG_CRIT)
63 #define	TIMERINTVL	30		/* interval for checking flush, mark */
64 #define	TTYMSGTIME	1		/* timeout passed to ttymsg */
65 #define	RCVBUF_MINSIZE	(80 * 1024)	/* minimum size of dgram rcv buffer */
66 
67 #include <sys/param.h>
68 #include <sys/ioctl.h>
69 #include <sys/mman.h>
70 #include <sys/stat.h>
71 #include <sys/wait.h>
72 #include <sys/socket.h>
73 #include <sys/queue.h>
74 #include <sys/uio.h>
75 #include <sys/un.h>
76 #include <sys/time.h>
77 #include <sys/resource.h>
78 #include <sys/syslimits.h>
79 #include <sys/types.h>
80 
81 #include <netinet/in.h>
82 #include <netdb.h>
83 #include <arpa/inet.h>
84 
85 #include <ctype.h>
86 #include <err.h>
87 #include <errno.h>
88 #include <fcntl.h>
89 #include <libutil.h>
90 #include <limits.h>
91 #include <paths.h>
92 #include <signal.h>
93 #include <stdio.h>
94 #include <stdlib.h>
95 #include <string.h>
96 #include <sysexits.h>
97 #include <unistd.h>
98 #include <utmpx.h>
99 
100 #include "pathnames.h"
101 #include "ttymsg.h"
102 
103 #define SYSLOG_NAMES
104 #include <sys/syslog.h>
105 
106 const char	*ConfFile = _PATH_LOGCONF;
107 const char	*PidFile = _PATH_LOGPID;
108 const char	ctty[] = _PATH_CONSOLE;
109 
110 #define	dprintf		if (Debug) printf
111 
112 #define	MAXUNAMES	20	/* maximum number of user names */
113 
114 /*
115  * Unix sockets.
116  * We have two default sockets, one with 666 permissions,
117  * and one for privileged programs.
118  */
119 struct funix {
120 	int			s;
121 	const char		*name;
122 	mode_t			mode;
123 	STAILQ_ENTRY(funix)	next;
124 };
125 struct funix funix_secure =	{ -1, _PATH_LOG_PRIV, S_IRUSR | S_IWUSR,
126 				{ NULL } };
127 struct funix funix_default =	{ -1, _PATH_LOG, DEFFILEMODE,
128 				{ &funix_secure } };
129 
130 STAILQ_HEAD(, funix) funixes =	{ &funix_default,
131 				&(funix_secure.next.stqe_next) };
132 
133 /*
134  * Flags to logmsg().
135  */
136 
137 #define	IGN_CONS	0x001	/* don't print on console */
138 #define	SYNC_FILE	0x002	/* do fsync on file after printing */
139 #define	ADDDATE		0x004	/* add a date to the message */
140 #define	MARK		0x008	/* this message is a mark */
141 #define	ISKERNEL	0x010	/* kernel generated message */
142 
143 /*
144  * This structure represents the files that will have log
145  * copies printed.
146  * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
147  * or if f_type if F_PIPE and f_pid > 0.
148  */
149 
150 struct filed {
151 	struct	filed *f_next;		/* next in linked list */
152 	short	f_type;			/* entry type, see below */
153 	short	f_file;			/* file descriptor */
154 	time_t	f_time;			/* time this was last written */
155 	char	*f_host;		/* host from which to recd. */
156 	u_char	f_pmask[LOG_NFACILITIES+1];	/* priority mask */
157 	u_char	f_pcmp[LOG_NFACILITIES+1];	/* compare priority */
158 #define PRI_LT	0x1
159 #define PRI_EQ	0x2
160 #define PRI_GT	0x4
161 	char	*f_program;		/* program this applies to */
162 	union {
163 		char	f_uname[MAXUNAMES][MAXLOGNAME];
164 		struct {
165 			char	f_hname[MAXHOSTNAMELEN];
166 			struct addrinfo *f_addr;
167 
168 		} f_forw;		/* forwarding address */
169 		char	f_fname[MAXPATHLEN];
170 		struct {
171 			char	f_pname[MAXPATHLEN];
172 			pid_t	f_pid;
173 		} f_pipe;
174 	} f_un;
175 	char	f_prevline[MAXSVLINE];		/* last message logged */
176 	char	f_lasttime[16];			/* time of last occurrence */
177 	char	f_prevhost[MAXHOSTNAMELEN];	/* host from which recd. */
178 	int	f_prevpri;			/* pri of f_prevline */
179 	int	f_prevlen;			/* length of f_prevline */
180 	int	f_prevcount;			/* repetition cnt of prevline */
181 	u_int	f_repeatcount;			/* number of "repeated" msgs */
182 	int	f_flags;			/* file-specific flags */
183 #define	FFLAG_SYNC 0x01
184 #define	FFLAG_NEEDSYNC	0x02
185 };
186 
187 /*
188  * Queue of about-to-be dead processes we should watch out for.
189  */
190 
191 TAILQ_HEAD(stailhead, deadq_entry) deadq_head;
192 struct stailhead *deadq_headp;
193 
194 struct deadq_entry {
195 	pid_t				dq_pid;
196 	int				dq_timeout;
197 	TAILQ_ENTRY(deadq_entry)	dq_entries;
198 };
199 
200 /*
201  * The timeout to apply to processes waiting on the dead queue.  Unit
202  * of measure is `mark intervals', i.e. 20 minutes by default.
203  * Processes on the dead queue will be terminated after that time.
204  */
205 
206 #define	 DQ_TIMO_INIT	2
207 
208 typedef struct deadq_entry *dq_t;
209 
210 
211 /*
212  * Struct to hold records of network addresses that are allowed to log
213  * to us.
214  */
215 struct allowedpeer {
216 	int isnumeric;
217 	u_short port;
218 	union {
219 		struct {
220 			struct sockaddr_storage addr;
221 			struct sockaddr_storage mask;
222 		} numeric;
223 		char *name;
224 	} u;
225 #define a_addr u.numeric.addr
226 #define a_mask u.numeric.mask
227 #define a_name u.name
228 };
229 
230 
231 /*
232  * Intervals at which we flush out "message repeated" messages,
233  * in seconds after previous message is logged.  After each flush,
234  * we move to the next interval until we reach the largest.
235  */
236 int	repeatinterval[] = { 30, 120, 600 };	/* # of secs before flush */
237 #define	MAXREPEAT (NELEM(repeatinterval) - 1)
238 #define	REPEATTIME(f)	((f)->f_time + repeatinterval[(f)->f_repeatcount])
239 #define	BACKOFF(f)	{ if (++(f)->f_repeatcount > MAXREPEAT) \
240 				 (f)->f_repeatcount = MAXREPEAT; \
241 			}
242 
243 /* values for f_type */
244 #define F_UNUSED	0		/* unused entry */
245 #define F_FILE		1		/* regular file */
246 #define F_TTY		2		/* terminal */
247 #define F_CONSOLE	3		/* console terminal */
248 #define F_FORW		4		/* remote machine */
249 #define F_USERS		5		/* list of users */
250 #define F_WALL		6		/* everyone logged on */
251 #define F_PIPE		7		/* pipe to program */
252 
253 const char *TypeNames[8] = {
254 	"UNUSED",	"FILE",		"TTY",		"CONSOLE",
255 	"FORW",		"USERS",	"WALL",		"PIPE"
256 };
257 
258 static struct filed *Files;	/* Log files that we write to */
259 static struct filed consfile;	/* Console */
260 
261 static int	Debug;		/* debug flag */
262 static int	resolve = 1;	/* resolve hostname */
263 static char	LocalHostName[MAXHOSTNAMELEN];	/* our hostname */
264 static const char *LocalDomain;	/* our local domain name */
265 static int	*finet;		/* Internet datagram socket */
266 static int	fklog = -1;	/* /dev/klog */
267 static int	Initialized;	/* set when we have initialized ourselves */
268 static int	MarkInterval = 20 * 60;	/* interval between marks in seconds */
269 static int	MarkSeq;	/* mark sequence number */
270 static int	NoBind;		/* don't bind() as suggested by RFC 3164 */
271 static int	SecureMode;	/* when true, receive only unix domain socks */
272 #ifdef INET6
273 static int	family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
274 #else
275 static int	family = PF_INET; /* protocol family (IPv4 only) */
276 #endif
277 static int	mask_C1 = 1;	/* mask characters from 0x80 - 0x9F */
278 static int	send_to_all;	/* send message to all IPv4/IPv6 addresses */
279 static int	use_bootfile;	/* log entire bootfile for every kern msg */
280 static int	no_compress;	/* don't compress messages (1=pipes, 2=all) */
281 static int	logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
282 
283 static char	bootfile[MAXLINE+1]; /* booted kernel file */
284 
285 struct allowedpeer *AllowedPeers; /* List of allowed peers */
286 static int	NumAllowed;	/* Number of entries in AllowedPeers */
287 static int	RemoteAddDate;	/* Always set the date on remote messages */
288 
289 static int	UniquePriority;	/* Only log specified priority? */
290 static int	LogFacPri;	/* Put facility and priority in log message: */
291 				/* 0=no, 1=numeric, 2=names */
292 static int	KeepKernFac;	/* Keep remotely logged kernel facility */
293 static int	needdofsync = 0; /* Are any file(s) waiting to be fsynced? */
294 static struct pidfh *pfh;
295 
296 volatile sig_atomic_t MarkSet, WantDie;
297 
298 static int	allowaddr(char *);
299 static void	cfline(const char *, struct filed *,
300 		    const char *, const char *);
301 static const char *cvthname(struct sockaddr *);
302 static void	deadq_enter(pid_t, const char *);
303 static int	deadq_remove(pid_t);
304 static int	decode(const char *, const CODE *);
305 static void	die(int);
306 static void	dodie(int);
307 static void	dofsync(void);
308 static void	domark(int);
309 static void	fprintlog(struct filed *, int, const char *);
310 static int	*socksetup(int, char *);
311 static void	init(int);
312 static void	logerror(const char *);
313 static void	logmsg(int, const char *, const char *, int);
314 static void	log_deadchild(pid_t, int, const char *);
315 static void	markit(void);
316 static int	skip_message(const char *, const char *, int);
317 static void	printline(const char *, char *, int);
318 static void	printsys(char *);
319 static int	p_open(const char *, pid_t *);
320 static void	readklog(void);
321 static void	reapchild(int);
322 static void	usage(void);
323 static int	validate(struct sockaddr *, const char *);
324 static void	unmapped(struct sockaddr *);
325 static void	wallmsg(struct filed *, struct iovec *, const int iovlen);
326 static int	waitdaemon(int, int, int);
327 static void	timedout(int);
328 static void	increase_rcvbuf(int);
329 
330 int
331 main(int argc, char *argv[])
332 {
333 	int ch, i, fdsrmax = 0, l;
334 	struct sockaddr_un sunx, fromunix;
335 	struct sockaddr_storage frominet;
336 	fd_set *fdsr = NULL;
337 	char line[MAXLINE + 1];
338 	char *bindhostname;
339 	const char *hname;
340 	struct timeval tv, *tvp;
341 	struct sigaction sact;
342 	struct funix *fx, *fx1;
343 	sigset_t mask;
344 	pid_t ppid = 1, spid;
345 	socklen_t len;
346 
347 	bindhostname = NULL;
348 	while ((ch = getopt(argc, argv, "468Aa:b:cCdf:kl:m:nNop:P:sS:Tuv"))
349 	    != -1)
350 		switch (ch) {
351 		case '4':
352 			family = PF_INET;
353 			break;
354 #ifdef INET6
355 		case '6':
356 			family = PF_INET6;
357 			break;
358 #endif
359 		case '8':
360 			mask_C1 = 0;
361 			break;
362 		case 'A':
363 			send_to_all++;
364 			break;
365 		case 'a':		/* allow specific network addresses only */
366 			if (allowaddr(optarg) == -1)
367 				usage();
368 			break;
369 		case 'b':
370 			bindhostname = optarg;
371 			break;
372 		case 'c':
373 			no_compress++;
374 			break;
375 		case 'C':
376 			logflags |= O_CREAT;
377 			break;
378 		case 'd':		/* debug */
379 			Debug++;
380 			break;
381 		case 'f':		/* configuration file */
382 			ConfFile = optarg;
383 			break;
384 		case 'k':		/* keep remote kern fac */
385 			KeepKernFac = 1;
386 			break;
387 		case 'l':
388 		    {
389 			long	perml;
390 			mode_t	mode;
391 			char	*name, *ep;
392 
393 			if (optarg[0] == '/') {
394 				mode = DEFFILEMODE;
395 				name = optarg;
396 			} else if ((name = strchr(optarg, ':')) != NULL) {
397 				*name++ = '\0';
398 				if (name[0] != '/')
399 					errx(1, "socket name must be absolute "
400 					    "path");
401 				if (isdigit(*optarg)) {
402 					perml = strtol(optarg, &ep, 8);
403 				    if (*ep || perml < 0 ||
404 					perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
405 					    errx(1, "invalid mode %s, exiting",
406 						optarg);
407 				    mode = (mode_t )perml;
408 				} else
409 					errx(1, "invalid mode %s, exiting",
410 					    optarg);
411 			} else	/* doesn't begin with '/', and no ':' */
412 				errx(1, "can't parse path %s", optarg);
413 
414 			if (strlen(name) >= sizeof(sunx.sun_path))
415 				errx(1, "%s path too long, exiting", name);
416 			if ((fx = malloc(sizeof(struct funix))) == NULL)
417 				errx(1, "malloc failed");
418 			fx->s = -1;
419 			fx->name = name;
420 			fx->mode = mode;
421 			STAILQ_INSERT_TAIL(&funixes, fx, next);
422 			break;
423 		   }
424 		case 'm':		/* mark interval */
425 			MarkInterval = atoi(optarg) * 60;
426 			break;
427 		case 'N':
428 			NoBind = 1;
429 			SecureMode = 1;
430 			break;
431 		case 'n':
432 			resolve = 0;
433 			break;
434 		case 'o':
435 			use_bootfile = 1;
436 			break;
437 		case 'p':		/* path */
438 			if (strlen(optarg) >= sizeof(sunx.sun_path))
439 				errx(1, "%s path too long, exiting", optarg);
440 			funix_default.name = optarg;
441 			break;
442 		case 'P':		/* path for alt. PID */
443 			PidFile = optarg;
444 			break;
445 		case 's':		/* no network mode */
446 			SecureMode++;
447 			break;
448 		case 'S':		/* path for privileged originator */
449 			if (strlen(optarg) >= sizeof(sunx.sun_path))
450 				errx(1, "%s path too long, exiting", optarg);
451 			funix_secure.name = optarg;
452 			break;
453 		case 'T':
454 			RemoteAddDate = 1;
455 			break;
456 		case 'u':		/* only log specified priority */
457 			UniquePriority++;
458 			break;
459 		case 'v':		/* log facility and priority */
460 		  	LogFacPri++;
461 			break;
462 		default:
463 			usage();
464 		}
465 	if ((argc -= optind) != 0)
466 		usage();
467 
468 	pfh = pidfile_open(PidFile, 0600, &spid);
469 	if (pfh == NULL) {
470 		if (errno == EEXIST)
471 			errx(1, "syslogd already running, pid: %d", spid);
472 		warn("cannot open pid file");
473 	}
474 
475 	if (!Debug) {
476 		ppid = waitdaemon(0, 0, 30);
477 		if (ppid < 0) {
478 			warn("could not become daemon");
479 			pidfile_remove(pfh);
480 			exit(1);
481 		}
482 	} else {
483 		setlinebuf(stdout);
484 	}
485 
486 	if (NumAllowed)
487 		endservent();
488 
489 	consfile.f_type = F_CONSOLE;
490 	(void)strlcpy(consfile.f_un.f_fname, ctty + sizeof _PATH_DEV - 1,
491 	    sizeof(consfile.f_un.f_fname));
492 	(void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
493 	(void)signal(SIGTERM, dodie);
494 	(void)signal(SIGINT, Debug ? dodie : SIG_IGN);
495 	(void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
496 	/*
497 	 * We don't want the SIGCHLD and SIGHUP handlers to interfere
498 	 * with each other; they are likely candidates for being called
499 	 * simultaneously (SIGHUP closes pipe descriptor, process dies,
500 	 * SIGCHLD happens).
501 	 */
502 	sigemptyset(&mask);
503 	sigaddset(&mask, SIGHUP);
504 	sact.sa_handler = reapchild;
505 	sact.sa_mask = mask;
506 	sact.sa_flags = SA_RESTART;
507 	(void)sigaction(SIGCHLD, &sact, NULL);
508 	(void)signal(SIGALRM, domark);
509 	(void)signal(SIGPIPE, SIG_IGN);	/* We'll catch EPIPE instead. */
510 	(void)alarm(TIMERINTVL);
511 
512 	TAILQ_INIT(&deadq_head);
513 
514 #ifndef SUN_LEN
515 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
516 #endif
517 	STAILQ_FOREACH_MUTABLE(fx, &funixes, next, fx1) {
518 		(void)unlink(fx->name);
519 		memset(&sunx, 0, sizeof(sunx));
520 		sunx.sun_family = AF_LOCAL;
521 		(void)strlcpy(sunx.sun_path, fx->name, sizeof(sunx.sun_path));
522 		fx->s = socket(PF_LOCAL, SOCK_DGRAM, 0);
523 		if (fx->s < 0 ||
524 		    bind(fx->s, (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
525 		    chmod(fx->name, fx->mode) < 0) {
526 			(void)snprintf(line, sizeof line,
527 					"cannot create %s", fx->name);
528 			logerror(line);
529 			dprintf("cannot create %s (%d)\n", fx->name, errno);
530 			if (fx == &funix_default || fx == &funix_secure)
531 				die(0);
532 			else {
533 				STAILQ_REMOVE(&funixes, fx, funix, next);
534 				continue;
535 			}
536 		}
537 		increase_rcvbuf(fx->s);
538 	}
539 	if (SecureMode <= 1)
540 		finet = socksetup(family, bindhostname);
541 
542 	if (finet) {
543 		if (SecureMode) {
544 			for (i = 0; i < *finet; i++) {
545 				if (shutdown(finet[i+1], SHUT_RD) < 0) {
546 					logerror("shutdown");
547 					if (!Debug)
548 						die(0);
549 				}
550 			}
551 		} else {
552 			dprintf("listening on inet and/or inet6 socket\n");
553 		}
554 		dprintf("sending on inet and/or inet6 socket\n");
555 	}
556 
557 	if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) >= 0)
558 		if (fcntl(fklog, F_SETFL, O_NONBLOCK) < 0)
559 			fklog = -1;
560 	if (fklog < 0)
561 		dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
562 
563 	/* tuck my process id away */
564 	pidfile_write(pfh);
565 
566 	dprintf("off & running....\n");
567 
568 	init(0);
569 	/* prevent SIGHUP and SIGCHLD handlers from running in parallel */
570 	sigemptyset(&mask);
571 	sigaddset(&mask, SIGCHLD);
572 	sact.sa_handler = init;
573 	sact.sa_mask = mask;
574 	sact.sa_flags = SA_RESTART;
575 	(void)sigaction(SIGHUP, &sact, NULL);
576 
577 	tvp = &tv;
578 	tv.tv_sec = tv.tv_usec = 0;
579 
580 	if (fklog != -1 && fklog > fdsrmax)
581 		fdsrmax = fklog;
582 	if (finet && !SecureMode) {
583 		for (i = 0; i < *finet; i++) {
584 		    if (finet[i+1] != -1 && finet[i+1] > fdsrmax)
585 			fdsrmax = finet[i+1];
586 		}
587 	}
588 	STAILQ_FOREACH(fx, &funixes, next)
589 		if (fx->s > fdsrmax)
590 			fdsrmax = fx->s;
591 
592 	fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS),
593 	    sizeof(fd_mask));
594 	if (fdsr == NULL)
595 		errx(1, "calloc fd_set");
596 
597 	for (;;) {
598 		if (MarkSet)
599 			markit();
600 		if (WantDie)
601 			die(WantDie);
602 
603 		bzero(fdsr, howmany(fdsrmax+1, NFDBITS) *
604 		    sizeof(fd_mask));
605 
606 		if (fklog != -1)
607 			FD_SET(fklog, fdsr);
608 		if (finet && !SecureMode) {
609 			for (i = 0; i < *finet; i++) {
610 				if (finet[i+1] != -1)
611 					FD_SET(finet[i+1], fdsr);
612 			}
613 		}
614 		STAILQ_FOREACH(fx, &funixes, next)
615 			FD_SET(fx->s, fdsr);
616 
617 		i = select(fdsrmax+1, fdsr, NULL, NULL,
618 		    needdofsync ? &tv : tvp);
619 		switch (i) {
620 		case 0:
621 			dofsync();
622 			needdofsync = 0;
623 			if (tvp) {
624 				tvp = NULL;
625 				if (ppid != 1)
626 					kill(ppid, SIGALRM);
627 			}
628 			continue;
629 		case -1:
630 			if (errno != EINTR)
631 				logerror("select");
632 			continue;
633 		}
634 		if (fklog != -1 && FD_ISSET(fklog, fdsr))
635 			readklog();
636 		if (finet && !SecureMode) {
637 			for (i = 0; i < *finet; i++) {
638 				if (FD_ISSET(finet[i+1], fdsr)) {
639 					len = sizeof(frominet);
640 					l = recvfrom(finet[i+1], line, MAXLINE,
641 					     0, (struct sockaddr *)&frominet,
642 					     &len);
643 					if (l > 0) {
644 						line[l] = '\0';
645 						hname = cvthname((struct sockaddr *)&frominet);
646 						unmapped((struct sockaddr *)&frominet);
647 						if (validate((struct sockaddr *)&frominet, hname))
648 							printline(hname, line, RemoteAddDate ? ADDDATE : 0);
649 					} else if (l < 0 && errno != EINTR)
650 						logerror("recvfrom inet");
651 				}
652 			}
653 		}
654 		STAILQ_FOREACH(fx, &funixes, next) {
655 			if (FD_ISSET(fx->s, fdsr)) {
656 				len = sizeof(fromunix);
657 				l = recvfrom(fx->s, line, MAXLINE, 0,
658 				    (struct sockaddr *)&fromunix, &len);
659 				if (l > 0) {
660 					line[l] = '\0';
661 					printline(LocalHostName, line, 0);
662 				} else if (l < 0 && errno != EINTR)
663 					logerror("recvfrom unix");
664 			}
665 		}
666 	}
667 	if (fdsr)
668 		free(fdsr);
669 }
670 
671 static void
672 unmapped(struct sockaddr *sa)
673 {
674 	struct sockaddr_in6 *sin6;
675 	struct sockaddr_in sin4;
676 
677 	if (sa->sa_family != AF_INET6)
678 		return;
679 	if (sa->sa_len != sizeof(struct sockaddr_in6) ||
680 	    sizeof(sin4) > sa->sa_len)
681 		return;
682 	sin6 = (struct sockaddr_in6 *)sa;
683 	if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
684 		return;
685 
686 	memset(&sin4, 0, sizeof(sin4));
687 	sin4.sin_family = AF_INET;
688 	sin4.sin_len = sizeof(struct sockaddr_in);
689 	memcpy(&sin4.sin_addr, &sin6->sin6_addr.s6_addr[12],
690 	       sizeof(sin4.sin_addr));
691 	sin4.sin_port = sin6->sin6_port;
692 
693 	memcpy(sa, &sin4, sin4.sin_len);
694 }
695 
696 static void
697 usage(void)
698 {
699 
700 	fprintf(stderr, "%s\n%s\n%s\n%s\n",
701 		"usage: syslogd [-468ACcdknosTuv] [-a allowed_peer]",
702 		"               [-b bind_address] [-f config_file]",
703 		"               [-l [mode:]path] [-m mark_interval]",
704 		"               [-P pid_file] [-p log_socket]");
705 	exit(1);
706 }
707 
708 /*
709  * Take a raw input line, decode the message, and print the message
710  * on the appropriate log files.
711  */
712 static void
713 printline(const char *hname, char *msg, int flags)
714 {
715 	char *p, *q;
716 	long n;
717 	int c, pri;
718 	char line[MAXLINE + 1];
719 
720 	/* test for special codes */
721 	p = msg;
722 	pri = DEFUPRI;
723 	if (*p == '<') {
724 		errno = 0;
725 		n = strtol(p + 1, &q, 10);
726 		if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
727 			p = q + 1;
728 			pri = n;
729 		}
730 	}
731 	if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
732 		pri = DEFUPRI;
733 
734 	/*
735 	 * Don't allow users to log kernel messages.
736 	 * NOTE: since LOG_KERN == 0 this will also match
737 	 *       messages with no facility specified.
738 	 */
739 	if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
740 		pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
741 
742 	q = line;
743 
744 	while ((c = (unsigned char)*p++) != '\0' &&
745 	    q < &line[sizeof(line) - 4]) {
746 		if (mask_C1 && (c & 0x80) && c < 0xA0) {
747 			c &= 0x7F;
748 			*q++ = 'M';
749 			*q++ = '-';
750 		}
751 		if (isascii(c) && iscntrl(c)) {
752 			if (c == '\n') {
753 				*q++ = ' ';
754 			} else if (c == '\t') {
755 				*q++ = '\t';
756 			} else {
757 				*q++ = '^';
758 				*q++ = c ^ 0100;
759 			}
760 		} else {
761 			*q++ = c;
762 		}
763 	}
764 	*q = '\0';
765 
766 	logmsg(pri, line, hname, flags);
767 }
768 
769 /*
770  * Read /dev/klog while data are available, split into lines.
771  *
772  * Only dump whole lines, fixing potential write/read races that can
773  * cause lines to be split up due to the speed.
774  */
775 static void
776 readklog(void)
777 {
778 	static char line[MAXLINE + 1];
779 	static int len = 0;
780 	char *p, *q;
781 	int i;
782 
783 	for (;;) {
784 		i = read(fklog, line + len, MAXLINE - 1 - len);
785 		if (i > 0) {
786 			line[i + len] = '\0';
787 		} else {
788 			if (i < 0 && errno != EINTR && errno != EAGAIN) {
789 				logerror("klog");
790 				fklog = -1;
791 			}
792 			break;
793 		}
794 
795 		for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
796 			*q = '\0';
797 			printsys(p);
798 		}
799 		len = strlen(p);
800 		if (len >= MAXLINE - 1) {
801 			printsys(p);
802 			len = 0;
803 		}
804 		if (len > 0)
805 			memmove(line, p, len + 1);
806 	}
807 }
808 
809 /*
810  * Take a raw input line from /dev/klog, format similar to syslog().
811  */
812 static void
813 printsys(char *msg)
814 {
815 	char *p, *q;
816 	long n;
817 	int flags, isprintf, pri;
818 
819 	flags = ISKERNEL | SYNC_FILE | ADDDATE;	/* fsync after write */
820 	p = msg;
821 	pri = DEFSPRI;
822 	isprintf = 1;
823 	if (*p == '<') {
824 		errno = 0;
825 		n = strtol(p + 1, &q, 10);
826 		if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
827 			p = q + 1;
828 			pri = n;
829 			isprintf = 0;
830 		}
831 	}
832 	/*
833 	 * Kernel printf's and LOG_CONSOLE messages have been displayed
834 	 * on the console already.
835 	 */
836 	if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
837 		flags |= IGN_CONS;
838 	if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
839 		pri = DEFSPRI;
840 	logmsg(pri, p, LocalHostName, flags);
841 }
842 
843 static time_t	now;
844 
845 /*
846  * Match a program or host name against a specification.
847  * Return a non-0 value if the message must be ignored
848  * based on the specification.
849  */
850 static int
851 skip_message(const char *name, const char *spec, int checkcase)
852 {
853 	const char *s;
854 	char prev, next;
855 	int exclude = 0;
856 	/* Behaviour on explicit match */
857 
858 	if (spec == NULL)
859 		return 0;
860 	switch (*spec) {
861 	case '-':
862 		exclude = 1;
863 		/*FALLTHROUGH*/
864 	case '+':
865 		spec++;
866 		break;
867 	default:
868 		break;
869 	}
870 	if (checkcase)
871 		s = strstr (spec, name);
872 	else
873 		s = strcasestr (spec, name);
874 
875 	if (s != NULL) {
876 		prev = (s == spec ? ',' : *(s - 1));
877 		next = *(s + strlen (name));
878 
879 		if (prev == ',' && (next == '\0' || next == ','))
880 			/* Explicit match: skip iff the spec is an
881 			   exclusive one. */
882 			return exclude;
883 	}
884 
885 	/* No explicit match for this name: skip the message iff
886 	   the spec is an inclusive one. */
887 	return !exclude;
888 }
889 
890 /*
891  * Log a message to the appropriate log files, users, etc. based on
892  * the priority.
893  */
894 static void
895 logmsg(int pri, const char *msg, const char *from, int flags)
896 {
897 	struct filed *f;
898 	int i, fac, msglen, omask, prilev;
899 	const char *timestamp;
900  	char prog[NAME_MAX+1];
901 	char buf[MAXLINE+1];
902 
903 	dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
904 	    pri, flags, from, msg);
905 
906 	omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
907 
908 	/*
909 	 * Check to see if msg looks non-standard.
910 	 */
911 	msglen = strlen(msg);
912 	if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
913 	    msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
914 		flags |= ADDDATE;
915 
916 	(void)time(&now);
917 	if (flags & ADDDATE) {
918 		timestamp = ctime(&now) + 4;
919 	} else {
920 		timestamp = msg;
921 		msg += 16;
922 		msglen -= 16;
923 	}
924 
925 	/* skip leading blanks */
926 	while (isspace(*msg)) {
927 		msg++;
928 		msglen--;
929 	}
930 
931 	/* extract facility and priority level */
932 	if (flags & MARK)
933 		fac = LOG_NFACILITIES;
934 	else
935 		fac = LOG_FAC(pri);
936 
937 	/* Check maximum facility number. */
938 	if (fac > LOG_NFACILITIES) {
939 		(void)sigsetmask(omask);
940 		return;
941 	}
942 
943 	prilev = LOG_PRI(pri);
944 
945 	/* extract program name */
946 	for (i = 0; i < NAME_MAX; i++) {
947 		if (!isprint(msg[i]) || msg[i] == ':' || msg[i] == '[' ||
948 		    msg[i] == '/' || isspace(msg[i]))
949 			break;
950 		prog[i] = msg[i];
951 	}
952 	prog[i] = 0;
953 
954 	/* add kernel prefix for kernel messages */
955 	if (flags & ISKERNEL) {
956 		snprintf(buf, sizeof(buf), "%s: %s",
957 		    use_bootfile ? bootfile : "kernel", msg);
958 		msg = buf;
959 		msglen = strlen(buf);
960 	}
961 
962 	/* log the message to the particular outputs */
963 	if (!Initialized) {
964 		f = &consfile;
965 		/*
966 		 * Open in non-blocking mode to avoid hangs during open
967 		 * and close(waiting for the port to drain).
968 		 */
969 		f->f_file = open(ctty, O_WRONLY | O_NONBLOCK, 0);
970 
971 		if (f->f_file >= 0) {
972 			(void)strlcpy(f->f_lasttime, timestamp,
973 				sizeof(f->f_lasttime));
974 			fprintlog(f, flags, msg);
975 			(void)close(f->f_file);
976 		}
977 		(void)sigsetmask(omask);
978 		return;
979 	}
980 	for (f = Files; f; f = f->f_next) {
981 		/* skip messages that are incorrect priority */
982 		if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
983 		     ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
984 		     ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
985 		     )
986 		    || f->f_pmask[fac] == INTERNAL_NOPRI)
987 			continue;
988 
989 		/* skip messages with the incorrect hostname */
990 		if (skip_message(from, f->f_host, 0))
991 			continue;
992 
993 		/* skip messages with the incorrect program name */
994 		if (skip_message(prog, f->f_program, 1))
995 			continue;
996 
997 		/* skip message to console if it has already been printed */
998 		if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
999 			continue;
1000 
1001 		/* don't output marks to recently written files */
1002 		if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1003 			continue;
1004 
1005 		/*
1006 		 * suppress duplicate lines to this file
1007 		 */
1008 		if (no_compress - (f->f_type != F_PIPE) < 1 &&
1009 		    (flags & MARK) == 0 && msglen == f->f_prevlen &&
1010 		    f->f_prevline && !strcmp(msg, f->f_prevline) &&
1011 		    !strcasecmp(from, f->f_prevhost)) {
1012 			(void)strlcpy(f->f_lasttime, timestamp,
1013 				sizeof(f->f_lasttime));
1014 			f->f_prevcount++;
1015 			dprintf("msg repeated %d times, %ld sec of %d\n",
1016 			    f->f_prevcount, (long)(now - f->f_time),
1017 			    repeatinterval[f->f_repeatcount]);
1018 			/*
1019 			 * If domark would have logged this by now,
1020 			 * flush it now (so we don't hold isolated messages),
1021 			 * but back off so we'll flush less often
1022 			 * in the future.
1023 			 */
1024 			if (now > REPEATTIME(f)) {
1025 				fprintlog(f, flags, NULL);
1026 				BACKOFF(f);
1027 			}
1028 		} else {
1029 			/* new line, save it */
1030 			if (f->f_prevcount)
1031 				fprintlog(f, 0, NULL);
1032 			f->f_repeatcount = 0;
1033 			f->f_prevpri = pri;
1034 			(void)strlcpy(f->f_lasttime, timestamp,
1035 				sizeof(f->f_lasttime));
1036 			(void)strlcpy(f->f_prevhost, from,
1037 			    sizeof(f->f_prevhost));
1038 			if (msglen < MAXSVLINE) {
1039 				f->f_prevlen = msglen;
1040 				(void)strlcpy(f->f_prevline, msg, sizeof(f->f_prevline));
1041 				fprintlog(f, flags, NULL);
1042 			} else {
1043 				f->f_prevline[0] = 0;
1044 				f->f_prevlen = 0;
1045 				fprintlog(f, flags, msg);
1046 			}
1047 		}
1048 	}
1049 	(void)sigsetmask(omask);
1050 }
1051 
1052 static void
1053 dofsync(void)
1054 {
1055 	struct filed *f;
1056 
1057 	for (f = Files; f; f = f->f_next) {
1058 		if ((f->f_type == F_FILE) &&
1059 		    (f->f_flags & FFLAG_NEEDSYNC)) {
1060 			f->f_flags &= ~FFLAG_NEEDSYNC;
1061 			(void)fsync(f->f_file);
1062 		}
1063 	}
1064 }
1065 
1066 #define IOV_SIZE 7
1067 static void
1068 fprintlog(struct filed *f, int flags, const char *msg)
1069 {
1070 	struct iovec iov[IOV_SIZE];
1071 	struct iovec *v;
1072 	struct addrinfo *r;
1073 	int i, l, lsent = 0;
1074 	char line[MAXLINE + 1], repbuf[80], greetings[200], *wmsg = NULL;
1075 	char nul[] = "", space[] = " ", lf[] = "\n", crlf[] = "\r\n";
1076 	const char *msgret;
1077 
1078 	v = iov;
1079 	if (f->f_type == F_WALL) {
1080 		v->iov_base = greetings;
1081 		/* The time displayed is not synchornized with the other log
1082 		 * destinations (like messages).  Following fragment was using
1083 		 * ctime(&now), which was updating the time every 30 sec.
1084 		 * With f_lasttime, time is synchronized correctly.
1085 		 */
1086 		v->iov_len = snprintf(greetings, sizeof greetings,
1087 		    "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
1088 		    f->f_prevhost, f->f_lasttime);
1089 		if (v->iov_len >= sizeof greetings)
1090 			v->iov_len = sizeof greetings - 1;
1091 		v++;
1092 		v->iov_base = nul;
1093 		v->iov_len = 0;
1094 		v++;
1095 	} else {
1096 		v->iov_base = f->f_lasttime;
1097 		v->iov_len = strlen(f->f_lasttime);
1098 		v++;
1099 		v->iov_base = space;
1100 		v->iov_len = 1;
1101 		v++;
1102 	}
1103 
1104 	if (LogFacPri) {
1105 	  	static char fp_buf[30];	/* Hollow laugh */
1106 		int fac = f->f_prevpri & LOG_FACMASK;
1107 		int pri = LOG_PRI(f->f_prevpri);
1108 		const char *f_s = NULL;
1109 		char f_n[5];	/* Hollow laugh */
1110 		const char *p_s = NULL;
1111 		char p_n[5];	/* Hollow laugh */
1112 
1113 		if (LogFacPri > 1) {
1114 		  const CODE *c;
1115 
1116 		  for (c = facilitynames; c->c_name; c++) {
1117 		    if (c->c_val == fac) {
1118 		      f_s = c->c_name;
1119 		      break;
1120 		    }
1121 		  }
1122 		  for (c = prioritynames; c->c_name; c++) {
1123 		    if (c->c_val == pri) {
1124 		      p_s = c->c_name;
1125 		      break;
1126 		    }
1127 		  }
1128 		}
1129 		if (!f_s) {
1130 		  snprintf(f_n, sizeof f_n, "%d", LOG_FAC(fac));
1131 		  f_s = f_n;
1132 		}
1133 		if (!p_s) {
1134 		  snprintf(p_n, sizeof p_n, "%d", pri);
1135 		  p_s = p_n;
1136 		}
1137 		snprintf(fp_buf, sizeof fp_buf, "<%s.%s> ", f_s, p_s);
1138 		v->iov_base = fp_buf;
1139 		v->iov_len = strlen(fp_buf);
1140 	} else {
1141 		v->iov_base = nul;
1142 		v->iov_len = 0;
1143 	}
1144 	v++;
1145 
1146 	v->iov_base = f->f_prevhost;
1147 	v->iov_len = strlen(v->iov_base);
1148 	v++;
1149 	v->iov_base = space;
1150 	v->iov_len = 1;
1151 	v++;
1152 
1153 	if (msg) {
1154 		wmsg = strdup(msg); /* XXX iov_base needs a `const' sibling. */
1155 		if (wmsg == NULL) {
1156 			logerror("strdup");
1157 			exit(1);
1158 		}
1159 		v->iov_base = wmsg;
1160 		v->iov_len = strlen(msg);
1161 	} else if (f->f_prevcount > 1) {
1162 		v->iov_base = repbuf;
1163 		v->iov_len = snprintf(repbuf, sizeof repbuf,
1164 		    "last message repeated %d times", f->f_prevcount);
1165 	} else if (f->f_prevline) {
1166 		v->iov_base = f->f_prevline;
1167 		v->iov_len = f->f_prevlen;
1168 	} else {
1169 		return;
1170 	}
1171 	v++;
1172 
1173 	dprintf("Logging to %s", TypeNames[f->f_type]);
1174 	f->f_time = now;
1175 
1176 	switch (f->f_type) {
1177 		int port;
1178 	case F_UNUSED:
1179 		dprintf("\n");
1180 		break;
1181 
1182 	case F_FORW:
1183 		port = (int)ntohs(((struct sockaddr_in *)
1184 			    (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1185 		if (port != 514) {
1186 			dprintf(" %s:%d\n", f->f_un.f_forw.f_hname, port);
1187 		} else {
1188 			dprintf(" %s\n", f->f_un.f_forw.f_hname);
1189 		}
1190 		/* check for local vs remote messages */
1191 		if (strcasecmp(f->f_prevhost, LocalHostName))
1192 			l = snprintf(line, sizeof line - 1,
1193 			    "<%d>%.15s Forwarded from %s: %s",
1194 			    f->f_prevpri, (char *)iov[0].iov_base,
1195 			    f->f_prevhost, (char *)iov[5].iov_base);
1196 		else
1197 			l = snprintf(line, sizeof line - 1, "<%d>%.15s %s",
1198 			     f->f_prevpri, (char *)iov[0].iov_base,
1199 			    (char *)iov[5].iov_base);
1200 		if (l < 0)
1201 			l = 0;
1202 		else if (l > MAXLINE)
1203 			l = MAXLINE;
1204 
1205 		if (finet) {
1206 			for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
1207 				for (i = 0; i < *finet; i++) {
1208 #if 0
1209 					/*
1210 					 * should we check AF first, or just
1211 					 * trial and error? FWD
1212 					 */
1213 					if (r->ai_family ==
1214 					    address_family_of(finet[i+1]))
1215 #endif
1216 					lsent = sendto(finet[i+1], line, l, 0,
1217 					    r->ai_addr, r->ai_addrlen);
1218 					if (lsent == l)
1219 						break;
1220 				}
1221 				if (lsent == l && !send_to_all)
1222 					break;
1223 			}
1224 			dprintf("lsent/l: %d/%d\n", lsent, l);
1225 			if (lsent != l) {
1226 				int e = errno;
1227 				logerror("sendto");
1228 				errno = e;
1229 				switch (errno) {
1230 				case ENOBUFS:
1231 				case ENETDOWN:
1232 				case ENETUNREACH:
1233 				case EHOSTUNREACH:
1234 				case EHOSTDOWN:
1235 				case EADDRNOTAVAIL:
1236 					break;
1237 				/* case EBADF: */
1238 				/* case EACCES: */
1239 				/* case ENOTSOCK: */
1240 				/* case EFAULT: */
1241 				/* case EMSGSIZE: */
1242 				/* case EAGAIN: */
1243 				/* case ENOBUFS: */
1244 				/* case ECONNREFUSED: */
1245 				default:
1246 					dprintf("removing entry: errno=%d\n", e);
1247 					f->f_type = F_UNUSED;
1248 					break;
1249 				}
1250 			}
1251 		}
1252 		break;
1253 
1254 	case F_FILE:
1255 		dprintf(" %s\n", f->f_un.f_fname);
1256 		v->iov_base = lf;
1257 		v->iov_len = 1;
1258 		if (writev(f->f_file, iov, IOV_SIZE) < 0) {
1259 			/*
1260 			 * If writev(2) fails for potentially transient errors
1261 			 * like the filesystem being full, ignore it.
1262 			 * Otherwise remove this logfile from the list.
1263 			 */
1264 			if (errno != ENOSPC) {
1265 				int e = errno;
1266 				(void)close(f->f_file);
1267 				f->f_type = F_UNUSED;
1268 				errno = e;
1269 				logerror(f->f_un.f_fname);
1270 			}
1271 		} else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1272 			f->f_flags |= FFLAG_NEEDSYNC;
1273 			needdofsync = 1;
1274 		}
1275 		break;
1276 
1277 	case F_PIPE:
1278 		dprintf(" %s\n", f->f_un.f_pipe.f_pname);
1279 		v->iov_base = lf;
1280 		v->iov_len = 1;
1281 		if (f->f_un.f_pipe.f_pid == 0) {
1282 			if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
1283 						&f->f_un.f_pipe.f_pid)) < 0) {
1284 				f->f_type = F_UNUSED;
1285 				logerror(f->f_un.f_pipe.f_pname);
1286 				break;
1287 			}
1288 		}
1289 		if (writev(f->f_file, iov, IOV_SIZE) < 0) {
1290 			int e = errno;
1291 			(void)close(f->f_file);
1292 			if (f->f_un.f_pipe.f_pid > 0)
1293 				deadq_enter(f->f_un.f_pipe.f_pid,
1294 					    f->f_un.f_pipe.f_pname);
1295 			f->f_un.f_pipe.f_pid = 0;
1296 			errno = e;
1297 			logerror(f->f_un.f_pipe.f_pname);
1298 		}
1299 		break;
1300 
1301 	case F_CONSOLE:
1302 		if (flags & IGN_CONS) {
1303 			dprintf(" (ignored)\n");
1304 			break;
1305 		}
1306 		/* FALLTHROUGH */
1307 
1308 	case F_TTY:
1309 		dprintf(" %s%s\n", _PATH_DEV, f->f_un.f_fname);
1310 		v->iov_base = crlf;
1311 		v->iov_len = 2;
1312 
1313 		errno = 0;	/* ttymsg() only sometimes returns an errno */
1314 		if ((msgret = ttymsg(iov, IOV_SIZE, f->f_un.f_fname, 10))) {
1315 			f->f_type = F_UNUSED;
1316 			logerror(msgret);
1317 		}
1318 		break;
1319 
1320 	case F_USERS:
1321 	case F_WALL:
1322 		dprintf("\n");
1323 		v->iov_base = crlf;
1324 		v->iov_len = 2;
1325 		wallmsg(f, iov, IOV_SIZE);
1326 		break;
1327 	}
1328 	f->f_prevcount = 0;
1329 	free(wmsg);
1330 }
1331 
1332 /*
1333  *  WALLMSG -- Write a message to the world at large
1334  *
1335  *	Write the specified message to either the entire
1336  *	world, or a list of approved users.
1337  */
1338 static void
1339 wallmsg(struct filed *f, struct iovec *iov, const int iovlen)
1340 {
1341 	static int reenter;			/* avoid calling ourselves */
1342 	struct utmpx *ut;
1343 	int i;
1344 	const char *p;
1345 
1346 	if (reenter++)
1347 		return;
1348 	setutxent();
1349 	/* NOSTRICT */
1350 	while ((ut = getutxent()) != NULL) {
1351 		if (ut->ut_type != USER_PROCESS)
1352 			continue;
1353 		if (f->f_type == F_WALL) {
1354 			if ((p = ttymsg(iov, iovlen, ut->ut_line,
1355 			    TTYMSGTIME)) != NULL) {
1356 				errno = 0;	/* already in msg */
1357 				logerror(p);
1358 			}
1359 			continue;
1360 		}
1361 		/* should we send the message to this user? */
1362 		for (i = 0; i < MAXUNAMES; i++) {
1363 			if (!f->f_un.f_uname[i][0])
1364 				break;
1365 			if (!strcmp(f->f_un.f_uname[i], ut->ut_user)) {
1366 				if ((p = ttymsg(iov, iovlen, ut->ut_line,
1367 				    TTYMSGTIME)) != NULL) {
1368 					errno = 0;	/* already in msg */
1369 					logerror(p);
1370 				}
1371 				break;
1372 			}
1373 		}
1374 	}
1375 	endutxent();
1376 	reenter = 0;
1377 }
1378 
1379 static void
1380 reapchild(int signo __unused)
1381 {
1382 	int status;
1383 	pid_t pid;
1384 	struct filed *f;
1385 
1386 	while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
1387 		if (!Initialized)
1388 			/* Don't tell while we are initting. */
1389 			continue;
1390 
1391 		/* First, look if it's a process from the dead queue. */
1392 		if (deadq_remove(pid))
1393 			continue;
1394 
1395 		/* Now, look in list of active processes. */
1396 		for (f = Files; f; f = f->f_next) {
1397 			if (f->f_type == F_PIPE &&
1398 			    f->f_un.f_pipe.f_pid == pid) {
1399 				(void)close(f->f_file);
1400 				f->f_un.f_pipe.f_pid = 0;
1401 				log_deadchild(pid, status,
1402 					      f->f_un.f_pipe.f_pname);
1403 				break;
1404 			}
1405 		}
1406 	}
1407 }
1408 
1409 /*
1410  * Return a printable representation of a host address.
1411  */
1412 static const char *
1413 cvthname(struct sockaddr *f)
1414 {
1415 	int error, hl;
1416 	sigset_t omask, nmask;
1417 	static char hname[NI_MAXHOST], ip[NI_MAXHOST];
1418 
1419 	error = getnameinfo((struct sockaddr *)f,
1420 			    ((struct sockaddr *)f)->sa_len,
1421 			    ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
1422 	dprintf("cvthname(%s)\n", ip);
1423 
1424 	if (error) {
1425 		dprintf("Malformed from address %s\n", gai_strerror(error));
1426 		return ("???");
1427 	}
1428 	if (!resolve)
1429 		return (ip);
1430 
1431 	sigemptyset(&nmask);
1432 	sigaddset(&nmask, SIGHUP);
1433 	sigprocmask(SIG_BLOCK, &nmask, &omask);
1434 	error = getnameinfo((struct sockaddr *)f,
1435 			    ((struct sockaddr *)f)->sa_len,
1436 			    hname, sizeof hname, NULL, 0, NI_NAMEREQD);
1437 	sigprocmask(SIG_SETMASK, &omask, NULL);
1438 	if (error) {
1439 		dprintf("Host name for your address (%s) unknown\n", ip);
1440 		return (ip);
1441 	}
1442 	hl = strlen(hname);
1443 	if (hl > 0 && hname[hl-1] == '.')
1444 		hname[--hl] = '\0';
1445 	trimdomain(hname, hl);
1446 	return (hname);
1447 }
1448 
1449 static void
1450 dodie(int signo)
1451 {
1452 
1453 	WantDie = signo;
1454 }
1455 
1456 static void
1457 domark(int signo __unused)
1458 {
1459 
1460 	MarkSet = 1;
1461 }
1462 
1463 /*
1464  * Print syslogd errors some place.
1465  */
1466 static void
1467 logerror(const char *type)
1468 {
1469 	char buf[512];
1470 	static int recursed = 0;
1471 
1472 	/* If there's an error while trying to log an error, give up. */
1473 	if (recursed)
1474 		return;
1475 	recursed++;
1476 	if (errno)
1477 		(void)snprintf(buf,
1478 		    sizeof buf, "syslogd: %s: %s", type, strerror(errno));
1479 	else
1480 		(void)snprintf(buf, sizeof buf, "syslogd: %s", type);
1481 	errno = 0;
1482 	dprintf("%s\n", buf);
1483 	logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1484 	recursed--;
1485 }
1486 
1487 static void
1488 die(int signo)
1489 {
1490 	struct filed *f;
1491 	struct funix *fx;
1492 	int was_initialized;
1493 	char buf[100];
1494 
1495 	was_initialized = Initialized;
1496 	Initialized = 0;	/* Don't log SIGCHLDs. */
1497 	for (f = Files; f != NULL; f = f->f_next) {
1498 		/* flush any pending output */
1499 		if (f->f_prevcount)
1500 			fprintlog(f, 0, NULL);
1501 		if (f->f_type == F_PIPE && f->f_un.f_pipe.f_pid > 0) {
1502 			(void)close(f->f_file);
1503 			f->f_un.f_pipe.f_pid = 0;
1504 		}
1505 	}
1506 	Initialized = was_initialized;
1507 	if (signo) {
1508 		dprintf("syslogd: exiting on signal %d\n", signo);
1509 		(void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
1510 		errno = 0;
1511 		logerror(buf);
1512 	}
1513 	STAILQ_FOREACH(fx, &funixes, next)
1514 		(void)unlink(fx->name);
1515 	pidfile_remove(pfh);
1516 
1517 	exit(1);
1518 }
1519 
1520 /*
1521  *  INIT -- Initialize syslogd from configuration table
1522  */
1523 static void
1524 init(int signo)
1525 {
1526 	int i;
1527 	FILE *cf;
1528 	struct filed *f, *next, **nextp;
1529 	char *p;
1530 	char cline[LINE_MAX];
1531  	char prog[NAME_MAX+1];
1532 	char host[MAXHOSTNAMELEN];
1533 	char oldLocalHostName[MAXHOSTNAMELEN];
1534 	char hostMsg[2*MAXHOSTNAMELEN+40];
1535 	char bootfileMsg[LINE_MAX];
1536 
1537 	dprintf("init\n");
1538 
1539 	/*
1540 	 * Load hostname (may have changed).
1541 	 */
1542 	if (signo != 0)
1543 		(void)strlcpy(oldLocalHostName, LocalHostName,
1544 		    sizeof(oldLocalHostName));
1545 	if (gethostname(LocalHostName, sizeof(LocalHostName)))
1546 		err(EX_OSERR, "gethostname() failed");
1547 	if ((p = strchr(LocalHostName, '.')) != NULL) {
1548 		*p++ = '\0';
1549 		LocalDomain = p;
1550 	} else {
1551 		LocalDomain = "";
1552 	}
1553 
1554 	/*
1555 	 *  Close all open log files.
1556 	 */
1557 	Initialized = 0;
1558 	for (f = Files; f != NULL; f = next) {
1559 		/* flush any pending output */
1560 		if (f->f_prevcount)
1561 			fprintlog(f, 0, NULL);
1562 
1563 		switch (f->f_type) {
1564 		case F_FILE:
1565 		case F_FORW:
1566 		case F_CONSOLE:
1567 		case F_TTY:
1568 			(void)close(f->f_file);
1569 			break;
1570 		case F_PIPE:
1571 			if (f->f_un.f_pipe.f_pid > 0) {
1572 				(void)close(f->f_file);
1573 				deadq_enter(f->f_un.f_pipe.f_pid,
1574 					    f->f_un.f_pipe.f_pname);
1575 			}
1576 			f->f_un.f_pipe.f_pid = 0;
1577 			break;
1578 		}
1579 		next = f->f_next;
1580 		if (f->f_program) free(f->f_program);
1581 		if (f->f_host) free(f->f_host);
1582 		free((char *)f);
1583 	}
1584 	Files = NULL;
1585 	nextp = &Files;
1586 
1587 	/* open the configuration file */
1588 	if ((cf = fopen(ConfFile, "r")) == NULL) {
1589 		dprintf("cannot open %s\n", ConfFile);
1590 		*nextp = (struct filed *)calloc(1, sizeof(*f));
1591 		if (*nextp == NULL) {
1592 			logerror("calloc");
1593 			exit(1);
1594 		}
1595 		cfline("*.ERR\t/dev/console", *nextp, "*", "*");
1596 		(*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1597 		if ((*nextp)->f_next == NULL) {
1598 			logerror("calloc");
1599 			exit(1);
1600 		}
1601 		cfline("*.PANIC\t*", (*nextp)->f_next, "*", "*");
1602 		Initialized = 1;
1603 		return;
1604 	}
1605 
1606 	/*
1607 	 *  Foreach line in the conf table, open that file.
1608 	 */
1609 	f = NULL;
1610 	(void)strlcpy(host, "*", sizeof(host));
1611 	(void)strlcpy(prog, "*", sizeof(prog));
1612 	while (fgets(cline, sizeof(cline), cf) != NULL) {
1613 		/*
1614 		 * check for end-of-section, comments, strip off trailing
1615 		 * spaces and newline character. #!prog is treated specially:
1616 		 * following lines apply only to that program.
1617 		 */
1618 		for (p = cline; isspace(*p); ++p)
1619 			continue;
1620 		if (*p == 0)
1621 			continue;
1622 		if (*p == '#') {
1623 			p++;
1624 			if (*p != '!' && *p != '+' && *p != '-')
1625 				continue;
1626 		}
1627 		if (*p == '+' || *p == '-') {
1628 			host[0] = *p++;
1629 			while (isspace(*p))
1630 				p++;
1631 			if ((!*p) || (*p == '*')) {
1632 				(void)strlcpy(host, "*", sizeof(host));
1633 				continue;
1634 			}
1635 			if (*p == '@')
1636 				p = LocalHostName;
1637 			for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
1638 				if (!isalnum(*p) && *p != '.' && *p != '-'
1639 				    && *p != ',' && *p != ':' && *p != '%')
1640 					break;
1641 				host[i] = *p++;
1642 			}
1643 			host[i] = '\0';
1644 			continue;
1645 		}
1646 		if (*p == '!') {
1647 			p++;
1648 			while (isspace(*p)) p++;
1649 			if ((!*p) || (*p == '*')) {
1650 				(void)strlcpy(prog, "*", sizeof(prog));
1651 				continue;
1652 			}
1653 			for (i = 0; i < NAME_MAX; i++) {
1654 				if (!isprint(p[i]) || isspace(p[i]))
1655 					break;
1656 				prog[i] = p[i];
1657 			}
1658 			prog[i] = 0;
1659 			continue;
1660 		}
1661 		for (p = cline + 1; *p != '\0'; p++) {
1662 			if (*p != '#')
1663 				continue;
1664 			if (*(p - 1) == '\\') {
1665 				strcpy(p - 1, p);
1666 				p--;
1667 				continue;
1668 			}
1669 			*p = '\0';
1670 			break;
1671 		}
1672 		for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
1673 			cline[i] = '\0';
1674 		f = (struct filed *)calloc(1, sizeof(*f));
1675 		if (f == NULL) {
1676 			logerror("calloc");
1677 			exit(1);
1678 		}
1679 		*nextp = f;
1680 		nextp = &f->f_next;
1681 		cfline(cline, f, prog, host);
1682 	}
1683 
1684 	/* close the configuration file */
1685 	(void)fclose(cf);
1686 
1687 	Initialized = 1;
1688 
1689 	if (Debug) {
1690 		int port;
1691 		for (f = Files; f; f = f->f_next) {
1692 			for (i = 0; i <= LOG_NFACILITIES; i++)
1693 				if (f->f_pmask[i] == INTERNAL_NOPRI)
1694 					printf("X ");
1695 				else
1696 					printf("%d ", f->f_pmask[i]);
1697 			printf("%s: ", TypeNames[f->f_type]);
1698 			switch (f->f_type) {
1699 			case F_FILE:
1700 				printf("%s", f->f_un.f_fname);
1701 				break;
1702 
1703 			case F_CONSOLE:
1704 			case F_TTY:
1705 				printf("%s%s", _PATH_DEV, f->f_un.f_fname);
1706 				break;
1707 
1708 			case F_FORW:
1709 				port = (int)ntohs(((struct sockaddr_in *)
1710 				    (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1711 				if (port != 514) {
1712 					printf("%s:%d",
1713 						f->f_un.f_forw.f_hname, port);
1714 				} else {
1715 					printf("%s", f->f_un.f_forw.f_hname);
1716 				}
1717 				break;
1718 
1719 			case F_PIPE:
1720 				printf("%s", f->f_un.f_pipe.f_pname);
1721 				break;
1722 
1723 			case F_USERS:
1724 				for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1725 					printf("%s, ", f->f_un.f_uname[i]);
1726 				break;
1727 			}
1728 			if (f->f_program)
1729 				printf(" (%s)", f->f_program);
1730 			printf("\n");
1731 		}
1732 	}
1733 
1734 	logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1735 	dprintf("syslogd: restarted\n");
1736 	/*
1737 	 * Log a change in hostname, but only on a restart.
1738 	 */
1739 	if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
1740 		(void)snprintf(hostMsg, sizeof(hostMsg),
1741 		    "syslogd: hostname changed, \"%s\" to \"%s\"",
1742 		    oldLocalHostName, LocalHostName);
1743 		logmsg(LOG_SYSLOG|LOG_INFO, hostMsg, LocalHostName, ADDDATE);
1744 		dprintf("%s\n", hostMsg);
1745 	}
1746 	/*
1747 	 * Log the kernel boot file if we aren't going to use it as
1748 	 * the prefix, and if this is *not* a restart.
1749 	 */
1750 	if (signo == 0 && !use_bootfile) {
1751 		(void)snprintf(bootfileMsg, sizeof(bootfileMsg),
1752 		    "syslogd: kernel boot file is %s", bootfile);
1753 		logmsg(LOG_KERN|LOG_INFO, bootfileMsg, LocalHostName, ADDDATE);
1754 		dprintf("%s\n", bootfileMsg);
1755 	}
1756 }
1757 
1758 /*
1759  * Crack a configuration file line
1760  */
1761 static void
1762 cfline(const char *line, struct filed *f, const char *prog, const char *host)
1763 {
1764 	struct addrinfo hints, *res;
1765 	int error, i, pri, syncfile;
1766 	const char *p, *q;
1767 	char *bp;
1768 	char buf[MAXLINE], ebuf[100];
1769 
1770 	dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
1771 
1772 	errno = 0;	/* keep strerror() stuff out of logerror messages */
1773 
1774 	/* clear out file entry */
1775 	memset(f, 0, sizeof(*f));
1776 	for (i = 0; i <= LOG_NFACILITIES; i++)
1777 		f->f_pmask[i] = INTERNAL_NOPRI;
1778 
1779 	/* save hostname if any */
1780 	if (host && *host == '*')
1781 		host = NULL;
1782 	if (host) {
1783 		int hl;
1784 
1785 		f->f_host = strdup(host);
1786 		if (f->f_host == NULL) {
1787 			logerror("strdup");
1788 			exit(1);
1789 		}
1790 		hl = strlen(f->f_host);
1791 		if (hl > 0 && f->f_host[hl-1] == '.')
1792 			f->f_host[--hl] = '\0';
1793 		trimdomain(f->f_host, hl);
1794 	}
1795 
1796 	/* save program name if any */
1797 	if (prog && *prog == '*')
1798 		prog = NULL;
1799 	if (prog) {
1800 		f->f_program = strdup(prog);
1801 		if (f->f_program == NULL) {
1802 			logerror("strdup");
1803 			exit(1);
1804 		}
1805 	}
1806 
1807 	/* scan through the list of selectors */
1808 	for (p = line; *p && *p != '\t' && *p != ' ';) {
1809 		int pri_done;
1810 		int pri_cmp;
1811 		int pri_invert;
1812 
1813 		/* find the end of this facility name list */
1814 		for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
1815 			continue;
1816 
1817 		/* get the priority comparison */
1818 		pri_cmp = 0;
1819 		pri_done = 0;
1820 		pri_invert = 0;
1821 		if (*q == '!') {
1822 			pri_invert = 1;
1823 			q++;
1824 		}
1825 		while (!pri_done) {
1826 			switch (*q) {
1827 			case '<':
1828 				pri_cmp |= PRI_LT;
1829 				q++;
1830 				break;
1831 			case '=':
1832 				pri_cmp |= PRI_EQ;
1833 				q++;
1834 				break;
1835 			case '>':
1836 				pri_cmp |= PRI_GT;
1837 				q++;
1838 				break;
1839 			default:
1840 				pri_done++;
1841 				break;
1842 			}
1843 		}
1844 
1845 		/* collect priority name */
1846 		for (bp = buf; *q && !strchr("\t,; ", *q); )
1847 			*bp++ = *q++;
1848 		*bp = '\0';
1849 
1850 		/* skip cruft */
1851 		while (strchr(",;", *q))
1852 			q++;
1853 
1854 		/* decode priority name */
1855 		if (*buf == '*') {
1856 			pri = LOG_PRIMASK;
1857 			pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
1858 		} else {
1859 			/* Ignore trailing spaces. */
1860 			for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
1861 				buf[i] = '\0';
1862 
1863 			pri = decode(buf, prioritynames);
1864 			if (pri < 0) {
1865 				errno = 0;
1866 				(void)snprintf(ebuf, sizeof ebuf,
1867 				    "unknown priority name \"%s\"", buf);
1868 				logerror(ebuf);
1869 				return;
1870 			}
1871 		}
1872 		if (!pri_cmp)
1873 			pri_cmp = (UniquePriority)
1874 				  ? (PRI_EQ)
1875 				  : (PRI_EQ | PRI_GT)
1876 				  ;
1877 		if (pri_invert)
1878 			pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
1879 
1880 		/* scan facilities */
1881 		while (*p && !strchr("\t.; ", *p)) {
1882 			for (bp = buf; *p && !strchr("\t,;. ", *p); )
1883 				*bp++ = *p++;
1884 			*bp = '\0';
1885 
1886 			if (*buf == '*') {
1887 				for (i = 0; i < LOG_NFACILITIES; i++) {
1888 					f->f_pmask[i] = pri;
1889 					f->f_pcmp[i] = pri_cmp;
1890 				}
1891 			} else {
1892 				i = decode(buf, facilitynames);
1893 				if (i < 0) {
1894 					errno = 0;
1895 					(void)snprintf(ebuf, sizeof ebuf,
1896 					    "unknown facility name \"%s\"",
1897 					    buf);
1898 					logerror(ebuf);
1899 					return;
1900 				}
1901 				f->f_pmask[i >> 3] = pri;
1902 				f->f_pcmp[i >> 3] = pri_cmp;
1903 			}
1904 			while (*p == ',' || *p == ' ')
1905 				p++;
1906 		}
1907 
1908 		p = q;
1909 	}
1910 
1911 	/* skip to action part */
1912 	while (*p == '\t' || *p == ' ')
1913 		p++;
1914 
1915 	if (*p == '-') {
1916 		syncfile = 0;
1917 		p++;
1918 	} else
1919 		syncfile = 1;
1920 
1921 	switch (*p) {
1922 	case '@':
1923 		{
1924 			char *tp;
1925 			char endkey = ':';
1926 			/*
1927 			 * scan forward to see if there is a port defined.
1928 			 * so we can't use strlcpy..
1929 			 */
1930 			i = sizeof(f->f_un.f_forw.f_hname);
1931 			tp = f->f_un.f_forw.f_hname;
1932 			p++;
1933 
1934 			/*
1935 			 * an ipv6 address should start with a '[' in that case
1936 			 * we should scan for a ']'
1937 			 */
1938 			if (*p == '[') {
1939 				p++;
1940 				endkey = ']';
1941 			}
1942 			while (*p && (*p != endkey) && (i-- > 0)) {
1943 				*tp++ = *p++;
1944 			}
1945 			if (endkey == ']' && *p == endkey)
1946 				p++;
1947 			*tp = '\0';
1948 		}
1949 		/* See if we copied a domain and have a port */
1950 		if (*p == ':')
1951 			p++;
1952 		else
1953 			p = NULL;
1954 
1955 		memset(&hints, 0, sizeof(hints));
1956 		hints.ai_family = family;
1957 		hints.ai_socktype = SOCK_DGRAM;
1958 		error = getaddrinfo(f->f_un.f_forw.f_hname,
1959 				p ? p : "syslog", &hints, &res);
1960 		if (error) {
1961 			logerror(gai_strerror(error));
1962 			break;
1963 		}
1964 		f->f_un.f_forw.f_addr = res;
1965 		f->f_type = F_FORW;
1966 		break;
1967 
1968 	case '/':
1969 		if ((f->f_file = open(p, logflags, 0600)) < 0) {
1970 			f->f_type = F_UNUSED;
1971 			logerror(p);
1972 			break;
1973 		}
1974 		if (syncfile)
1975 			f->f_flags |= FFLAG_SYNC;
1976 		if (isatty(f->f_file)) {
1977 			if (strcmp(p, ctty) == 0)
1978 				f->f_type = F_CONSOLE;
1979 			else
1980 				f->f_type = F_TTY;
1981 			(void)strlcpy(f->f_un.f_fname, p + sizeof(_PATH_DEV) - 1,
1982 			    sizeof(f->f_un.f_fname));
1983 		} else {
1984 			(void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
1985 			f->f_type = F_FILE;
1986 		}
1987 		break;
1988 
1989 	case '|':
1990 		f->f_un.f_pipe.f_pid = 0;
1991 		(void)strlcpy(f->f_un.f_pipe.f_pname, p + 1,
1992 		    sizeof(f->f_un.f_pipe.f_pname));
1993 		f->f_type = F_PIPE;
1994 		break;
1995 
1996 	case '*':
1997 		f->f_type = F_WALL;
1998 		break;
1999 
2000 	default:
2001 		for (i = 0; i < MAXUNAMES && *p; i++) {
2002 			for (q = p; *q && *q != ','; )
2003 				q++;
2004 			(void)strncpy(f->f_un.f_uname[i], p, MAXLOGNAME - 1);
2005 			if ((q - p) >= MAXLOGNAME)
2006 				f->f_un.f_uname[i][MAXLOGNAME - 1] = '\0';
2007 			else
2008 				f->f_un.f_uname[i][q - p] = '\0';
2009 			while (*q == ',' || *q == ' ')
2010 				q++;
2011 			p = q;
2012 		}
2013 		f->f_type = F_USERS;
2014 		break;
2015 	}
2016 }
2017 
2018 
2019 /*
2020  *  Decode a symbolic name to a numeric value
2021  */
2022 static int
2023 decode(const char *name, const CODE *codetab)
2024 {
2025 	const CODE *c;
2026 	char *p, buf[40];
2027 
2028 	if (isdigit(*name))
2029 		return (atoi(name));
2030 
2031 	for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
2032 		if (isupper(*name))
2033 			*p = tolower(*name);
2034 		else
2035 			*p = *name;
2036 	}
2037 	*p = '\0';
2038 	for (c = codetab; c->c_name; c++)
2039 		if (!strcmp(buf, c->c_name))
2040 			return (c->c_val);
2041 
2042 	return (-1);
2043 }
2044 
2045 static void
2046 markit(void)
2047 {
2048 	struct filed *f;
2049 	dq_t q, next;
2050 
2051 	now = time(NULL);
2052 	MarkSeq += TIMERINTVL;
2053 	if (MarkSeq >= MarkInterval) {
2054 		logmsg(LOG_INFO, "-- MARK --",
2055 		    LocalHostName, ADDDATE|MARK);
2056 		MarkSeq = 0;
2057 	}
2058 
2059 	for (f = Files; f; f = f->f_next) {
2060 		if (f->f_prevcount && now >= REPEATTIME(f)) {
2061 			dprintf("flush %s: repeated %d times, %d sec.\n",
2062 			    TypeNames[f->f_type], f->f_prevcount,
2063 			    repeatinterval[f->f_repeatcount]);
2064 			fprintlog(f, 0, NULL);
2065 			BACKOFF(f);
2066 		}
2067 	}
2068 
2069 	/* Walk the dead queue, and see if we should signal somebody. */
2070 	for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = next) {
2071 		next = TAILQ_NEXT(q, dq_entries);
2072 
2073 		switch (q->dq_timeout) {
2074 		case 0:
2075 			/* Already signalled once, try harder now. */
2076 			if (kill(q->dq_pid, SIGKILL) != 0)
2077 				(void)deadq_remove(q->dq_pid);
2078 			break;
2079 
2080 		case 1:
2081 			/*
2082 			 * Timed out on dead queue, send terminate
2083 			 * signal.  Note that we leave the removal
2084 			 * from the dead queue to reapchild(), which
2085 			 * will also log the event (unless the process
2086 			 * didn't even really exist, in case we simply
2087 			 * drop it from the dead queue).
2088 			 */
2089 			if (kill(q->dq_pid, SIGTERM) != 0)
2090 				(void)deadq_remove(q->dq_pid);
2091 			/* FALLTHROUGH */
2092 
2093 		default:
2094 			q->dq_timeout--;
2095 		}
2096 	}
2097 	MarkSet = 0;
2098 	(void)alarm(TIMERINTVL);
2099 }
2100 
2101 /*
2102  * fork off and become a daemon, but wait for the child to come online
2103  * before returing to the parent, or we get disk thrashing at boot etc.
2104  * Set a timer so we don't hang forever if it wedges.
2105  */
2106 static int
2107 waitdaemon(int nochdir, int noclose, int maxwait)
2108 {
2109 	int fd;
2110 	int status;
2111 	pid_t pid, childpid;
2112 
2113 	switch (childpid = fork()) {
2114 	case -1:
2115 		return (-1);
2116 	case 0:
2117 		break;
2118 	default:
2119 		signal(SIGALRM, timedout);
2120 		alarm(maxwait);
2121 		while ((pid = wait3(&status, 0, NULL)) != -1) {
2122 			if (WIFEXITED(status))
2123 				errx(1, "child pid %d exited with return code %d",
2124 					pid, WEXITSTATUS(status));
2125 			if (WIFSIGNALED(status))
2126 				errx(1, "child pid %d exited on signal %d%s",
2127 					pid, WTERMSIG(status),
2128 					WCOREDUMP(status) ? " (core dumped)" :
2129 					"");
2130 			if (pid == childpid)	/* it's gone... */
2131 				break;
2132 		}
2133 		exit(0);
2134 	}
2135 
2136 	if (setsid() == -1)
2137 		return (-1);
2138 
2139 	if (!nochdir)
2140 		(void)chdir("/");
2141 
2142 	if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2143 		(void)dup2(fd, STDIN_FILENO);
2144 		(void)dup2(fd, STDOUT_FILENO);
2145 		(void)dup2(fd, STDERR_FILENO);
2146 		if (fd > 2)
2147 			(void)close (fd);
2148 	}
2149 	return (getppid());
2150 }
2151 
2152 /*
2153  * We get a SIGALRM from the child when it's running and finished doing it's
2154  * fsync()'s or O_SYNC writes for all the boot messages.
2155  *
2156  * We also get a signal from the kernel if the timer expires, so check to
2157  * see what happened.
2158  */
2159 static void
2160 timedout(int sig __unused)
2161 {
2162 	int left;
2163 	left = alarm(0);
2164 	signal(SIGALRM, SIG_DFL);
2165 	if (left == 0)
2166 		errx(1, "timed out waiting for child");
2167 	else
2168 		_exit(0);
2169 }
2170 
2171 /*
2172  * Add `s' to the list of allowable peer addresses to accept messages
2173  * from.
2174  *
2175  * `s' is a string in the form:
2176  *
2177  *    [*]domainname[:{servicename|portnumber|*}]
2178  *
2179  * or
2180  *
2181  *    netaddr/maskbits[:{servicename|portnumber|*}]
2182  *
2183  * Returns -1 on error, 0 if the argument was valid.
2184  */
2185 static int
2186 allowaddr(char *s)
2187 {
2188 	char *cp1, *cp2;
2189 	struct allowedpeer ap;
2190 	struct servent *se;
2191 	int masklen = -1;
2192 	struct addrinfo hints, *res;
2193 	struct in_addr *addrp, *maskp;
2194 #ifdef INET6
2195 	int i;
2196 	u_int32_t *addr6p, *mask6p;
2197 #endif
2198 	char ip[NI_MAXHOST];
2199 
2200 #ifdef INET6
2201 	if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
2202 #endif
2203 		cp1 = s;
2204 	if ((cp1 = strrchr(cp1, ':'))) {
2205 		/* service/port provided */
2206 		*cp1++ = '\0';
2207 		if (strlen(cp1) == 1 && *cp1 == '*')
2208 			/* any port allowed */
2209 			ap.port = 0;
2210 		else if ((se = getservbyname(cp1, "udp"))) {
2211 			ap.port = ntohs(se->s_port);
2212 		} else {
2213 			ap.port = strtol(cp1, &cp2, 0);
2214 			if (*cp2 != '\0')
2215 				return (-1); /* port not numeric */
2216 		}
2217 	} else {
2218 		if ((se = getservbyname("syslog", "udp")))
2219 			ap.port = ntohs(se->s_port);
2220 		else
2221 			/* sanity, should not happen */
2222 			ap.port = 514;
2223 	}
2224 
2225 	if ((cp1 = strchr(s, '/')) != NULL &&
2226 	    strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
2227 		*cp1 = '\0';
2228 		if ((masklen = atoi(cp1 + 1)) < 0)
2229 			return (-1);
2230 	}
2231 #ifdef INET6
2232 	if (*s == '[') {
2233 		cp2 = s + strlen(s) - 1;
2234 		if (*cp2 == ']') {
2235 			++s;
2236 			*cp2 = '\0';
2237 		} else {
2238 			cp2 = NULL;
2239 		}
2240 	} else {
2241 		cp2 = NULL;
2242 	}
2243 #endif
2244 	memset(&hints, 0, sizeof(hints));
2245 	hints.ai_family = PF_UNSPEC;
2246 	hints.ai_socktype = SOCK_DGRAM;
2247 	hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2248 	if (getaddrinfo(s, NULL, &hints, &res) == 0) {
2249 		ap.isnumeric = 1;
2250 		memcpy(&ap.a_addr, res->ai_addr, res->ai_addrlen);
2251 		memset(&ap.a_mask, 0, sizeof(ap.a_mask));
2252 		ap.a_mask.ss_family = res->ai_family;
2253 		if (res->ai_family == AF_INET) {
2254 			ap.a_mask.ss_len = sizeof(struct sockaddr_in);
2255 			maskp = &((struct sockaddr_in *)&ap.a_mask)->sin_addr;
2256 			addrp = &((struct sockaddr_in *)&ap.a_addr)->sin_addr;
2257 			if (masklen < 0) {
2258 				/* use default netmask */
2259 				if (IN_CLASSA(ntohl(addrp->s_addr)))
2260 					maskp->s_addr = htonl(IN_CLASSA_NET);
2261 				else if (IN_CLASSB(ntohl(addrp->s_addr)))
2262 					maskp->s_addr = htonl(IN_CLASSB_NET);
2263 				else
2264 					maskp->s_addr = htonl(IN_CLASSC_NET);
2265 			} else if (masklen <= 32) {
2266 				/* convert masklen to netmask */
2267 				if (masklen == 0)
2268 					maskp->s_addr = 0;
2269 				else
2270 					maskp->s_addr = htonl(~((1 << (32 - masklen)) - 1));
2271 			} else {
2272 				freeaddrinfo(res);
2273 				return (-1);
2274 			}
2275 			/* Lose any host bits in the network number. */
2276 			addrp->s_addr &= maskp->s_addr;
2277 		}
2278 #ifdef INET6
2279 		else if (res->ai_family == AF_INET6 && masklen <= 128) {
2280 			ap.a_mask.ss_len = sizeof(struct sockaddr_in6);
2281 			if (masklen < 0)
2282 				masklen = 128;
2283 			mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2284 			/* convert masklen to netmask */
2285 			while (masklen > 0) {
2286 				if (masklen < 32) {
2287 					*mask6p = htonl(~(0xffffffff >> masklen));
2288 					break;
2289 				}
2290 				*mask6p++ = 0xffffffff;
2291 				masklen -= 32;
2292 			}
2293 			/* Lose any host bits in the network number. */
2294 			mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2295 			addr6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_addr)->sin6_addr;
2296 			for (i = 0; i < 4; i++)
2297 				addr6p[i] &= mask6p[i];
2298 		}
2299 #endif
2300 		else {
2301 			freeaddrinfo(res);
2302 			return (-1);
2303 		}
2304 		freeaddrinfo(res);
2305 	} else {
2306 		/* arg `s' is domain name */
2307 		ap.isnumeric = 0;
2308 		ap.a_name = s;
2309 		if (cp1)
2310 			*cp1 = '/';
2311 #ifdef INET6
2312 		if (cp2) {
2313 			*cp2 = ']';
2314 			--s;
2315 		}
2316 #endif
2317 	}
2318 
2319 	if (Debug) {
2320 		printf("allowaddr: rule %d: ", NumAllowed);
2321 		if (ap.isnumeric) {
2322 			printf("numeric, ");
2323 			getnameinfo((struct sockaddr *)&ap.a_addr,
2324 				    ((struct sockaddr *)&ap.a_addr)->sa_len,
2325 				    ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2326 			printf("addr = %s, ", ip);
2327 			getnameinfo((struct sockaddr *)&ap.a_mask,
2328 				    ((struct sockaddr *)&ap.a_mask)->sa_len,
2329 				    ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2330 			printf("mask = %s; ", ip);
2331 		} else {
2332 			printf("domainname = %s; ", ap.a_name);
2333 		}
2334 		printf("port = %d\n", ap.port);
2335 	}
2336 
2337 	if ((AllowedPeers = realloc(AllowedPeers,
2338 				    ++NumAllowed * sizeof(struct allowedpeer)))
2339 	    == NULL) {
2340 		logerror("realloc");
2341 		exit(1);
2342 	}
2343 	memcpy(&AllowedPeers[NumAllowed - 1], &ap, sizeof(struct allowedpeer));
2344 	return (0);
2345 }
2346 
2347 /*
2348  * Validate that the remote peer has permission to log to us.
2349  */
2350 static int
2351 validate(struct sockaddr *sa, const char *hname)
2352 {
2353 	int i;
2354 	size_t l1, l2;
2355 	char *cp, name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
2356 	struct allowedpeer *ap;
2357 	struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
2358 #ifdef INET6
2359 	int j, reject;
2360 	struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
2361 #endif
2362 	struct addrinfo hints, *res;
2363 	u_short sport;
2364 
2365 	if (NumAllowed == 0)
2366 		/* traditional behaviour, allow everything */
2367 		return (1);
2368 
2369 	(void)strlcpy(name, hname, sizeof(name));
2370 	memset(&hints, 0, sizeof(hints));
2371 	hints.ai_family = PF_UNSPEC;
2372 	hints.ai_socktype = SOCK_DGRAM;
2373 	hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2374 	if (getaddrinfo(name, NULL, &hints, &res) == 0)
2375 		freeaddrinfo(res);
2376 	else if (strchr(name, '.') == NULL) {
2377 		strlcat(name, ".", sizeof name);
2378 		strlcat(name, LocalDomain, sizeof name);
2379 	}
2380 	if (getnameinfo(sa, sa->sa_len, ip, sizeof ip, port, sizeof port,
2381 			NI_NUMERICHOST | NI_NUMERICSERV) != 0)
2382 		return (0);	/* for safety, should not occur */
2383 	dprintf("validate: dgram from IP %s, port %s, name %s;\n",
2384 		ip, port, name);
2385 	sport = atoi(port);
2386 
2387 	/* now, walk down the list */
2388 	for (i = 0, ap = AllowedPeers; i < NumAllowed; i++, ap++) {
2389 		if (ap->port != 0 && ap->port != sport) {
2390 			dprintf("rejected in rule %d due to port mismatch.\n", i);
2391 			continue;
2392 		}
2393 
2394 		if (ap->isnumeric) {
2395 			if (ap->a_addr.ss_family != sa->sa_family) {
2396 				dprintf("rejected in rule %d due to address family mismatch.\n", i);
2397 				continue;
2398 			}
2399 			if (ap->a_addr.ss_family == AF_INET) {
2400 				sin4 = (struct sockaddr_in *)sa;
2401 				a4p = (struct sockaddr_in *)&ap->a_addr;
2402 				m4p = (struct sockaddr_in *)&ap->a_mask;
2403 				if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
2404 				    != a4p->sin_addr.s_addr) {
2405 					dprintf("rejected in rule %d due to IP mismatch.\n", i);
2406 					continue;
2407 				}
2408 			}
2409 #ifdef INET6
2410 			else if (ap->a_addr.ss_family == AF_INET6) {
2411 				sin6 = (struct sockaddr_in6 *)sa;
2412 				a6p = (struct sockaddr_in6 *)&ap->a_addr;
2413 				m6p = (struct sockaddr_in6 *)&ap->a_mask;
2414 				if (a6p->sin6_scope_id != 0 &&
2415 				    sin6->sin6_scope_id != a6p->sin6_scope_id) {
2416 					dprintf("rejected in rule %d due to scope mismatch.\n", i);
2417 					continue;
2418 				}
2419 				reject = 0;
2420 				for (j = 0; j < 16; j += 4) {
2421 					if ((*(u_int32_t *)&sin6->sin6_addr.s6_addr[j] & *(u_int32_t *)&m6p->sin6_addr.s6_addr[j])
2422 					    != *(u_int32_t *)&a6p->sin6_addr.s6_addr[j]) {
2423 						++reject;
2424 						break;
2425 					}
2426 				}
2427 				if (reject) {
2428 					dprintf("rejected in rule %d due to IP mismatch.\n", i);
2429 					continue;
2430 				}
2431 			}
2432 #endif
2433 			else
2434 				continue;
2435 		} else {
2436 			cp = ap->a_name;
2437 			l1 = strlen(name);
2438 			if (*cp == '*') {
2439 				/* allow wildmatch */
2440 				cp++;
2441 				l2 = strlen(cp);
2442 				if (l2 > l1 || memcmp(cp, &name[l1 - l2], l2) != 0) {
2443 					dprintf("rejected in rule %d due to name mismatch.\n", i);
2444 					continue;
2445 				}
2446 			} else {
2447 				/* exact match */
2448 				l2 = strlen(cp);
2449 				if (l2 != l1 || memcmp(cp, name, l1) != 0) {
2450 					dprintf("rejected in rule %d due to name mismatch.\n", i);
2451 					continue;
2452 				}
2453 			}
2454 		}
2455 		dprintf("accepted in rule %d.\n", i);
2456 		return (1);	/* hooray! */
2457 	}
2458 	return (0);
2459 }
2460 
2461 /*
2462  * Fairly similar to popen(3), but returns an open descriptor, as
2463  * opposed to a FILE *.
2464  */
2465 static int
2466 p_open(const char *prog, pid_t *rpid)
2467 {
2468 	int pfd[2], nulldesc;
2469 	pid_t pid;
2470 	sigset_t omask, mask;
2471 	char *argv[4]; /* sh -c cmd NULL */
2472 	char errmsg[200];
2473 
2474 	if (pipe(pfd) == -1)
2475 		return (-1);
2476 	if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
2477 		/* we are royally screwed anyway */
2478 		return (-1);
2479 
2480 	sigemptyset(&mask);
2481 	sigaddset(&mask, SIGALRM);
2482 	sigaddset(&mask, SIGHUP);
2483 	sigprocmask(SIG_BLOCK, &mask, &omask);
2484 	switch ((pid = fork())) {
2485 	case -1:
2486 		sigprocmask(SIG_SETMASK, &omask, 0);
2487 		close(nulldesc);
2488 		return (-1);
2489 
2490 	case 0:
2491 		argv[0] = strdup("sh");
2492 		argv[1] = strdup("-c");
2493 		argv[2] = strdup(prog);
2494 		argv[3] = NULL;
2495 		if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
2496 			logerror("strdup");
2497 			exit(1);
2498 		}
2499 
2500 		alarm(0);
2501 		(void)setsid();	/* Avoid catching SIGHUPs. */
2502 
2503 		/*
2504 		 * Throw away pending signals, and reset signal
2505 		 * behaviour to standard values.
2506 		 */
2507 		signal(SIGALRM, SIG_IGN);
2508 		signal(SIGHUP, SIG_IGN);
2509 		sigprocmask(SIG_SETMASK, &omask, 0);
2510 		signal(SIGPIPE, SIG_DFL);
2511 		signal(SIGQUIT, SIG_DFL);
2512 		signal(SIGALRM, SIG_DFL);
2513 		signal(SIGHUP, SIG_DFL);
2514 
2515 		dup2(pfd[0], STDIN_FILENO);
2516 		dup2(nulldesc, STDOUT_FILENO);
2517 		dup2(nulldesc, STDERR_FILENO);
2518 		closefrom(3);
2519 
2520 		(void)execvp(_PATH_BSHELL, argv);
2521 		_exit(255);
2522 	}
2523 
2524 	sigprocmask(SIG_SETMASK, &omask, 0);
2525 	close(nulldesc);
2526 	close(pfd[0]);
2527 	/*
2528 	 * Avoid blocking on a hung pipe.  With O_NONBLOCK, we are
2529 	 * supposed to get an EWOULDBLOCK on writev(2), which is
2530 	 * caught by the logic above anyway, which will in turn close
2531 	 * the pipe, and fork a new logging subprocess if necessary.
2532 	 * The stale subprocess will be killed some time later unless
2533 	 * it terminated itself due to closing its input pipe (so we
2534 	 * get rid of really dead puppies).
2535 	 */
2536 	if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
2537 		/* This is bad. */
2538 		(void)snprintf(errmsg, sizeof errmsg,
2539 			       "Warning: cannot change pipe to PID %d to "
2540 			       "non-blocking behaviour.",
2541 			       (int)pid);
2542 		logerror(errmsg);
2543 	}
2544 	*rpid = pid;
2545 	return (pfd[1]);
2546 }
2547 
2548 static void
2549 deadq_enter(pid_t pid, const char *name)
2550 {
2551 	dq_t p;
2552 	int status;
2553 
2554 	/*
2555 	 * Be paranoid, if we can't signal the process, don't enter it
2556 	 * into the dead queue (perhaps it's already dead).  If possible,
2557 	 * we try to fetch and log the child's status.
2558 	 */
2559 	if (kill(pid, 0) != 0) {
2560 		if (waitpid(pid, &status, WNOHANG) > 0)
2561 			log_deadchild(pid, status, name);
2562 		return;
2563 	}
2564 
2565 	p = malloc(sizeof(struct deadq_entry));
2566 	if (p == NULL) {
2567 		logerror("malloc");
2568 		exit(1);
2569 	}
2570 
2571 	p->dq_pid = pid;
2572 	p->dq_timeout = DQ_TIMO_INIT;
2573 	TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
2574 }
2575 
2576 static int
2577 deadq_remove(pid_t pid)
2578 {
2579 	dq_t q;
2580 
2581 	TAILQ_FOREACH(q, &deadq_head, dq_entries) {
2582 		if (q->dq_pid == pid) {
2583 			TAILQ_REMOVE(&deadq_head, q, dq_entries);
2584 				free(q);
2585 				return (1);
2586 		}
2587 	}
2588 
2589 	return (0);
2590 }
2591 
2592 static void
2593 log_deadchild(pid_t pid, int status, const char *name)
2594 {
2595 	int code;
2596 	char buf[256];
2597 	const char *reason;
2598 
2599 	errno = 0; /* Keep strerror() stuff out of logerror messages. */
2600 	if (WIFSIGNALED(status)) {
2601 		reason = "due to signal";
2602 		code = WTERMSIG(status);
2603 	} else {
2604 		reason = "with status";
2605 		code = WEXITSTATUS(status);
2606 		if (code == 0)
2607 			return;
2608 	}
2609 	(void)snprintf(buf, sizeof buf,
2610 		       "Logging subprocess %d (%s) exited %s %d.",
2611 		       pid, name, reason, code);
2612 	logerror(buf);
2613 }
2614 
2615 static int *
2616 socksetup(int af, char *bindhostname)
2617 {
2618 	struct addrinfo hints, *res, *r;
2619 	const char *bindservice;
2620 	char *cp;
2621 	int error, maxs, *s, *socks;
2622 
2623 	/*
2624 	 * We have to handle this case for backwards compatibility:
2625 	 * If there are two (or more) colons but no '[' and ']',
2626 	 * assume this is an inet6 address without a service.
2627 	 */
2628 	bindservice = "syslog";
2629 	if (bindhostname != NULL) {
2630 #ifdef INET6
2631 		if (*bindhostname == '[' &&
2632 		    (cp = strchr(bindhostname + 1, ']')) != NULL) {
2633 			++bindhostname;
2634 			*cp = '\0';
2635 			if (cp[1] == ':' && cp[2] != '\0')
2636 				bindservice = cp + 2;
2637 		} else {
2638 #endif
2639 			cp = strchr(bindhostname, ':');
2640 			if (cp != NULL && strchr(cp + 1, ':') == NULL) {
2641 				*cp = '\0';
2642 				if (cp[1] != '\0')
2643 					bindservice = cp + 1;
2644 				if (cp == bindhostname)
2645 					bindhostname = NULL;
2646 			}
2647 #ifdef INET6
2648 		}
2649 #endif
2650 	}
2651 
2652 	memset(&hints, 0, sizeof(hints));
2653 	hints.ai_flags = AI_PASSIVE;
2654 	hints.ai_family = af;
2655 	hints.ai_socktype = SOCK_DGRAM;
2656 	error = getaddrinfo(bindhostname, bindservice, &hints, &res);
2657 	if (error) {
2658 		logerror(gai_strerror(error));
2659 		errno = 0;
2660 		die(0);
2661 	}
2662 
2663 	/* Count max number of sockets we may open */
2664 	for (maxs = 0, r = res; r; r = r->ai_next, maxs++);
2665 	socks = malloc((maxs+1) * sizeof(int));
2666 	if (socks == NULL) {
2667 		logerror("couldn't allocate memory for sockets");
2668 		die(0);
2669 	}
2670 
2671 	*socks = 0;   /* num of sockets counter at start of array */
2672 	s = socks + 1;
2673 	for (r = res; r; r = r->ai_next) {
2674 		int on = 1;
2675 		*s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
2676 		if (*s < 0) {
2677 			logerror("socket");
2678 			continue;
2679 		}
2680 #ifdef INET6
2681 		if (r->ai_family == AF_INET6) {
2682 			if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
2683 				       (char *)&on, sizeof (on)) < 0) {
2684 				logerror("setsockopt");
2685 				close(*s);
2686 				continue;
2687 			}
2688 		}
2689 #endif
2690 		if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
2691 			       (char *)&on, sizeof (on)) < 0) {
2692 			logerror("setsockopt");
2693 			close(*s);
2694 			continue;
2695 		}
2696 		/*
2697 		 * RFC 3164 recommends that client side message
2698 		 * should come from the privileged syslogd port.
2699 		 *
2700 		 * If the system administrator choose not to obey
2701 		 * this, we can skip the bind() step so that the
2702 		 * system will choose a port for us.
2703 		 */
2704 		if (!NoBind) {
2705 		if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
2706 				logerror("bind");
2707 			close(*s);
2708 			continue;
2709 		}
2710 
2711 			if (!SecureMode)
2712 				increase_rcvbuf(*s);
2713 		}
2714 
2715 		(*socks)++;
2716 		s++;
2717 	}
2718 
2719 	if (*socks == 0) {
2720 		free(socks);
2721 		if (Debug)
2722 			return (NULL);
2723 		else
2724 			die(0);
2725 	}
2726 	if (res)
2727 		freeaddrinfo(res);
2728 
2729 	return (socks);
2730 }
2731 
2732 static void
2733 increase_rcvbuf(int fd)
2734 {
2735 	socklen_t len, slen;
2736 
2737 	slen = sizeof(len);
2738 
2739 	if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, &slen) == 0) {
2740 		if (len < RCVBUF_MINSIZE) {
2741 			len = RCVBUF_MINSIZE;
2742 			setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, sizeof(len));
2743 		}
2744 	}
2745 }
2746