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