xref: /freebsd/usr.sbin/syslogd/syslogd.c (revision 00e53a11e8adffa0d3dd71af4eefe64f4f5a4de8)
1 /*
2  * Copyright (c) 1983, 1988, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #ifndef lint
35 static const char copyright[] =
36 "@(#) Copyright (c) 1983, 1988, 1993, 1994\n\
37 	The Regents of the University of California.  All rights reserved.\n";
38 #endif /* not lint */
39 
40 #ifndef lint
41 #if 0
42 static char sccsid[] = "@(#)syslogd.c	8.3 (Berkeley) 4/4/94";
43 #endif
44 static const char rcsid[] =
45 	"$Id: syslogd.c,v 1.43 1998/12/04 06:49:20 jkh Exp $";
46 #endif /* not lint */
47 
48 /*
49  *  syslogd -- log system messages
50  *
51  * This program implements a system log. It takes a series of lines.
52  * Each line may have a priority, signified as "<n>" as
53  * the first characters of the line.  If this is
54  * not present, a default priority is used.
55  *
56  * To kill syslogd, send a signal 15 (terminate).  A signal 1 (hup) will
57  * cause it to reread its configuration file.
58  *
59  * Defined Constants:
60  *
61  * MAXLINE -- the maximimum line length that can be handled.
62  * DEFUPRI -- the default priority for user messages
63  * DEFSPRI -- the default priority for kernel messages
64  *
65  * Author: Eric Allman
66  * extensive changes by Ralph Campbell
67  * more extensive changes by Eric Allman (again)
68  * Extension to log by program name as well as facility and priority
69  *   by Peter da Silva.
70  * -u and -v by Harlan Stenn.
71  * Priority comparison code by Harlan Stenn.
72  */
73 
74 #define	MAXLINE		1024		/* maximum line length */
75 #define	MAXSVLINE	120		/* maximum saved line length */
76 #define DEFUPRI		(LOG_USER|LOG_NOTICE)
77 #define DEFSPRI		(LOG_KERN|LOG_CRIT)
78 #define TIMERINTVL	30		/* interval for checking flush, mark */
79 #define TTYMSGTIME	1		/* timed out passed to ttymsg */
80 
81 #include <sys/param.h>
82 #include <sys/ioctl.h>
83 #include <sys/stat.h>
84 #include <sys/wait.h>
85 #include <sys/socket.h>
86 #include <sys/queue.h>
87 #include <sys/uio.h>
88 #include <sys/un.h>
89 #include <sys/time.h>
90 #include <sys/resource.h>
91 #include <sys/syslimits.h>
92 #include <paths.h>
93 
94 #include <netinet/in.h>
95 #include <netdb.h>
96 #include <arpa/inet.h>
97 
98 #include <ctype.h>
99 #include <err.h>
100 #include <errno.h>
101 #include <fcntl.h>
102 #include <regex.h>
103 #include <setjmp.h>
104 #include <signal.h>
105 #include <stdio.h>
106 #include <stdlib.h>
107 #include <string.h>
108 #include <sysexits.h>
109 #include <unistd.h>
110 #include <utmp.h>
111 #include "pathnames.h"
112 
113 #define SYSLOG_NAMES
114 #include <sys/syslog.h>
115 
116 const char	*ConfFile = _PATH_LOGCONF;
117 const char	*PidFile = _PATH_LOGPID;
118 const char	ctty[] = _PATH_CONSOLE;
119 
120 #define	dprintf		if (Debug) printf
121 
122 #define MAXUNAMES	20	/* maximum number of user names */
123 
124 #define MAXFUNIX       20
125 
126 int nfunix = 1;
127 char *funixn[MAXFUNIX] = { _PATH_LOG };
128 int funix[MAXFUNIX];
129 
130 /*
131  * Flags to logmsg().
132  */
133 
134 #define IGN_CONS	0x001	/* don't print on console */
135 #define SYNC_FILE	0x002	/* do fsync on file after printing */
136 #define ADDDATE		0x004	/* add a date to the message */
137 #define MARK		0x008	/* this message is a mark */
138 #define ISKERNEL	0x010	/* kernel generated message */
139 
140 /*
141  * This structure represents the files that will have log
142  * copies printed.
143  */
144 
145 struct filed {
146 	struct	filed *f_next;		/* next in linked list */
147 	short	f_type;			/* entry type, see below */
148 	short	f_file;			/* file descriptor */
149 	time_t	f_time;			/* time this was last written */
150 	u_char	f_pmask[LOG_NFACILITIES+1];	/* priority mask */
151 	u_char	f_pcmp[LOG_NFACILITIES+1];	/* compare priority */
152 #define PRI_LT	0x1
153 #define PRI_EQ	0x2
154 #define PRI_GT	0x4
155 	char	*f_program;		/* program this applies to */
156 	union {
157 		char	f_uname[MAXUNAMES][UT_NAMESIZE+1];
158 		struct {
159 			char	f_hname[MAXHOSTNAMELEN+1];
160 			struct sockaddr_in	f_addr;
161 		} f_forw;		/* forwarding address */
162 		char	f_fname[MAXPATHLEN];
163 		struct {
164 			char	f_pname[MAXPATHLEN];
165 			pid_t	f_pid;
166 		} f_pipe;
167 	} f_un;
168 	char	f_prevline[MAXSVLINE];		/* last message logged */
169 	char	f_lasttime[16];			/* time of last occurrence */
170 	char	f_prevhost[MAXHOSTNAMELEN+1];	/* host from which recd. */
171 	int	f_prevpri;			/* pri of f_prevline */
172 	int	f_prevlen;			/* length of f_prevline */
173 	int	f_prevcount;			/* repetition cnt of prevline */
174 	int	f_repeatcount;			/* number of "repeated" msgs */
175 };
176 
177 /*
178  * Queue of about-to-be dead processes we should watch out for.
179  */
180 
181 TAILQ_HEAD(stailhead, deadq_entry) deadq_head;
182 struct stailhead *deadq_headp;
183 
184 struct deadq_entry {
185 	pid_t				dq_pid;
186 	int				dq_timeout;
187 	TAILQ_ENTRY(deadq_entry)	dq_entries;
188 };
189 
190 /*
191  * The timeout to apply to processes waiting on the dead queue.  Unit
192  * of measure is `mark intervals', i.e. 20 minutes by default.
193  * Processes on the dead queue will be terminated after that time.
194  */
195 
196 #define DQ_TIMO_INIT	2
197 
198 typedef struct deadq_entry *dq_t;
199 
200 
201 /*
202  * Struct to hold records of network addresses that are allowed to log
203  * to us.
204  */
205 struct allowedpeer {
206 	int isnumeric;
207 	u_short port;
208 	union {
209 		struct {
210 			struct in_addr addr;
211 			struct in_addr mask;
212 		} numeric;
213 		char *name;
214 	} u;
215 #define a_addr u.numeric.addr
216 #define a_mask u.numeric.mask
217 #define a_name u.name
218 };
219 
220 
221 /*
222  * Intervals at which we flush out "message repeated" messages,
223  * in seconds after previous message is logged.  After each flush,
224  * we move to the next interval until we reach the largest.
225  */
226 int	repeatinterval[] = { 30, 120, 600 };	/* # of secs before flush */
227 #define	MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
228 #define	REPEATTIME(f)	((f)->f_time + repeatinterval[(f)->f_repeatcount])
229 #define	BACKOFF(f)	{ if (++(f)->f_repeatcount > MAXREPEAT) \
230 				 (f)->f_repeatcount = MAXREPEAT; \
231 			}
232 
233 /* values for f_type */
234 #define F_UNUSED	0		/* unused entry */
235 #define F_FILE		1		/* regular file */
236 #define F_TTY		2		/* terminal */
237 #define F_CONSOLE	3		/* console terminal */
238 #define F_FORW		4		/* remote machine */
239 #define F_USERS		5		/* list of users */
240 #define F_WALL		6		/* everyone logged on */
241 #define F_PIPE		7		/* pipe to program */
242 
243 char	*TypeNames[8] = {
244 	"UNUSED",	"FILE",		"TTY",		"CONSOLE",
245 	"FORW",		"USERS",	"WALL",		"PIPE"
246 };
247 
248 struct	filed *Files;
249 struct	filed consfile;
250 
251 int	Debug;			/* debug flag */
252 char	LocalHostName[MAXHOSTNAMELEN+1];	/* our hostname */
253 char	*LocalDomain;		/* our local domain name */
254 int	finet;			/* Internet datagram socket */
255 int	LogPort;		/* port number for INET connections */
256 int	Initialized = 0;	/* set when we have initialized ourselves */
257 int	MarkInterval = 20 * 60;	/* interval between marks in seconds */
258 int	MarkSeq = 0;		/* mark sequence number */
259 int	SecureMode = 0;		/* when true, receive only unix domain socks */
260 u_int	Vogons = 0;		/* packets arriving in SecureMode */
261 
262 char	bootfile[MAXLINE+1];	/* booted kernel file */
263 
264 struct allowedpeer *AllowedPeers;
265 int	NumAllowed = 0;		/* # of AllowedPeer entries */
266 
267 int	UniquePriority = 0;	/* Only log specified priority? */
268 int	LogFacPri = 0;		/* Put facility and priority in log message: */
269 				/* 0=no, 1=numeric, 2=names */
270 
271 int	allowaddr __P((char *));
272 void	cfline __P((char *, struct filed *, char *));
273 char   *cvthname __P((struct sockaddr_in *));
274 void	deadq_enter __P((pid_t));
275 int	decode __P((const char *, CODE *));
276 void	die __P((int));
277 void	domark __P((int));
278 void	fprintlog __P((struct filed *, int, char *));
279 void	init __P((int));
280 void	logerror __P((const char *));
281 void	logmsg __P((int, char *, char *, int));
282 void	printline __P((char *, char *));
283 void	printsys __P((char *));
284 int	p_open __P((char *, pid_t *));
285 void	reapchild __P((int));
286 char   *ttymsg __P((struct iovec *, int, char *, int));
287 static void	usage __P((void));
288 int	validate __P((struct sockaddr_in *, const char *));
289 void	wallmsg __P((struct filed *, struct iovec *));
290 int	waitdaemon __P((int, int, int));
291 void	timedout __P((int));
292 
293 int
294 main(argc, argv)
295 	int argc;
296 	char *argv[];
297 {
298 	int ch, i, l, fklog, len;
299 	struct sockaddr_un sunx, fromunix;
300 	struct sockaddr_in sin, frominet;
301 	FILE *fp;
302 	char *p, *hname, line[MAXLINE + 1];
303 	struct timeval tv, *tvp;
304 	pid_t ppid = 1;
305 
306 	while ((ch = getopt(argc, argv, "a:dl:f:m:p:suv")) != -1)
307 		switch(ch) {
308 		case 'd':		/* debug */
309 			Debug++;
310 			break;
311 		case 'a':		/* allow specific network addresses only */
312 			if (allowaddr(optarg) == -1)
313 				usage();
314 			break;
315 		case 'f':		/* configuration file */
316 			ConfFile = optarg;
317 			break;
318 		case 'm':		/* mark interval */
319 			MarkInterval = atoi(optarg) * 60;
320 			break;
321 		case 'p':		/* path */
322 			funixn[0] = optarg;
323 			break;
324 		case 's':		/* no network mode */
325 			SecureMode++;
326 			break;
327 		case 'l':
328 			if (nfunix < MAXFUNIX)
329 				funixn[nfunix++] = optarg;
330 			else
331 				fprintf(stderr,
332 				   "syslogd: out of descriptors, ignoring %s\n",
333 					optarg);
334 			break;
335 		case 'u':		/* only log specified priority */
336 		        UniquePriority++;
337 			break;
338 		case 'v':		/* log facility and priority */
339 		  	LogFacPri++;
340 			break;
341 		case '?':
342 		default:
343 			usage();
344 		}
345 	if ((argc -= optind) != 0)
346 		usage();
347 
348 	if (!Debug) {
349 		ppid = waitdaemon(0, 0, 30);
350 		if (ppid < 0)
351 			err(1, "could not become daemon");
352 	} else
353 		setlinebuf(stdout);
354 
355 	if (NumAllowed)
356 		endservent();
357 
358 	consfile.f_type = F_CONSOLE;
359 	(void)strcpy(consfile.f_un.f_fname, ctty + sizeof _PATH_DEV - 1);
360 	(void)gethostname(LocalHostName, sizeof(LocalHostName));
361 	if ((p = strchr(LocalHostName, '.')) != NULL) {
362 		*p++ = '\0';
363 		LocalDomain = p;
364 	} else
365 		LocalDomain = "";
366 	(void)strcpy(bootfile, getbootfile());
367 	(void)signal(SIGTERM, die);
368 	(void)signal(SIGINT, Debug ? die : SIG_IGN);
369 	(void)signal(SIGQUIT, Debug ? die : SIG_IGN);
370 	(void)signal(SIGCHLD, reapchild);
371 	(void)signal(SIGALRM, domark);
372 	(void)signal(SIGPIPE, SIG_IGN);	/* We'll catch EPIPE instead. */
373 	(void)alarm(TIMERINTVL);
374 
375 	TAILQ_INIT(&deadq_head);
376 
377 #ifndef SUN_LEN
378 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
379 #endif
380 	for (i = 0; i < nfunix; i++) {
381 		memset(&sunx, 0, sizeof(sunx));
382 		sunx.sun_family = AF_UNIX;
383 		(void)strncpy(sunx.sun_path, funixn[i], sizeof(sunx.sun_path));
384 		funix[i] = socket(AF_UNIX, SOCK_DGRAM, 0);
385 		if (funix[i] < 0 ||
386 		    bind(funix[i], (struct sockaddr *)&sunx,
387 			 SUN_LEN(&sunx)) < 0 ||
388 		    chmod(funixn[i], 0666) < 0) {
389 			(void) snprintf(line, sizeof line,
390 					"cannot create %s", funixn[i]);
391 			logerror(line);
392 			dprintf("cannot create %s (%d)\n", funixn[i], errno);
393 			if (i == 0)
394 				die(0);
395 		}
396 	}
397 	finet = socket(AF_INET, SOCK_DGRAM, 0);
398 	if (finet >= 0) {
399 		struct servent *sp;
400 
401 		sp = getservbyname("syslog", "udp");
402 		if (sp == NULL) {
403 			errno = 0;
404 			logerror("syslog/udp: unknown service");
405 			die(0);
406 		}
407 		memset(&sin, 0, sizeof(sin));
408 		sin.sin_family = AF_INET;
409 		sin.sin_port = LogPort = sp->s_port;
410 
411 		if (bind(finet, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
412 			logerror("bind");
413 			if (!Debug)
414 				die(0);
415 		}
416 	}
417 
418 	if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) < 0)
419 		dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
420 
421 	/* tuck my process id away */
422 	fp = fopen(PidFile, "w");
423 	if (fp != NULL) {
424 		fprintf(fp, "%d\n", getpid());
425 		(void) fclose(fp);
426 	}
427 
428 	dprintf("off & running....\n");
429 
430 	init(0);
431 	(void)signal(SIGHUP, init);
432 
433 	tvp = &tv;
434 	tv.tv_sec = tv.tv_usec = 0;
435 
436 	for (;;) {
437 		fd_set readfds;
438 		int nfds = 0;
439 
440 		FD_ZERO(&readfds);
441 		if (fklog != -1) {
442 			FD_SET(fklog, &readfds);
443 			if (fklog > nfds)
444 				nfds = fklog;
445 		}
446 		if (finet != -1) {
447 			FD_SET(finet, &readfds);
448 			if (finet > nfds)
449 				nfds = finet;
450 		}
451 		for (i = 0; i < nfunix; i++) {
452 			if (funix[i] != -1) {
453 				FD_SET(funix[i], &readfds);
454 				if (funix[i] > nfds)
455 					nfds = funix[i];
456 			}
457 		}
458 
459 		/*dprintf("readfds = %#x\n", readfds);*/
460 		nfds = select(nfds+1, &readfds, (fd_set *)NULL,
461 			      (fd_set *)NULL, tvp);
462 		if (nfds == 0) {
463 			if (tvp) {
464 				tvp = NULL;
465 				if (ppid != 1)
466 					kill(ppid, SIGALRM);
467 			}
468 			continue;
469 		}
470 		if (nfds < 0) {
471 			if (errno != EINTR)
472 				logerror("select");
473 			continue;
474 		}
475 		/*dprintf("got a message (%d, %#x)\n", nfds, readfds);*/
476 		if (fklog != -1 && FD_ISSET(fklog, &readfds)) {
477 			i = read(fklog, line, MAXLINE - 1);
478 			if (i > 0) {
479 				line[i] = '\0';
480 				printsys(line);
481 			} else if (i < 0 && errno != EINTR) {
482 				logerror("klog");
483 				fklog = -1;
484 			}
485 		}
486 		if (finet != -1 && FD_ISSET(finet, &readfds)) {
487 			len = sizeof(frominet);
488 			l = recvfrom(finet, line, MAXLINE, 0,
489 			    (struct sockaddr *)&frominet, &len);
490 			if (SecureMode) {
491 				Vogons++;
492 				if (!(Vogons & (Vogons - 1))) {
493 					(void)snprintf(line, sizeof line,
494 "syslogd: discarded %d unwanted packets in secure mode, last from %s", Vogons,
495 						inet_ntoa(frominet.sin_addr));
496 					logmsg(LOG_SYSLOG|LOG_AUTH, line,
497 					    LocalHostName, ADDDATE);
498 				}
499 			} else if (l > 0) {
500 				line[l] = '\0';
501 				hname = cvthname(&frominet);
502 				if (validate(&frominet, hname))
503 					printline(hname, line);
504 			} else if (l < 0 && errno != EINTR)
505 				logerror("recvfrom inet");
506 		}
507 		for (i = 0; i < nfunix; i++) {
508 			if (funix[i] != -1 && FD_ISSET(funix[i], &readfds)) {
509 				len = sizeof(fromunix);
510 				l = recvfrom(funix[i], line, MAXLINE, 0,
511 				    (struct sockaddr *)&fromunix, &len);
512 				if (l > 0) {
513 					line[l] = '\0';
514 					printline(LocalHostName, line);
515 				} else if (l < 0 && errno != EINTR)
516 					logerror("recvfrom unix");
517 			}
518 		}
519 	}
520 }
521 
522 static void
523 usage()
524 {
525 
526 	fprintf(stderr, "%s\n%s\n%s\n",
527 		"usage: syslogd [-dsuv] [-a allowed_peer] [-f config_file]",
528 		"               [-m mark_interval] [-p log_socket]",
529 		"               [-l log_socket]");
530 	exit(1);
531 }
532 
533 /*
534  * Take a raw input line, decode the message, and print the message
535  * on the appropriate log files.
536  */
537 void
538 printline(hname, msg)
539 	char *hname;
540 	char *msg;
541 {
542 	int c, pri;
543 	char *p, *q, line[MAXLINE + 1];
544 
545 	/* test for special codes */
546 	pri = DEFUPRI;
547 	p = msg;
548 	if (*p == '<') {
549 		pri = 0;
550 		while (isdigit(*++p))
551 			pri = 10 * pri + (*p - '0');
552 		if (*p == '>')
553 			++p;
554 	}
555 	if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
556 		pri = DEFUPRI;
557 
558 	/* don't allow users to log kernel messages */
559 	if (LOG_FAC(pri) == LOG_KERN)
560 		pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
561 
562 	q = line;
563 
564 	while ((c = *p++ & 0177) != '\0' &&
565 	    q < &line[sizeof(line) - 1])
566 		if (iscntrl(c))
567 			if (c == '\n')
568 				*q++ = ' ';
569 			else if (c == '\t')
570 				*q++ = '\t';
571 			else {
572 				*q++ = '^';
573 				*q++ = c ^ 0100;
574 			}
575 		else
576 			*q++ = c;
577 	*q = '\0';
578 
579 	logmsg(pri, line, hname, 0);
580 }
581 
582 /*
583  * Take a raw input line from /dev/klog, split and format similar to syslog().
584  */
585 void
586 printsys(msg)
587 	char *msg;
588 {
589 	int pri, flags;
590 	char *p, *q;
591 
592 	for (p = msg; *p != '\0'; ) {
593 		flags = ISKERNEL | SYNC_FILE | ADDDATE;	/* fsync after write */
594 		pri = DEFSPRI;
595 		if (*p == '<') {
596 			pri = 0;
597 			while (isdigit(*++p))
598 				pri = 10 * pri + (*p - '0');
599 			if (*p == '>')
600 				++p;
601 		} else {
602 			/* kernel printf's come out on console */
603 			flags |= IGN_CONS;
604 		}
605 		if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
606 			pri = DEFSPRI;
607 		for (q = p; *q != '\0' && *q != '\n'; q++);
608 		if (*q != '\0')
609 			*q++ = '\0';
610 		logmsg(pri, p, LocalHostName, flags);
611 		p = q;
612 	}
613 }
614 
615 time_t	now;
616 
617 /*
618  * Log a message to the appropriate log files, users, etc. based on
619  * the priority.
620  */
621 void
622 logmsg(pri, msg, from, flags)
623 	int pri;
624 	char *msg, *from;
625 	int flags;
626 {
627 	struct filed *f;
628 	int i, fac, msglen, omask, prilev;
629 	char *timestamp;
630  	char prog[NAME_MAX+1];
631 	char buf[MAXLINE+1];
632 
633 	dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
634 	    pri, flags, from, msg);
635 
636 	omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
637 
638 	/*
639 	 * Check to see if msg looks non-standard.
640 	 */
641 	msglen = strlen(msg);
642 	if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
643 	    msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
644 		flags |= ADDDATE;
645 
646 	(void)time(&now);
647 	if (flags & ADDDATE)
648 		timestamp = ctime(&now) + 4;
649 	else {
650 		timestamp = msg;
651 		msg += 16;
652 		msglen -= 16;
653 	}
654 
655 	/* skip leading blanks */
656 	while(isspace(*msg)) {
657 		msg++;
658 		msglen--;
659 	}
660 
661 	/* extract facility and priority level */
662 	if (flags & MARK)
663 		fac = LOG_NFACILITIES;
664 	else
665 		fac = LOG_FAC(pri);
666 	prilev = LOG_PRI(pri);
667 
668 	/* extract program name */
669 	for(i = 0; i < NAME_MAX; i++) {
670 		if(!isalnum(msg[i]))
671 			break;
672 		prog[i] = msg[i];
673 	}
674 	prog[i] = 0;
675 
676 	/* add kernel prefix for kernel messages */
677 	if (flags & ISKERNEL) {
678 		snprintf(buf, sizeof(buf), "%s: %s", bootfile, msg);
679 		msg = buf;
680 		msglen = strlen(buf);
681 	}
682 
683 	/* log the message to the particular outputs */
684 	if (!Initialized) {
685 		f = &consfile;
686 		f->f_file = open(ctty, O_WRONLY, 0);
687 
688 		if (f->f_file >= 0) {
689 			fprintlog(f, flags, msg);
690 			(void)close(f->f_file);
691 		}
692 		(void)sigsetmask(omask);
693 		return;
694 	}
695 	for (f = Files; f; f = f->f_next) {
696 		/* skip messages that are incorrect priority */
697 		if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
698 		     ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
699 		     ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
700 		     )
701 		    || f->f_pmask[fac] == INTERNAL_NOPRI)
702 			continue;
703 		/* skip messages with the incorrect program name */
704 		if(f->f_program)
705 			if(strcmp(prog, f->f_program) != 0)
706 				continue;
707 
708 		if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
709 			continue;
710 
711 		/* don't output marks to recently written files */
712 		if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
713 			continue;
714 
715 		/*
716 		 * suppress duplicate lines to this file
717 		 */
718 		if ((flags & MARK) == 0 && msglen == f->f_prevlen &&
719 		    !strcmp(msg, f->f_prevline) &&
720 		    !strcmp(from, f->f_prevhost)) {
721 			(void)strncpy(f->f_lasttime, timestamp, 15);
722 			f->f_prevcount++;
723 			dprintf("msg repeated %d times, %ld sec of %d\n",
724 			    f->f_prevcount, (long)(now - f->f_time),
725 			    repeatinterval[f->f_repeatcount]);
726 			/*
727 			 * If domark would have logged this by now,
728 			 * flush it now (so we don't hold isolated messages),
729 			 * but back off so we'll flush less often
730 			 * in the future.
731 			 */
732 			if (now > REPEATTIME(f)) {
733 				fprintlog(f, flags, (char *)NULL);
734 				BACKOFF(f);
735 			}
736 		} else {
737 			/* new line, save it */
738 			if (f->f_prevcount)
739 				fprintlog(f, 0, (char *)NULL);
740 			f->f_repeatcount = 0;
741 			f->f_prevpri = pri;
742 			(void)strncpy(f->f_lasttime, timestamp, 15);
743 			(void)strncpy(f->f_prevhost, from,
744 					sizeof(f->f_prevhost));
745 			if (msglen < MAXSVLINE) {
746 				f->f_prevlen = msglen;
747 				(void)strcpy(f->f_prevline, msg);
748 				fprintlog(f, flags, (char *)NULL);
749 			} else {
750 				f->f_prevline[0] = 0;
751 				f->f_prevlen = 0;
752 				fprintlog(f, flags, msg);
753 			}
754 		}
755 	}
756 	(void)sigsetmask(omask);
757 }
758 
759 void
760 fprintlog(f, flags, msg)
761 	struct filed *f;
762 	int flags;
763 	char *msg;
764 {
765 	struct iovec iov[7];
766 	struct iovec *v;
767 	int l;
768 	char line[MAXLINE + 1], repbuf[80], greetings[200];
769 	char *msgret;
770 
771 	v = iov;
772 	if (f->f_type == F_WALL) {
773 		v->iov_base = greetings;
774 		v->iov_len = snprintf(greetings, sizeof greetings,
775 		    "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
776 		    f->f_prevhost, ctime(&now));
777 		v++;
778 		v->iov_base = "";
779 		v->iov_len = 0;
780 		v++;
781 	} else {
782 		v->iov_base = f->f_lasttime;
783 		v->iov_len = 15;
784 		v++;
785 		v->iov_base = " ";
786 		v->iov_len = 1;
787 		v++;
788 	}
789 
790 	if (LogFacPri) {
791 	  	static char fp_buf[30];	/* Hollow laugh */
792 		int fac = f->f_prevpri & LOG_FACMASK;
793 		int pri = LOG_PRI(f->f_prevpri);
794 		char *f_s = 0;
795 		char f_n[5];	/* Hollow laugh */
796 		char *p_s = 0;
797 		char p_n[5];	/* Hollow laugh */
798 
799 		if (LogFacPri > 1) {
800 		  CODE *c;
801 
802 		  for (c = facilitynames; c; c++) {
803 		    if (c->c_val == fac) {
804 		      f_s = c->c_name;
805 		      break;
806 		    }
807 		  }
808 		  for (c = prioritynames; c; c++) {
809 		    if (c->c_val == pri) {
810 		      p_s = c->c_name;
811 		      break;
812 		    }
813 		  }
814 		}
815 		if (!f_s) {
816 		  snprintf(f_n, sizeof f_n, "%d", LOG_FAC(fac));
817 		  f_s = f_n;
818 		}
819 		if (!p_s) {
820 		  snprintf(p_n, sizeof p_n, "%d", pri);
821 		  p_s = p_n;
822 		}
823 		snprintf(fp_buf, sizeof fp_buf, "<%s.%s> ", f_s, p_s);
824 		v->iov_base = fp_buf;
825 		v->iov_len = strlen(fp_buf);
826 	} else {
827 	        v->iov_base="";
828 		v->iov_len = 0;
829 	}
830 	v++;
831 
832 	v->iov_base = f->f_prevhost;
833 	v->iov_len = strlen(v->iov_base);
834 	v++;
835 	v->iov_base = " ";
836 	v->iov_len = 1;
837 	v++;
838 
839 	if (msg) {
840 		v->iov_base = msg;
841 		v->iov_len = strlen(msg);
842 	} else if (f->f_prevcount > 1) {
843 		v->iov_base = repbuf;
844 		v->iov_len = sprintf(repbuf, "last message repeated %d times",
845 		    f->f_prevcount);
846 	} else {
847 		v->iov_base = f->f_prevline;
848 		v->iov_len = f->f_prevlen;
849 	}
850 	v++;
851 
852 	dprintf("Logging to %s", TypeNames[f->f_type]);
853 	f->f_time = now;
854 
855 	switch (f->f_type) {
856 	case F_UNUSED:
857 		dprintf("\n");
858 		break;
859 
860 	case F_FORW:
861 		dprintf(" %s\n", f->f_un.f_forw.f_hname);
862 		/* check for local vs remote messages */
863 		if (strcmp(f->f_prevhost, LocalHostName))
864 			l = snprintf(line, sizeof line - 1,
865 			    "<%d>%.15s Forwarded from %s: %s",
866 			    f->f_prevpri, iov[0].iov_base, f->f_prevhost,
867 			    iov[5].iov_base);
868 		else
869 			l = snprintf(line, sizeof line - 1, "<%d>%.15s %s",
870 			     f->f_prevpri, iov[0].iov_base, iov[5].iov_base);
871 		if (l > MAXLINE)
872 			l = MAXLINE;
873 		if ((finet >= 0) &&
874 		     (sendto(finet, line, l, 0,
875 			     (struct sockaddr *)&f->f_un.f_forw.f_addr,
876 			     sizeof(f->f_un.f_forw.f_addr)) != l)) {
877 			int e = errno;
878 			(void)close(f->f_file);
879 			f->f_type = F_UNUSED;
880 			errno = e;
881 			logerror("sendto");
882 		}
883 		break;
884 
885 	case F_FILE:
886 		dprintf(" %s\n", f->f_un.f_fname);
887 		v->iov_base = "\n";
888 		v->iov_len = 1;
889 		if (writev(f->f_file, iov, 7) < 0) {
890 			int e = errno;
891 			(void)close(f->f_file);
892 			f->f_type = F_UNUSED;
893 			errno = e;
894 			logerror(f->f_un.f_fname);
895 		} else if (flags & SYNC_FILE)
896 			(void)fsync(f->f_file);
897 		break;
898 
899 	case F_PIPE:
900 		dprintf(" %s\n", f->f_un.f_pipe.f_pname);
901 		v->iov_base = "\n";
902 		v->iov_len = 1;
903 		if (f->f_un.f_pipe.f_pid == 0) {
904 			if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
905 						&f->f_un.f_pipe.f_pid)) < 0) {
906 				f->f_type = F_UNUSED;
907 				logerror(f->f_un.f_pipe.f_pname);
908 				break;
909 			}
910 		}
911 		if (writev(f->f_file, iov, 7) < 0) {
912 			int e = errno;
913 			(void)close(f->f_file);
914 			if (f->f_un.f_pipe.f_pid > 0)
915 				deadq_enter(f->f_un.f_pipe.f_pid);
916 			f->f_un.f_pipe.f_pid = 0;
917 			errno = e;
918 			logerror(f->f_un.f_pipe.f_pname);
919 		}
920 		break;
921 
922 	case F_CONSOLE:
923 		if (flags & IGN_CONS) {
924 			dprintf(" (ignored)\n");
925 			break;
926 		}
927 		/* FALLTHROUGH */
928 
929 	case F_TTY:
930 		dprintf(" %s%s\n", _PATH_DEV, f->f_un.f_fname);
931 		v->iov_base = "\r\n";
932 		v->iov_len = 2;
933 
934 		errno = 0;	/* ttymsg() only sometimes returns an errno */
935 		if ((msgret = ttymsg(iov, 7, f->f_un.f_fname, 10))) {
936 			f->f_type = F_UNUSED;
937 			logerror(msgret);
938 		}
939 		break;
940 
941 	case F_USERS:
942 	case F_WALL:
943 		dprintf("\n");
944 		v->iov_base = "\r\n";
945 		v->iov_len = 2;
946 		wallmsg(f, iov);
947 		break;
948 	}
949 	f->f_prevcount = 0;
950 }
951 
952 /*
953  *  WALLMSG -- Write a message to the world at large
954  *
955  *	Write the specified message to either the entire
956  *	world, or a list of approved users.
957  */
958 void
959 wallmsg(f, iov)
960 	struct filed *f;
961 	struct iovec *iov;
962 {
963 	static int reenter;			/* avoid calling ourselves */
964 	FILE *uf;
965 	struct utmp ut;
966 	int i;
967 	char *p;
968 	char line[sizeof(ut.ut_line) + 1];
969 
970 	if (reenter++)
971 		return;
972 	if ((uf = fopen(_PATH_UTMP, "r")) == NULL) {
973 		logerror(_PATH_UTMP);
974 		reenter = 0;
975 		return;
976 	}
977 	/* NOSTRICT */
978 	while (fread((char *)&ut, sizeof(ut), 1, uf) == 1) {
979 		if (ut.ut_name[0] == '\0')
980 			continue;
981 		strncpy(line, ut.ut_line, sizeof(ut.ut_line));
982 		line[sizeof(ut.ut_line)] = '\0';
983 		if (f->f_type == F_WALL) {
984 			if ((p = ttymsg(iov, 7, line, TTYMSGTIME)) != NULL) {
985 				errno = 0;	/* already in msg */
986 				logerror(p);
987 			}
988 			continue;
989 		}
990 		/* should we send the message to this user? */
991 		for (i = 0; i < MAXUNAMES; i++) {
992 			if (!f->f_un.f_uname[i][0])
993 				break;
994 			if (!strncmp(f->f_un.f_uname[i], ut.ut_name,
995 			    UT_NAMESIZE)) {
996 				if ((p = ttymsg(iov, 7, line, TTYMSGTIME))
997 								!= NULL) {
998 					errno = 0;	/* already in msg */
999 					logerror(p);
1000 				}
1001 				break;
1002 			}
1003 		}
1004 	}
1005 	(void)fclose(uf);
1006 	reenter = 0;
1007 }
1008 
1009 void
1010 reapchild(signo)
1011 	int signo;
1012 {
1013 	int status, code;
1014 	pid_t pid;
1015 	struct filed *f;
1016 	char buf[256];
1017 	const char *reason;
1018 	dq_t q;
1019 
1020 	while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
1021 		if (!Initialized)
1022 			/* Don't tell while we are initting. */
1023 			continue;
1024 
1025 		/* First, look if it's a process from the dead queue. */
1026 		for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = TAILQ_NEXT(q, dq_entries))
1027 			if (q->dq_pid == pid) {
1028 				TAILQ_REMOVE(&deadq_head, q, dq_entries);
1029 				free(q);
1030 				goto oncemore;
1031 			}
1032 
1033 		/* Now, look in list of active processes. */
1034 		for (f = Files; f; f = f->f_next)
1035 			if (f->f_type == F_PIPE &&
1036 			    f->f_un.f_pipe.f_pid == pid) {
1037 				(void)close(f->f_file);
1038 
1039 				errno = 0; /* Keep strerror() stuff out of logerror messages. */
1040 				f->f_un.f_pipe.f_pid = 0;
1041 				if (WIFSIGNALED(status)) {
1042 					reason = "due to signal";
1043 					code = WTERMSIG(status);
1044 				} else {
1045 					reason = "with status";
1046 					code = WEXITSTATUS(status);
1047 					if (code == 0)
1048 						goto oncemore; /* Exited OK. */
1049 				}
1050 				(void)snprintf(buf, sizeof buf,
1051 				"Logging subprocess %d (%s) exited %s %d.",
1052 					       pid, f->f_un.f_pipe.f_pname,
1053 					       reason, code);
1054 				logerror(buf);
1055 				break;
1056 			}
1057 	  oncemore:
1058 	}
1059 }
1060 
1061 /*
1062  * Return a printable representation of a host address.
1063  */
1064 char *
1065 cvthname(f)
1066 	struct sockaddr_in *f;
1067 {
1068 	struct hostent *hp;
1069 	sigset_t omask, nmask;
1070 	char *p;
1071 
1072 	dprintf("cvthname(%s)\n", inet_ntoa(f->sin_addr));
1073 
1074 	if (f->sin_family != AF_INET) {
1075 		dprintf("Malformed from address\n");
1076 		return ("???");
1077 	}
1078 	sigemptyset(&nmask);
1079 	sigaddset(&nmask, SIGHUP);
1080 	sigprocmask(SIG_BLOCK, &nmask, &omask);
1081 	hp = gethostbyaddr((char *)&f->sin_addr,
1082 	    sizeof(struct in_addr), f->sin_family);
1083 	sigprocmask(SIG_SETMASK, &omask, NULL);
1084 	if (hp == 0) {
1085 		dprintf("Host name for your address (%s) unknown\n",
1086 			inet_ntoa(f->sin_addr));
1087 		return (inet_ntoa(f->sin_addr));
1088 	}
1089 	if ((p = strchr(hp->h_name, '.')) && strcmp(p + 1, LocalDomain) == 0)
1090 		*p = '\0';
1091 	return (hp->h_name);
1092 }
1093 
1094 void
1095 domark(signo)
1096 	int signo;
1097 {
1098 	struct filed *f;
1099 	dq_t q;
1100 
1101 	now = time((time_t *)NULL);
1102 	MarkSeq += TIMERINTVL;
1103 	if (MarkSeq >= MarkInterval) {
1104 		logmsg(LOG_INFO, "-- MARK --", LocalHostName, ADDDATE|MARK);
1105 		MarkSeq = 0;
1106 	}
1107 
1108 	for (f = Files; f; f = f->f_next) {
1109 		if (f->f_prevcount && now >= REPEATTIME(f)) {
1110 			dprintf("flush %s: repeated %d times, %d sec.\n",
1111 			    TypeNames[f->f_type], f->f_prevcount,
1112 			    repeatinterval[f->f_repeatcount]);
1113 			fprintlog(f, 0, (char *)NULL);
1114 			BACKOFF(f);
1115 		}
1116 	}
1117 
1118 	/* Walk the dead queue, and see if we should signal somebody. */
1119 	for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = TAILQ_NEXT(q, dq_entries))
1120 		switch (q->dq_timeout) {
1121 		case 0:
1122 			/* Already signalled once, try harder now. */
1123 			kill(q->dq_pid, SIGKILL);
1124 			break;
1125 
1126 		case 1:
1127 			/*
1128 			 * Timed out on dead queue, send terminate
1129 			 * signal.  Note that we leave the removal
1130 			 * from the dead queue to reapchild(), which
1131 			 * will also log the event.
1132 			 */
1133 			kill(q->dq_pid, SIGTERM);
1134 			/* FALLTROUGH */
1135 
1136 		default:
1137 			q->dq_timeout--;
1138 		}
1139 
1140 	(void)alarm(TIMERINTVL);
1141 }
1142 
1143 /*
1144  * Print syslogd errors some place.
1145  */
1146 void
1147 logerror(type)
1148 	const char *type;
1149 {
1150 	char buf[512];
1151 
1152 	if (errno)
1153 		(void)snprintf(buf,
1154 		    sizeof buf, "syslogd: %s: %s", type, strerror(errno));
1155 	else
1156 		(void)snprintf(buf, sizeof buf, "syslogd: %s", type);
1157 	errno = 0;
1158 	dprintf("%s\n", buf);
1159 	logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1160 }
1161 
1162 void
1163 die(signo)
1164 	int signo;
1165 {
1166 	struct filed *f;
1167 	int was_initialized;
1168 	char buf[100];
1169 	int i;
1170 
1171 	was_initialized = Initialized;
1172 	Initialized = 0;	/* Don't log SIGCHLDs. */
1173 	for (f = Files; f != NULL; f = f->f_next) {
1174 		/* flush any pending output */
1175 		if (f->f_prevcount)
1176 			fprintlog(f, 0, (char *)NULL);
1177 		if (f->f_type == F_PIPE)
1178 			(void)close(f->f_file);
1179 	}
1180 	Initialized = was_initialized;
1181 	if (signo) {
1182 		dprintf("syslogd: exiting on signal %d\n", signo);
1183 		(void)sprintf(buf, "exiting on signal %d", signo);
1184 		errno = 0;
1185 		logerror(buf);
1186 	}
1187 	for (i = 0; i < nfunix; i++)
1188 		if (funixn[i] && funix[i] != -1)
1189 			(void)unlink(funixn[i]);
1190 	exit(1);
1191 }
1192 
1193 /*
1194  *  INIT -- Initialize syslogd from configuration table
1195  */
1196 void
1197 init(signo)
1198 	int signo;
1199 {
1200 	int i;
1201 	FILE *cf;
1202 	struct filed *f, *next, **nextp;
1203 	char *p;
1204 	char cline[LINE_MAX];
1205  	char prog[NAME_MAX+1];
1206 
1207 	dprintf("init\n");
1208 
1209 	/*
1210 	 *  Close all open log files.
1211 	 */
1212 	Initialized = 0;
1213 	for (f = Files; f != NULL; f = next) {
1214 		/* flush any pending output */
1215 		if (f->f_prevcount)
1216 			fprintlog(f, 0, (char *)NULL);
1217 
1218 		switch (f->f_type) {
1219 		case F_FILE:
1220 		case F_FORW:
1221 		case F_CONSOLE:
1222 		case F_TTY:
1223 			(void)close(f->f_file);
1224 			break;
1225 		case F_PIPE:
1226 			(void)close(f->f_file);
1227 			if (f->f_un.f_pipe.f_pid > 0)
1228 				deadq_enter(f->f_un.f_pipe.f_pid);
1229 			f->f_un.f_pipe.f_pid = 0;
1230 			break;
1231 		}
1232 		next = f->f_next;
1233 		if(f->f_program) free(f->f_program);
1234 		free((char *)f);
1235 	}
1236 	Files = NULL;
1237 	nextp = &Files;
1238 
1239 	/* open the configuration file */
1240 	if ((cf = fopen(ConfFile, "r")) == NULL) {
1241 		dprintf("cannot open %s\n", ConfFile);
1242 		*nextp = (struct filed *)calloc(1, sizeof(*f));
1243 		cfline("*.ERR\t/dev/console", *nextp, "*");
1244 		(*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1245 		cfline("*.PANIC\t*", (*nextp)->f_next, "*");
1246 		Initialized = 1;
1247 		return;
1248 	}
1249 
1250 	/*
1251 	 *  Foreach line in the conf table, open that file.
1252 	 */
1253 	f = NULL;
1254 	strcpy(prog, "*");
1255 	while (fgets(cline, sizeof(cline), cf) != NULL) {
1256 		/*
1257 		 * check for end-of-section, comments, strip off trailing
1258 		 * spaces and newline character. #!prog is treated specially:
1259 		 * following lines apply only to that program.
1260 		 */
1261 		for (p = cline; isspace(*p); ++p)
1262 			continue;
1263 		if (*p == 0)
1264 			continue;
1265 		if(*p == '#') {
1266 			p++;
1267 			if(*p!='!')
1268 				continue;
1269 		}
1270 		if(*p=='!') {
1271 			p++;
1272 			while(isspace(*p)) p++;
1273 			if(!*p) {
1274 				strcpy(prog, "*");
1275 				continue;
1276 			}
1277 			for(i = 0; i < NAME_MAX; i++) {
1278 				if(!isalnum(p[i]))
1279 					break;
1280 				prog[i] = p[i];
1281 			}
1282 			prog[i] = 0;
1283 			continue;
1284 		}
1285 		for (p = strchr(cline, '\0'); isspace(*--p);)
1286 			continue;
1287 		*++p = '\0';
1288 		f = (struct filed *)calloc(1, sizeof(*f));
1289 		*nextp = f;
1290 		nextp = &f->f_next;
1291 		cfline(cline, f, prog);
1292 	}
1293 
1294 	/* close the configuration file */
1295 	(void)fclose(cf);
1296 
1297 	Initialized = 1;
1298 
1299 	if (Debug) {
1300 		for (f = Files; f; f = f->f_next) {
1301 			for (i = 0; i <= LOG_NFACILITIES; i++)
1302 				if (f->f_pmask[i] == INTERNAL_NOPRI)
1303 					printf("X ");
1304 				else
1305 					printf("%d ", f->f_pmask[i]);
1306 			printf("%s: ", TypeNames[f->f_type]);
1307 			switch (f->f_type) {
1308 			case F_FILE:
1309 				printf("%s", f->f_un.f_fname);
1310 				break;
1311 
1312 			case F_CONSOLE:
1313 			case F_TTY:
1314 				printf("%s%s", _PATH_DEV, f->f_un.f_fname);
1315 				break;
1316 
1317 			case F_FORW:
1318 				printf("%s", f->f_un.f_forw.f_hname);
1319 				break;
1320 
1321 			case F_PIPE:
1322 				printf("%s", f->f_un.f_pipe.f_pname);
1323 				break;
1324 
1325 			case F_USERS:
1326 				for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1327 					printf("%s, ", f->f_un.f_uname[i]);
1328 				break;
1329 			}
1330 			if(f->f_program) {
1331 				printf(" (%s)", f->f_program);
1332 			}
1333 			printf("\n");
1334 		}
1335 	}
1336 
1337 	logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1338 	dprintf("syslogd: restarted\n");
1339 }
1340 
1341 /*
1342  * Crack a configuration file line
1343  */
1344 void
1345 cfline(line, f, prog)
1346 	char *line;
1347 	struct filed *f;
1348 	char *prog;
1349 {
1350 	struct hostent *hp;
1351 	int i, pri;
1352 	char *bp, *p, *q;
1353 	char buf[MAXLINE], ebuf[100];
1354 
1355 	dprintf("cfline(\"%s\", f, \"%s\")\n", line, prog);
1356 
1357 	errno = 0;	/* keep strerror() stuff out of logerror messages */
1358 
1359 	/* clear out file entry */
1360 	memset(f, 0, sizeof(*f));
1361 	for (i = 0; i <= LOG_NFACILITIES; i++)
1362 		f->f_pmask[i] = INTERNAL_NOPRI;
1363 
1364 	/* save program name if any */
1365 	if(prog && *prog=='*') prog = NULL;
1366 	if(prog) {
1367 		f->f_program = calloc(1, strlen(prog)+1);
1368 		if(f->f_program) {
1369 			strcpy(f->f_program, prog);
1370 		}
1371 	}
1372 
1373 	/* scan through the list of selectors */
1374 	for (p = line; *p && *p != '\t' && *p != ' ';) {
1375 		int pri_done;
1376 		int pri_cmp;
1377 
1378 		/* find the end of this facility name list */
1379 		for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
1380 			continue;
1381 
1382 		/* get the priority comparison */
1383 		pri_cmp = 0;
1384 		pri_done = 0;
1385 		while (!pri_done) {
1386 			switch (*q) {
1387 			case '<':
1388 				pri_cmp |= PRI_LT;
1389 				q++;
1390 				break;
1391 			case '=':
1392 				pri_cmp |= PRI_EQ;
1393 				q++;
1394 				break;
1395 			case '>':
1396 				pri_cmp |= PRI_GT;
1397 				q++;
1398 				break;
1399 			default:
1400 				pri_done++;
1401 				break;
1402 			}
1403 		}
1404 		if (!pri_cmp)
1405 			pri_cmp = (UniquePriority)
1406 				  ? (PRI_EQ)
1407 				  : (PRI_EQ | PRI_GT)
1408 				  ;
1409 
1410 		/* collect priority name */
1411 		for (bp = buf; *q && !strchr("\t,; ", *q); )
1412 			*bp++ = *q++;
1413 		*bp = '\0';
1414 
1415 		/* skip cruft */
1416 		while (strchr(",;", *q))
1417 			q++;
1418 
1419 		/* decode priority name */
1420 		if (*buf == '*')
1421 			pri = LOG_PRIMASK + 1;
1422 		else {
1423 			pri = decode(buf, prioritynames);
1424 			if (pri < 0) {
1425 				(void)snprintf(ebuf, sizeof ebuf,
1426 				    "unknown priority name \"%s\"", buf);
1427 				logerror(ebuf);
1428 				return;
1429 			}
1430 		}
1431 
1432 		/* scan facilities */
1433 		while (*p && !strchr("\t.; ", *p)) {
1434 			for (bp = buf; *p && !strchr("\t,;. ", *p); )
1435 				*bp++ = *p++;
1436 			*bp = '\0';
1437 
1438 			if (*buf == '*')
1439 				for (i = 0; i < LOG_NFACILITIES; i++) {
1440 					f->f_pmask[i] = pri;
1441 					f->f_pcmp[i] = pri_cmp;
1442 				}
1443 			else {
1444 				i = decode(buf, facilitynames);
1445 				if (i < 0) {
1446 					(void)snprintf(ebuf, sizeof ebuf,
1447 					    "unknown facility name \"%s\"",
1448 					    buf);
1449 					logerror(ebuf);
1450 					return;
1451 				}
1452 				f->f_pmask[i >> 3] = pri;
1453 				f->f_pcmp[i >> 3] = pri_cmp;
1454 			}
1455 			while (*p == ',' || *p == ' ')
1456 				p++;
1457 		}
1458 
1459 		p = q;
1460 	}
1461 
1462 	/* skip to action part */
1463 	while (*p == '\t' || *p == ' ')
1464 		p++;
1465 
1466 	switch (*p)
1467 	{
1468 	case '@':
1469 		(void)strcpy(f->f_un.f_forw.f_hname, ++p);
1470 		hp = gethostbyname(p);
1471 		if (hp == NULL) {
1472 			extern int h_errno;
1473 
1474 			logerror(hstrerror(h_errno));
1475 			break;
1476 		}
1477 		memset(&f->f_un.f_forw.f_addr, 0,
1478 			 sizeof(f->f_un.f_forw.f_addr));
1479 		f->f_un.f_forw.f_addr.sin_family = AF_INET;
1480 		f->f_un.f_forw.f_addr.sin_port = LogPort;
1481 		memmove(&f->f_un.f_forw.f_addr.sin_addr, hp->h_addr, hp->h_length);
1482 		f->f_type = F_FORW;
1483 		break;
1484 
1485 	case '/':
1486 		if ((f->f_file = open(p, O_WRONLY|O_APPEND, 0)) < 0) {
1487 			f->f_type = F_UNUSED;
1488 			logerror(p);
1489 			break;
1490 		}
1491 		if (isatty(f->f_file)) {
1492 			if (strcmp(p, ctty) == 0)
1493 				f->f_type = F_CONSOLE;
1494 			else
1495 				f->f_type = F_TTY;
1496 			(void)strcpy(f->f_un.f_fname, p + sizeof _PATH_DEV - 1);
1497 		} else {
1498 			(void)strcpy(f->f_un.f_fname, p);
1499 			f->f_type = F_FILE;
1500 		}
1501 		break;
1502 
1503 	case '|':
1504 		f->f_un.f_pipe.f_pid = 0;
1505 		(void)strcpy(f->f_un.f_pipe.f_pname, p + 1);
1506 		f->f_type = F_PIPE;
1507 		break;
1508 
1509 	case '*':
1510 		f->f_type = F_WALL;
1511 		break;
1512 
1513 	default:
1514 		for (i = 0; i < MAXUNAMES && *p; i++) {
1515 			for (q = p; *q && *q != ','; )
1516 				q++;
1517 			(void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
1518 			if ((q - p) > UT_NAMESIZE)
1519 				f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
1520 			else
1521 				f->f_un.f_uname[i][q - p] = '\0';
1522 			while (*q == ',' || *q == ' ')
1523 				q++;
1524 			p = q;
1525 		}
1526 		f->f_type = F_USERS;
1527 		break;
1528 	}
1529 }
1530 
1531 
1532 /*
1533  *  Decode a symbolic name to a numeric value
1534  */
1535 int
1536 decode(name, codetab)
1537 	const char *name;
1538 	CODE *codetab;
1539 {
1540 	CODE *c;
1541 	char *p, buf[40];
1542 
1543 	if (isdigit(*name))
1544 		return (atoi(name));
1545 
1546 	for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
1547 		if (isupper(*name))
1548 			*p = tolower(*name);
1549 		else
1550 			*p = *name;
1551 	}
1552 	*p = '\0';
1553 	for (c = codetab; c->c_name; c++)
1554 		if (!strcmp(buf, c->c_name))
1555 			return (c->c_val);
1556 
1557 	return (-1);
1558 }
1559 
1560 /*
1561  * fork off and become a daemon, but wait for the child to come online
1562  * before returing to the parent, or we get disk thrashing at boot etc.
1563  * Set a timer so we don't hang forever if it wedges.
1564  */
1565 int
1566 waitdaemon(nochdir, noclose, maxwait)
1567 	int nochdir, noclose, maxwait;
1568 {
1569 	int fd;
1570 	int status;
1571 	pid_t pid, childpid;
1572 
1573 	switch (childpid = fork()) {
1574 	case -1:
1575 		return (-1);
1576 	case 0:
1577 		break;
1578 	default:
1579 		signal(SIGALRM, timedout);
1580 		alarm(maxwait);
1581 		while ((pid = wait3(&status, 0, NULL)) != -1) {
1582 			if (WIFEXITED(status))
1583 				errx(1, "child pid %d exited with return code %d",
1584 					pid, WEXITSTATUS(status));
1585 			if (WIFSIGNALED(status))
1586 				errx(1, "child pid %d exited on signal %d%s",
1587 					pid, WTERMSIG(status),
1588 					WCOREDUMP(status) ? " (core dumped)" :
1589 					"");
1590 			if (pid == childpid)	/* it's gone... */
1591 				break;
1592 		}
1593 		exit(0);
1594 	}
1595 
1596 	if (setsid() == -1)
1597 		return (-1);
1598 
1599 	if (!nochdir)
1600 		(void)chdir("/");
1601 
1602 	if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1603 		(void)dup2(fd, STDIN_FILENO);
1604 		(void)dup2(fd, STDOUT_FILENO);
1605 		(void)dup2(fd, STDERR_FILENO);
1606 		if (fd > 2)
1607 			(void)close (fd);
1608 	}
1609 	return (getppid());
1610 }
1611 
1612 /*
1613  * We get a SIGALRM from the child when it's running and finished doing it's
1614  * fsync()'s or O_SYNC writes for all the boot messages.
1615  *
1616  * We also get a signal from the kernel if the timer expires, so check to
1617  * see what happened.
1618  */
1619 void
1620 timedout(sig)
1621 	int sig __unused;
1622 {
1623 	int left;
1624 	left = alarm(0);
1625 	signal(SIGALRM, SIG_DFL);
1626 	if (left == 0)
1627 		errx(1, "timed out waiting for child");
1628 	else
1629 		exit(0);
1630 }
1631 
1632 /*
1633  * Add `s' to the list of allowable peer addresses to accept messages
1634  * from.
1635  *
1636  * `s' is a string in the form:
1637  *
1638  *    [*]domainname[:{servicename|portnumber|*}]
1639  *
1640  * or
1641  *
1642  *    netaddr/maskbits[:{servicename|portnumber|*}]
1643  *
1644  * Returns -1 on error, 0 if the argument was valid.
1645  */
1646 int
1647 allowaddr(s)
1648 	char *s;
1649 {
1650 	char *cp1, *cp2;
1651 	struct allowedpeer ap;
1652 	struct servent *se;
1653 	regex_t re;
1654 	int i;
1655 
1656 	if ((cp1 = strrchr(s, ':'))) {
1657 		/* service/port provided */
1658 		*cp1++ = '\0';
1659 		if (strlen(cp1) == 1 && *cp1 == '*')
1660 			/* any port allowed */
1661 			ap.port = htons(0);
1662 		else if ((se = getservbyname(cp1, "udp")))
1663 			ap.port = se->s_port;
1664 		else {
1665 			ap.port = htons((int)strtol(cp1, &cp2, 0));
1666 			if (*cp2 != '\0')
1667 				return -1; /* port not numeric */
1668 		}
1669 	} else {
1670 		if ((se = getservbyname("syslog", "udp")))
1671 			ap.port = se->s_port;
1672 		else
1673 			/* sanity, should not happen */
1674 			ap.port = htons(514);
1675 	}
1676 
1677 	/* the regexp's are ugly, but the cleanest way */
1678 
1679 	if (regcomp(&re, "^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+(/[0-9]+)?$",
1680 		    REG_EXTENDED))
1681 		/* if RE compilation fails, that's an internal error */
1682 		abort();
1683 	if (regexec(&re, s, 0, 0, 0) == 0) {
1684 		/* arg `s' is numeric */
1685 		ap.isnumeric = 1;
1686 		if ((cp1 = strchr(s, '/')) != NULL) {
1687 			*cp1++ = '\0';
1688 			i = atoi(cp1);
1689 			if (i < 0 || i > 32)
1690 				return -1;
1691 			/* convert masklen to netmask */
1692 			ap.a_mask.s_addr = htonl(~((1 << (32 - i)) - 1));
1693 		}
1694 		if (ascii2addr(AF_INET, s, &ap.a_addr) == -1)
1695 			return -1;
1696 		if (cp1 == NULL) {
1697 			/* use default netmask */
1698 			if (IN_CLASSA(ntohl(ap.a_addr.s_addr)))
1699 				ap.a_mask.s_addr = htonl(IN_CLASSA_NET);
1700 			else if (IN_CLASSB(ntohl(ap.a_addr.s_addr)))
1701 				ap.a_mask.s_addr = htonl(IN_CLASSB_NET);
1702 			else
1703 				ap.a_mask.s_addr = htonl(IN_CLASSC_NET);
1704 		}
1705 	} else {
1706 		/* arg `s' is domain name */
1707 		ap.isnumeric = 0;
1708 		ap.a_name = s;
1709 	}
1710 	regfree(&re);
1711 
1712 	if (Debug) {
1713 		printf("allowaddr: rule %d: ", NumAllowed);
1714 		if (ap.isnumeric) {
1715 			printf("numeric, ");
1716 			printf("addr = %s, ",
1717 			       addr2ascii(AF_INET, &ap.a_addr, sizeof(struct in_addr), 0));
1718 			printf("mask = %s; ",
1719 			       addr2ascii(AF_INET, &ap.a_mask, sizeof(struct in_addr), 0));
1720 		} else
1721 			printf("domainname = %s; ", ap.a_name);
1722 		printf("port = %d\n", ntohs(ap.port));
1723 	}
1724 
1725 	if ((AllowedPeers = realloc(AllowedPeers,
1726 				    ++NumAllowed * sizeof(struct allowedpeer)))
1727 	    == NULL) {
1728 		fprintf(stderr, "Out of memory!\n");
1729 		exit(EX_OSERR);
1730 	}
1731 	memcpy(&AllowedPeers[NumAllowed - 1], &ap, sizeof(struct allowedpeer));
1732 	return 0;
1733 }
1734 
1735 /*
1736  * Validate that the remote peer has permission to log to us.
1737  */
1738 int
1739 validate(sin, hname)
1740 	struct sockaddr_in *sin;
1741 	const char *hname;
1742 {
1743 	int i;
1744 	size_t l1, l2;
1745 	char *cp, name[MAXHOSTNAMELEN];
1746 	struct allowedpeer *ap;
1747 
1748 	if (NumAllowed == 0)
1749 		/* traditional behaviour, allow everything */
1750 		return 1;
1751 
1752 	strncpy(name, hname, sizeof name);
1753 	if (strchr(name, '.') == NULL) {
1754 		strncat(name, ".", sizeof name - strlen(name) - 1);
1755 		strncat(name, LocalDomain, sizeof name - strlen(name) - 1);
1756 	}
1757 	dprintf("validate: dgram from IP %s, port %d, name %s;\n",
1758 		addr2ascii(AF_INET, &sin->sin_addr, sizeof(struct in_addr), 0),
1759 		ntohs(sin->sin_port), name);
1760 
1761 	/* now, walk down the list */
1762 	for (i = 0, ap = AllowedPeers; i < NumAllowed; i++, ap++) {
1763 		if (ntohs(ap->port) != 0 && ap->port != sin->sin_port) {
1764 			dprintf("rejected in rule %d due to port mismatch.\n", i);
1765 			continue;
1766 		}
1767 
1768 		if (ap->isnumeric) {
1769 			if ((sin->sin_addr.s_addr & ap->a_mask.s_addr)
1770 			    != ap->a_addr.s_addr) {
1771 				dprintf("rejected in rule %d due to IP mismatch.\n", i);
1772 				continue;
1773 			}
1774 		} else {
1775 			cp = ap->a_name;
1776 			l1 = strlen(name);
1777 			if (*cp == '*') {
1778 				/* allow wildmatch */
1779 				cp++;
1780 				l2 = strlen(cp);
1781 				if (l2 > l1 || memcmp(cp, &name[l1 - l2], l2) != 0) {
1782 					dprintf("rejected in rule %d due to name mismatch.\n", i);
1783 					continue;
1784 				}
1785 			} else {
1786 				/* exact match */
1787 				l2 = strlen(cp);
1788 				if (l2 != l1 || memcmp(cp, name, l1) != 0) {
1789 					dprintf("rejected in rule %d due to name mismatch.\n", i);
1790 					continue;
1791 				}
1792 			}
1793 		}
1794 		dprintf("accepted in rule %d.\n", i);
1795 		return 1;	/* hooray! */
1796 	}
1797 	return 0;
1798 }
1799 
1800 /*
1801  * Fairly similar to popen(3), but returns an open descriptor, as
1802  * opposed to a FILE *.
1803  */
1804 int
1805 p_open(prog, pid)
1806 	char *prog;
1807 	pid_t *pid;
1808 {
1809 	int pfd[2], nulldesc, i;
1810 	sigset_t omask, mask;
1811 	char *argv[4]; /* sh -c cmd NULL */
1812 	char errmsg[200];
1813 
1814 	if (pipe(pfd) == -1)
1815 		return -1;
1816 	if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
1817 		/* we are royally screwed anyway */
1818 		return -1;
1819 
1820 	sigemptyset(&mask);
1821 	sigaddset(&mask, SIGALRM);
1822 	sigaddset(&mask, SIGHUP);
1823 	sigprocmask(SIG_BLOCK, &mask, &omask);
1824 	switch ((*pid = fork())) {
1825 	case -1:
1826 		sigprocmask(SIG_SETMASK, &omask, 0);
1827 		close(nulldesc);
1828 		return -1;
1829 
1830 	case 0:
1831 		argv[0] = "sh";
1832 		argv[1] = "-c";
1833 		argv[2] = prog;
1834 		argv[3] = NULL;
1835 
1836 		alarm(0);
1837 		(void)setsid();	/* Avoid catching SIGHUPs. */
1838 
1839 		/*
1840 		 * Throw away pending signals, and reset signal
1841 		 * behaviour to standard values.
1842 		 */
1843 		signal(SIGALRM, SIG_IGN);
1844 		signal(SIGHUP, SIG_IGN);
1845 		sigprocmask(SIG_SETMASK, &omask, 0);
1846 		signal(SIGPIPE, SIG_DFL);
1847 		signal(SIGQUIT, SIG_DFL);
1848 		signal(SIGALRM, SIG_DFL);
1849 		signal(SIGHUP, SIG_DFL);
1850 
1851 		dup2(pfd[0], STDIN_FILENO);
1852 		dup2(nulldesc, STDOUT_FILENO);
1853 		dup2(nulldesc, STDERR_FILENO);
1854 		for (i = getdtablesize(); i > 2; i--)
1855 			(void) close(i);
1856 
1857 		(void) execvp(_PATH_BSHELL, argv);
1858 		_exit(255);
1859 	}
1860 
1861 	sigprocmask(SIG_SETMASK, &omask, 0);
1862 	close(nulldesc);
1863 	close(pfd[0]);
1864 	/*
1865 	 * Avoid blocking on a hung pipe.  With O_NONBLOCK, we are
1866 	 * supposed to get an EWOULDBLOCK on writev(2), which is
1867 	 * caught by the logic above anyway, which will in turn close
1868 	 * the pipe, and fork a new logging subprocess if necessary.
1869 	 * The stale subprocess will be killed some time later unless
1870 	 * it terminated itself due to closing its input pipe (so we
1871 	 * get rid of really dead puppies).
1872 	 */
1873 	if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
1874 		/* This is bad. */
1875 		(void)snprintf(errmsg, sizeof errmsg,
1876 			       "Warning: cannot change pipe to PID %d to "
1877 			       "non-blocking behaviour.",
1878 			       (int)*pid);
1879 		logerror(errmsg);
1880 	}
1881 	return pfd[1];
1882 }
1883 
1884 void
1885 deadq_enter(pid)
1886 	pid_t pid;
1887 {
1888 	dq_t p;
1889 
1890 	p = malloc(sizeof(struct deadq_entry));
1891 	if (p == 0) {
1892 		errno = 0;
1893 		logerror("panic: out of virtual memory!");
1894 		exit(1);
1895 	}
1896 
1897 	p->dq_pid = pid;
1898 	p->dq_timeout = DQ_TIMO_INIT;
1899 	TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
1900 }
1901