xref: /freebsd/usr.sbin/syslogd/syslogd.c (revision 2aebedc3ad9e722b272254e6dd3a12e399595e57)
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.42 1998/11/05 10:51:21 dg 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 	char *p;
1070 
1071 	dprintf("cvthname(%s)\n", inet_ntoa(f->sin_addr));
1072 
1073 	if (f->sin_family != AF_INET) {
1074 		dprintf("Malformed from address\n");
1075 		return ("???");
1076 	}
1077 	hp = gethostbyaddr((char *)&f->sin_addr,
1078 	    sizeof(struct in_addr), f->sin_family);
1079 	if (hp == 0) {
1080 		dprintf("Host name for your address (%s) unknown\n",
1081 			inet_ntoa(f->sin_addr));
1082 		return (inet_ntoa(f->sin_addr));
1083 	}
1084 	if ((p = strchr(hp->h_name, '.')) && strcmp(p + 1, LocalDomain) == 0)
1085 		*p = '\0';
1086 	return (hp->h_name);
1087 }
1088 
1089 void
1090 domark(signo)
1091 	int signo;
1092 {
1093 	struct filed *f;
1094 	dq_t q;
1095 
1096 	now = time((time_t *)NULL);
1097 	MarkSeq += TIMERINTVL;
1098 	if (MarkSeq >= MarkInterval) {
1099 		logmsg(LOG_INFO, "-- MARK --", LocalHostName, ADDDATE|MARK);
1100 		MarkSeq = 0;
1101 	}
1102 
1103 	for (f = Files; f; f = f->f_next) {
1104 		if (f->f_prevcount && now >= REPEATTIME(f)) {
1105 			dprintf("flush %s: repeated %d times, %d sec.\n",
1106 			    TypeNames[f->f_type], f->f_prevcount,
1107 			    repeatinterval[f->f_repeatcount]);
1108 			fprintlog(f, 0, (char *)NULL);
1109 			BACKOFF(f);
1110 		}
1111 	}
1112 
1113 	/* Walk the dead queue, and see if we should signal somebody. */
1114 	for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = TAILQ_NEXT(q, dq_entries))
1115 		switch (q->dq_timeout) {
1116 		case 0:
1117 			/* Already signalled once, try harder now. */
1118 			kill(q->dq_pid, SIGKILL);
1119 			break;
1120 
1121 		case 1:
1122 			/*
1123 			 * Timed out on dead queue, send terminate
1124 			 * signal.  Note that we leave the removal
1125 			 * from the dead queue to reapchild(), which
1126 			 * will also log the event.
1127 			 */
1128 			kill(q->dq_pid, SIGTERM);
1129 			/* FALLTROUGH */
1130 
1131 		default:
1132 			q->dq_timeout--;
1133 		}
1134 
1135 	(void)alarm(TIMERINTVL);
1136 }
1137 
1138 /*
1139  * Print syslogd errors some place.
1140  */
1141 void
1142 logerror(type)
1143 	const char *type;
1144 {
1145 	char buf[512];
1146 
1147 	if (errno)
1148 		(void)snprintf(buf,
1149 		    sizeof buf, "syslogd: %s: %s", type, strerror(errno));
1150 	else
1151 		(void)snprintf(buf, sizeof buf, "syslogd: %s", type);
1152 	errno = 0;
1153 	dprintf("%s\n", buf);
1154 	logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1155 }
1156 
1157 void
1158 die(signo)
1159 	int signo;
1160 {
1161 	struct filed *f;
1162 	int was_initialized;
1163 	char buf[100];
1164 	int i;
1165 
1166 	was_initialized = Initialized;
1167 	Initialized = 0;	/* Don't log SIGCHLDs. */
1168 	for (f = Files; f != NULL; f = f->f_next) {
1169 		/* flush any pending output */
1170 		if (f->f_prevcount)
1171 			fprintlog(f, 0, (char *)NULL);
1172 		if (f->f_type == F_PIPE)
1173 			(void)close(f->f_file);
1174 	}
1175 	Initialized = was_initialized;
1176 	if (signo) {
1177 		dprintf("syslogd: exiting on signal %d\n", signo);
1178 		(void)sprintf(buf, "exiting on signal %d", signo);
1179 		errno = 0;
1180 		logerror(buf);
1181 	}
1182 	for (i = 0; i < nfunix; i++)
1183 		if (funixn[i] && funix[i] != -1)
1184 			(void)unlink(funixn[i]);
1185 	exit(1);
1186 }
1187 
1188 /*
1189  *  INIT -- Initialize syslogd from configuration table
1190  */
1191 void
1192 init(signo)
1193 	int signo;
1194 {
1195 	int i;
1196 	FILE *cf;
1197 	struct filed *f, *next, **nextp;
1198 	char *p;
1199 	char cline[LINE_MAX];
1200  	char prog[NAME_MAX+1];
1201 
1202 	dprintf("init\n");
1203 
1204 	/*
1205 	 *  Close all open log files.
1206 	 */
1207 	Initialized = 0;
1208 	for (f = Files; f != NULL; f = next) {
1209 		/* flush any pending output */
1210 		if (f->f_prevcount)
1211 			fprintlog(f, 0, (char *)NULL);
1212 
1213 		switch (f->f_type) {
1214 		case F_FILE:
1215 		case F_FORW:
1216 		case F_CONSOLE:
1217 		case F_TTY:
1218 			(void)close(f->f_file);
1219 			break;
1220 		case F_PIPE:
1221 			(void)close(f->f_file);
1222 			if (f->f_un.f_pipe.f_pid > 0)
1223 				deadq_enter(f->f_un.f_pipe.f_pid);
1224 			f->f_un.f_pipe.f_pid = 0;
1225 			break;
1226 		}
1227 		next = f->f_next;
1228 		if(f->f_program) free(f->f_program);
1229 		free((char *)f);
1230 	}
1231 	Files = NULL;
1232 	nextp = &Files;
1233 
1234 	/* open the configuration file */
1235 	if ((cf = fopen(ConfFile, "r")) == NULL) {
1236 		dprintf("cannot open %s\n", ConfFile);
1237 		*nextp = (struct filed *)calloc(1, sizeof(*f));
1238 		cfline("*.ERR\t/dev/console", *nextp, "*");
1239 		(*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1240 		cfline("*.PANIC\t*", (*nextp)->f_next, "*");
1241 		Initialized = 1;
1242 		return;
1243 	}
1244 
1245 	/*
1246 	 *  Foreach line in the conf table, open that file.
1247 	 */
1248 	f = NULL;
1249 	strcpy(prog, "*");
1250 	while (fgets(cline, sizeof(cline), cf) != NULL) {
1251 		/*
1252 		 * check for end-of-section, comments, strip off trailing
1253 		 * spaces and newline character. #!prog is treated specially:
1254 		 * following lines apply only to that program.
1255 		 */
1256 		for (p = cline; isspace(*p); ++p)
1257 			continue;
1258 		if (*p == 0)
1259 			continue;
1260 		if(*p == '#') {
1261 			p++;
1262 			if(*p!='!')
1263 				continue;
1264 		}
1265 		if(*p=='!') {
1266 			p++;
1267 			while(isspace(*p)) p++;
1268 			if(!*p) {
1269 				strcpy(prog, "*");
1270 				continue;
1271 			}
1272 			for(i = 0; i < NAME_MAX; i++) {
1273 				if(!isalnum(p[i]))
1274 					break;
1275 				prog[i] = p[i];
1276 			}
1277 			prog[i] = 0;
1278 			continue;
1279 		}
1280 		for (p = strchr(cline, '\0'); isspace(*--p);)
1281 			continue;
1282 		*++p = '\0';
1283 		f = (struct filed *)calloc(1, sizeof(*f));
1284 		*nextp = f;
1285 		nextp = &f->f_next;
1286 		cfline(cline, f, prog);
1287 	}
1288 
1289 	/* close the configuration file */
1290 	(void)fclose(cf);
1291 
1292 	Initialized = 1;
1293 
1294 	if (Debug) {
1295 		for (f = Files; f; f = f->f_next) {
1296 			for (i = 0; i <= LOG_NFACILITIES; i++)
1297 				if (f->f_pmask[i] == INTERNAL_NOPRI)
1298 					printf("X ");
1299 				else
1300 					printf("%d ", f->f_pmask[i]);
1301 			printf("%s: ", TypeNames[f->f_type]);
1302 			switch (f->f_type) {
1303 			case F_FILE:
1304 				printf("%s", f->f_un.f_fname);
1305 				break;
1306 
1307 			case F_CONSOLE:
1308 			case F_TTY:
1309 				printf("%s%s", _PATH_DEV, f->f_un.f_fname);
1310 				break;
1311 
1312 			case F_FORW:
1313 				printf("%s", f->f_un.f_forw.f_hname);
1314 				break;
1315 
1316 			case F_PIPE:
1317 				printf("%s", f->f_un.f_pipe.f_pname);
1318 				break;
1319 
1320 			case F_USERS:
1321 				for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1322 					printf("%s, ", f->f_un.f_uname[i]);
1323 				break;
1324 			}
1325 			if(f->f_program) {
1326 				printf(" (%s)", f->f_program);
1327 			}
1328 			printf("\n");
1329 		}
1330 	}
1331 
1332 	logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1333 	dprintf("syslogd: restarted\n");
1334 }
1335 
1336 /*
1337  * Crack a configuration file line
1338  */
1339 void
1340 cfline(line, f, prog)
1341 	char *line;
1342 	struct filed *f;
1343 	char *prog;
1344 {
1345 	struct hostent *hp;
1346 	int i, pri;
1347 	char *bp, *p, *q;
1348 	char buf[MAXLINE], ebuf[100];
1349 
1350 	dprintf("cfline(\"%s\", f, \"%s\")\n", line, prog);
1351 
1352 	errno = 0;	/* keep strerror() stuff out of logerror messages */
1353 
1354 	/* clear out file entry */
1355 	memset(f, 0, sizeof(*f));
1356 	for (i = 0; i <= LOG_NFACILITIES; i++)
1357 		f->f_pmask[i] = INTERNAL_NOPRI;
1358 
1359 	/* save program name if any */
1360 	if(prog && *prog=='*') prog = NULL;
1361 	if(prog) {
1362 		f->f_program = calloc(1, strlen(prog)+1);
1363 		if(f->f_program) {
1364 			strcpy(f->f_program, prog);
1365 		}
1366 	}
1367 
1368 	/* scan through the list of selectors */
1369 	for (p = line; *p && *p != '\t' && *p != ' ';) {
1370 		int pri_done;
1371 		int pri_cmp;
1372 
1373 		/* find the end of this facility name list */
1374 		for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
1375 			continue;
1376 
1377 		/* get the priority comparison */
1378 		pri_cmp = 0;
1379 		pri_done = 0;
1380 		while (!pri_done) {
1381 			switch (*q) {
1382 			case '<':
1383 				pri_cmp |= PRI_LT;
1384 				q++;
1385 				break;
1386 			case '=':
1387 				pri_cmp |= PRI_EQ;
1388 				q++;
1389 				break;
1390 			case '>':
1391 				pri_cmp |= PRI_GT;
1392 				q++;
1393 				break;
1394 			default:
1395 				pri_done++;
1396 				break;
1397 			}
1398 		}
1399 		if (!pri_cmp)
1400 			pri_cmp = (UniquePriority)
1401 				  ? (PRI_EQ)
1402 				  : (PRI_EQ | PRI_GT)
1403 				  ;
1404 
1405 		/* collect priority name */
1406 		for (bp = buf; *q && !strchr("\t,; ", *q); )
1407 			*bp++ = *q++;
1408 		*bp = '\0';
1409 
1410 		/* skip cruft */
1411 		while (strchr(",;", *q))
1412 			q++;
1413 
1414 		/* decode priority name */
1415 		if (*buf == '*')
1416 			pri = LOG_PRIMASK + 1;
1417 		else {
1418 			pri = decode(buf, prioritynames);
1419 			if (pri < 0) {
1420 				(void)snprintf(ebuf, sizeof ebuf,
1421 				    "unknown priority name \"%s\"", buf);
1422 				logerror(ebuf);
1423 				return;
1424 			}
1425 		}
1426 
1427 		/* scan facilities */
1428 		while (*p && !strchr("\t.; ", *p)) {
1429 			for (bp = buf; *p && !strchr("\t,;. ", *p); )
1430 				*bp++ = *p++;
1431 			*bp = '\0';
1432 
1433 			if (*buf == '*')
1434 				for (i = 0; i < LOG_NFACILITIES; i++) {
1435 					f->f_pmask[i] = pri;
1436 					f->f_pcmp[i] = pri_cmp;
1437 				}
1438 			else {
1439 				i = decode(buf, facilitynames);
1440 				if (i < 0) {
1441 					(void)snprintf(ebuf, sizeof ebuf,
1442 					    "unknown facility name \"%s\"",
1443 					    buf);
1444 					logerror(ebuf);
1445 					return;
1446 				}
1447 				f->f_pmask[i >> 3] = pri;
1448 				f->f_pcmp[i >> 3] = pri_cmp;
1449 			}
1450 			while (*p == ',' || *p == ' ')
1451 				p++;
1452 		}
1453 
1454 		p = q;
1455 	}
1456 
1457 	/* skip to action part */
1458 	while (*p == '\t' || *p == ' ')
1459 		p++;
1460 
1461 	switch (*p)
1462 	{
1463 	case '@':
1464 		(void)strcpy(f->f_un.f_forw.f_hname, ++p);
1465 		hp = gethostbyname(p);
1466 		if (hp == NULL) {
1467 			extern int h_errno;
1468 
1469 			logerror(hstrerror(h_errno));
1470 			break;
1471 		}
1472 		memset(&f->f_un.f_forw.f_addr, 0,
1473 			 sizeof(f->f_un.f_forw.f_addr));
1474 		f->f_un.f_forw.f_addr.sin_family = AF_INET;
1475 		f->f_un.f_forw.f_addr.sin_port = LogPort;
1476 		memmove(&f->f_un.f_forw.f_addr.sin_addr, hp->h_addr, hp->h_length);
1477 		f->f_type = F_FORW;
1478 		break;
1479 
1480 	case '/':
1481 		if ((f->f_file = open(p, O_WRONLY|O_APPEND, 0)) < 0) {
1482 			f->f_type = F_UNUSED;
1483 			logerror(p);
1484 			break;
1485 		}
1486 		if (isatty(f->f_file)) {
1487 			if (strcmp(p, ctty) == 0)
1488 				f->f_type = F_CONSOLE;
1489 			else
1490 				f->f_type = F_TTY;
1491 			(void)strcpy(f->f_un.f_fname, p + sizeof _PATH_DEV - 1);
1492 		} else {
1493 			(void)strcpy(f->f_un.f_fname, p);
1494 			f->f_type = F_FILE;
1495 		}
1496 		break;
1497 
1498 	case '|':
1499 		f->f_un.f_pipe.f_pid = 0;
1500 		(void)strcpy(f->f_un.f_pipe.f_pname, p + 1);
1501 		f->f_type = F_PIPE;
1502 		break;
1503 
1504 	case '*':
1505 		f->f_type = F_WALL;
1506 		break;
1507 
1508 	default:
1509 		for (i = 0; i < MAXUNAMES && *p; i++) {
1510 			for (q = p; *q && *q != ','; )
1511 				q++;
1512 			(void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
1513 			if ((q - p) > UT_NAMESIZE)
1514 				f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
1515 			else
1516 				f->f_un.f_uname[i][q - p] = '\0';
1517 			while (*q == ',' || *q == ' ')
1518 				q++;
1519 			p = q;
1520 		}
1521 		f->f_type = F_USERS;
1522 		break;
1523 	}
1524 }
1525 
1526 
1527 /*
1528  *  Decode a symbolic name to a numeric value
1529  */
1530 int
1531 decode(name, codetab)
1532 	const char *name;
1533 	CODE *codetab;
1534 {
1535 	CODE *c;
1536 	char *p, buf[40];
1537 
1538 	if (isdigit(*name))
1539 		return (atoi(name));
1540 
1541 	for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
1542 		if (isupper(*name))
1543 			*p = tolower(*name);
1544 		else
1545 			*p = *name;
1546 	}
1547 	*p = '\0';
1548 	for (c = codetab; c->c_name; c++)
1549 		if (!strcmp(buf, c->c_name))
1550 			return (c->c_val);
1551 
1552 	return (-1);
1553 }
1554 
1555 /*
1556  * fork off and become a daemon, but wait for the child to come online
1557  * before returing to the parent, or we get disk thrashing at boot etc.
1558  * Set a timer so we don't hang forever if it wedges.
1559  */
1560 int
1561 waitdaemon(nochdir, noclose, maxwait)
1562 	int nochdir, noclose, maxwait;
1563 {
1564 	int fd;
1565 	int status;
1566 	pid_t pid, childpid;
1567 
1568 	switch (childpid = fork()) {
1569 	case -1:
1570 		return (-1);
1571 	case 0:
1572 		break;
1573 	default:
1574 		signal(SIGALRM, timedout);
1575 		alarm(maxwait);
1576 		while ((pid = wait3(&status, 0, NULL)) != -1) {
1577 			if (WIFEXITED(status))
1578 				errx(1, "child pid %d exited with return code %d",
1579 					pid, WEXITSTATUS(status));
1580 			if (WIFSIGNALED(status))
1581 				errx(1, "child pid %d exited on signal %d%s",
1582 					pid, WTERMSIG(status),
1583 					WCOREDUMP(status) ? " (core dumped)" :
1584 					"");
1585 			if (pid == childpid)	/* it's gone... */
1586 				break;
1587 		}
1588 		exit(0);
1589 	}
1590 
1591 	if (setsid() == -1)
1592 		return (-1);
1593 
1594 	if (!nochdir)
1595 		(void)chdir("/");
1596 
1597 	if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1598 		(void)dup2(fd, STDIN_FILENO);
1599 		(void)dup2(fd, STDOUT_FILENO);
1600 		(void)dup2(fd, STDERR_FILENO);
1601 		if (fd > 2)
1602 			(void)close (fd);
1603 	}
1604 	return (getppid());
1605 }
1606 
1607 /*
1608  * We get a SIGALRM from the child when it's running and finished doing it's
1609  * fsync()'s or O_SYNC writes for all the boot messages.
1610  *
1611  * We also get a signal from the kernel if the timer expires, so check to
1612  * see what happened.
1613  */
1614 void
1615 timedout(sig)
1616 	int sig __unused;
1617 {
1618 	int left;
1619 	left = alarm(0);
1620 	signal(SIGALRM, SIG_DFL);
1621 	if (left == 0)
1622 		errx(1, "timed out waiting for child");
1623 	else
1624 		exit(0);
1625 }
1626 
1627 /*
1628  * Add `s' to the list of allowable peer addresses to accept messages
1629  * from.
1630  *
1631  * `s' is a string in the form:
1632  *
1633  *    [*]domainname[:{servicename|portnumber|*}]
1634  *
1635  * or
1636  *
1637  *    netaddr/maskbits[:{servicename|portnumber|*}]
1638  *
1639  * Returns -1 on error, 0 if the argument was valid.
1640  */
1641 int
1642 allowaddr(s)
1643 	char *s;
1644 {
1645 	char *cp1, *cp2;
1646 	struct allowedpeer ap;
1647 	struct servent *se;
1648 	regex_t re;
1649 	int i;
1650 
1651 	if ((cp1 = strrchr(s, ':'))) {
1652 		/* service/port provided */
1653 		*cp1++ = '\0';
1654 		if (strlen(cp1) == 1 && *cp1 == '*')
1655 			/* any port allowed */
1656 			ap.port = htons(0);
1657 		else if ((se = getservbyname(cp1, "udp")))
1658 			ap.port = se->s_port;
1659 		else {
1660 			ap.port = htons((int)strtol(cp1, &cp2, 0));
1661 			if (*cp2 != '\0')
1662 				return -1; /* port not numeric */
1663 		}
1664 	} else {
1665 		if ((se = getservbyname("syslog", "udp")))
1666 			ap.port = se->s_port;
1667 		else
1668 			/* sanity, should not happen */
1669 			ap.port = htons(514);
1670 	}
1671 
1672 	/* the regexp's are ugly, but the cleanest way */
1673 
1674 	if (regcomp(&re, "^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+(/[0-9]+)?$",
1675 		    REG_EXTENDED))
1676 		/* if RE compilation fails, that's an internal error */
1677 		abort();
1678 	if (regexec(&re, s, 0, 0, 0) == 0) {
1679 		/* arg `s' is numeric */
1680 		ap.isnumeric = 1;
1681 		if ((cp1 = strchr(s, '/')) != NULL) {
1682 			*cp1++ = '\0';
1683 			i = atoi(cp1);
1684 			if (i < 0 || i > 32)
1685 				return -1;
1686 			/* convert masklen to netmask */
1687 			ap.a_mask.s_addr = htonl(~((1 << (32 - i)) - 1));
1688 		}
1689 		if (ascii2addr(AF_INET, s, &ap.a_addr) == -1)
1690 			return -1;
1691 		if (cp1 == NULL) {
1692 			/* use default netmask */
1693 			if (IN_CLASSA(ntohl(ap.a_addr.s_addr)))
1694 				ap.a_mask.s_addr = htonl(IN_CLASSA_NET);
1695 			else if (IN_CLASSB(ntohl(ap.a_addr.s_addr)))
1696 				ap.a_mask.s_addr = htonl(IN_CLASSB_NET);
1697 			else
1698 				ap.a_mask.s_addr = htonl(IN_CLASSC_NET);
1699 		}
1700 	} else {
1701 		/* arg `s' is domain name */
1702 		ap.isnumeric = 0;
1703 		ap.a_name = s;
1704 	}
1705 	regfree(&re);
1706 
1707 	if (Debug) {
1708 		printf("allowaddr: rule %d: ", NumAllowed);
1709 		if (ap.isnumeric) {
1710 			printf("numeric, ");
1711 			printf("addr = %s, ",
1712 			       addr2ascii(AF_INET, &ap.a_addr, sizeof(struct in_addr), 0));
1713 			printf("mask = %s; ",
1714 			       addr2ascii(AF_INET, &ap.a_mask, sizeof(struct in_addr), 0));
1715 		} else
1716 			printf("domainname = %s; ", ap.a_name);
1717 		printf("port = %d\n", ntohs(ap.port));
1718 	}
1719 
1720 	if ((AllowedPeers = realloc(AllowedPeers,
1721 				    ++NumAllowed * sizeof(struct allowedpeer)))
1722 	    == NULL) {
1723 		fprintf(stderr, "Out of memory!\n");
1724 		exit(EX_OSERR);
1725 	}
1726 	memcpy(&AllowedPeers[NumAllowed - 1], &ap, sizeof(struct allowedpeer));
1727 	return 0;
1728 }
1729 
1730 /*
1731  * Validate that the remote peer has permission to log to us.
1732  */
1733 int
1734 validate(sin, hname)
1735 	struct sockaddr_in *sin;
1736 	const char *hname;
1737 {
1738 	int i;
1739 	size_t l1, l2;
1740 	char *cp, name[MAXHOSTNAMELEN];
1741 	struct allowedpeer *ap;
1742 
1743 	if (NumAllowed == 0)
1744 		/* traditional behaviour, allow everything */
1745 		return 1;
1746 
1747 	strncpy(name, hname, sizeof name);
1748 	if (strchr(name, '.') == NULL) {
1749 		strncat(name, ".", sizeof name - strlen(name) - 1);
1750 		strncat(name, LocalDomain, sizeof name - strlen(name) - 1);
1751 	}
1752 	dprintf("validate: dgram from IP %s, port %d, name %s;\n",
1753 		addr2ascii(AF_INET, &sin->sin_addr, sizeof(struct in_addr), 0),
1754 		ntohs(sin->sin_port), name);
1755 
1756 	/* now, walk down the list */
1757 	for (i = 0, ap = AllowedPeers; i < NumAllowed; i++, ap++) {
1758 		if (ntohs(ap->port) != 0 && ap->port != sin->sin_port) {
1759 			dprintf("rejected in rule %d due to port mismatch.\n", i);
1760 			continue;
1761 		}
1762 
1763 		if (ap->isnumeric) {
1764 			if ((sin->sin_addr.s_addr & ap->a_mask.s_addr)
1765 			    != ap->a_addr.s_addr) {
1766 				dprintf("rejected in rule %d due to IP mismatch.\n", i);
1767 				continue;
1768 			}
1769 		} else {
1770 			cp = ap->a_name;
1771 			l1 = strlen(name);
1772 			if (*cp == '*') {
1773 				/* allow wildmatch */
1774 				cp++;
1775 				l2 = strlen(cp);
1776 				if (l2 > l1 || memcmp(cp, &name[l1 - l2], l2) != 0) {
1777 					dprintf("rejected in rule %d due to name mismatch.\n", i);
1778 					continue;
1779 				}
1780 			} else {
1781 				/* exact match */
1782 				l2 = strlen(cp);
1783 				if (l2 != l1 || memcmp(cp, name, l1) != 0) {
1784 					dprintf("rejected in rule %d due to name mismatch.\n", i);
1785 					continue;
1786 				}
1787 			}
1788 		}
1789 		dprintf("accepted in rule %d.\n", i);
1790 		return 1;	/* hooray! */
1791 	}
1792 	return 0;
1793 }
1794 
1795 /*
1796  * Fairly similar to popen(3), but returns an open descriptor, as
1797  * opposed to a FILE *.
1798  */
1799 int
1800 p_open(prog, pid)
1801 	char *prog;
1802 	pid_t *pid;
1803 {
1804 	int pfd[2], nulldesc, i;
1805 	sigset_t omask, mask;
1806 	char *argv[4]; /* sh -c cmd NULL */
1807 	char errmsg[200];
1808 
1809 	if (pipe(pfd) == -1)
1810 		return -1;
1811 	if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
1812 		/* we are royally screwed anyway */
1813 		return -1;
1814 
1815 	sigemptyset(&mask);
1816 	sigaddset(&mask, SIGALRM);
1817 	sigaddset(&mask, SIGHUP);
1818 	sigprocmask(SIG_BLOCK, &mask, &omask);
1819 	switch ((*pid = fork())) {
1820 	case -1:
1821 		sigprocmask(SIG_SETMASK, &omask, 0);
1822 		close(nulldesc);
1823 		return -1;
1824 
1825 	case 0:
1826 		argv[0] = "sh";
1827 		argv[1] = "-c";
1828 		argv[2] = prog;
1829 		argv[3] = NULL;
1830 
1831 		alarm(0);
1832 		(void)setsid();	/* Avoid catching SIGHUPs. */
1833 
1834 		/*
1835 		 * Throw away pending signals, and reset signal
1836 		 * behaviour to standard values.
1837 		 */
1838 		signal(SIGALRM, SIG_IGN);
1839 		signal(SIGHUP, SIG_IGN);
1840 		sigprocmask(SIG_SETMASK, &omask, 0);
1841 		signal(SIGPIPE, SIG_DFL);
1842 		signal(SIGQUIT, SIG_DFL);
1843 		signal(SIGALRM, SIG_DFL);
1844 		signal(SIGHUP, SIG_DFL);
1845 
1846 		dup2(pfd[0], STDIN_FILENO);
1847 		dup2(nulldesc, STDOUT_FILENO);
1848 		dup2(nulldesc, STDERR_FILENO);
1849 		for (i = getdtablesize(); i > 2; i--)
1850 			(void) close(i);
1851 
1852 		(void) execvp(_PATH_BSHELL, argv);
1853 		_exit(255);
1854 	}
1855 
1856 	sigprocmask(SIG_SETMASK, &omask, 0);
1857 	close(nulldesc);
1858 	close(pfd[0]);
1859 	/*
1860 	 * Avoid blocking on a hung pipe.  With O_NONBLOCK, we are
1861 	 * supposed to get an EWOULDBLOCK on writev(2), which is
1862 	 * caught by the logic above anyway, which will in turn close
1863 	 * the pipe, and fork a new logging subprocess if necessary.
1864 	 * The stale subprocess will be killed some time later unless
1865 	 * it terminated itself due to closing its input pipe (so we
1866 	 * get rid of really dead puppies).
1867 	 */
1868 	if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
1869 		/* This is bad. */
1870 		(void)snprintf(errmsg, sizeof errmsg,
1871 			       "Warning: cannot change pipe to PID %d to "
1872 			       "non-blocking behaviour.",
1873 			       (int)*pid);
1874 		logerror(errmsg);
1875 	}
1876 	return pfd[1];
1877 }
1878 
1879 void
1880 deadq_enter(pid)
1881 	pid_t pid;
1882 {
1883 	dq_t p;
1884 
1885 	p = malloc(sizeof(struct deadq_entry));
1886 	if (p == 0) {
1887 		errno = 0;
1888 		logerror("panic: out of virtual memory!");
1889 		exit(1);
1890 	}
1891 
1892 	p->dq_pid = pid;
1893 	p->dq_timeout = DQ_TIMO_INIT;
1894 	TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
1895 }
1896