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