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