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