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