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