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