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