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