xref: /original-bsd/usr.sbin/syslogd/syslogd.c (revision d919d844)
1 /*
2  * Copyright (c) 1983, 1988 Regents of the University of California.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms are permitted
6  * provided that the above copyright notice and this paragraph are
7  * duplicated in all such forms and that any documentation,
8  * advertising materials, and other materials related to such
9  * distribution and use acknowledge that the software was developed
10  * by the University of California, Berkeley.  The name of the
11  * University may not be used to endorse or promote products derived
12  * from this software without specific prior written permission.
13  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
15  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
16  */
17 
18 #ifndef lint
19 char copyright[] =
20 "@(#) Copyright (c) 1983, 1988 Regents of the University of California.\n\
21  All rights reserved.\n";
22 #endif /* not lint */
23 
24 #ifndef lint
25 static char sccsid[] = "@(#)syslogd.c	5.27 (Berkeley) 10/10/88";
26 #endif /* not lint */
27 
28 /*
29  *  syslogd -- log system messages
30  *
31  * This program implements a system log. It takes a series of lines.
32  * Each line may have a priority, signified as "<n>" as
33  * the first characters of the line.  If this is
34  * not present, a default priority is used.
35  *
36  * To kill syslogd, send a signal 15 (terminate).  A signal 1 (hup) will
37  * cause it to reread its configuration file.
38  *
39  * Defined Constants:
40  *
41  * MAXLINE -- the maximimum line length that can be handled.
42  * DEFUPRI -- the default priority for user messages
43  * DEFSPRI -- the default priority for kernel messages
44  *
45  * Author: Eric Allman
46  * extensive changes by Ralph Campbell
47  * more extensive changes by Eric Allman (again)
48  */
49 
50 #define	MAXLINE		1024		/* maximum line length */
51 #define	MAXSVLINE	120		/* maximum saved line length */
52 #define DEFUPRI		(LOG_USER|LOG_NOTICE)
53 #define DEFSPRI		(LOG_KERN|LOG_CRIT)
54 #define TIMERINTVL	30		/* interval for checking flush, mark */
55 
56 #include <stdio.h>
57 #include <utmp.h>
58 #include <ctype.h>
59 #include <strings.h>
60 #include <setjmp.h>
61 
62 #include <sys/syslog.h>
63 #include <sys/param.h>
64 #include <sys/errno.h>
65 #include <sys/ioctl.h>
66 #include <sys/stat.h>
67 #include <sys/wait.h>
68 #include <sys/socket.h>
69 #include <sys/file.h>
70 #include <sys/msgbuf.h>
71 #include <sys/uio.h>
72 #include <sys/un.h>
73 #include <sys/time.h>
74 #include <sys/resource.h>
75 #include <sys/signal.h>
76 
77 #include <netinet/in.h>
78 #include <netdb.h>
79 
80 #define	CTTY	"/dev/console"
81 char	*LogName = "/dev/log";
82 char	*ConfFile = "/etc/syslog.conf";
83 char	*PidFile = "/etc/syslog.pid";
84 char	ctty[] = CTTY;
85 
86 #define FDMASK(fd)	(1 << (fd))
87 
88 #define	dprintf		if (Debug) printf
89 
90 #define UNAMESZ		8	/* length of a login name */
91 #define MAXUNAMES	20	/* maximum number of user names */
92 #define MAXFNAME	200	/* max file pathname length */
93 
94 #define NOPRI		0x10	/* the "no priority" priority */
95 #define	LOG_MARK	LOG_MAKEPRI(LOG_NFACILITIES, 0)	/* mark "facility" */
96 
97 /*
98  * Flags to logmsg().
99  */
100 
101 #define IGN_CONS	0x001	/* don't print on console */
102 #define SYNC_FILE	0x002	/* do fsync on file after printing */
103 #define ADDDATE		0x004	/* add a date to the message */
104 #define MARK		0x008	/* this message is a mark */
105 
106 /*
107  * This structure represents the files that will have log
108  * copies printed.
109  */
110 
111 struct filed {
112 	struct	filed *f_next;		/* next in linked list */
113 	short	f_type;			/* entry type, see below */
114 	short	f_file;			/* file descriptor */
115 	time_t	f_time;			/* time this was last written */
116 	u_char	f_pmask[LOG_NFACILITIES+1];	/* priority mask */
117 	union {
118 		char	f_uname[MAXUNAMES][UNAMESZ+1];
119 		struct {
120 			char	f_hname[MAXHOSTNAMELEN+1];
121 			struct sockaddr_in	f_addr;
122 		} f_forw;		/* forwarding address */
123 		char	f_fname[MAXFNAME];
124 	} f_un;
125 	char	f_prevline[MAXSVLINE];		/* last message logged */
126 	char	f_lasttime[16];			/* time of last occurrence */
127 	char	f_prevhost[MAXHOSTNAMELEN+1];	/* host from which recd. */
128 	int	f_prevpri;			/* pri of f_prevline */
129 	int	f_prevlen;			/* length of f_prevline */
130 	int	f_prevcount;			/* repetition cnt of prevline */
131 	int	f_repeatcount;			/* number of "repeated" msgs */
132 };
133 
134 /*
135  * Intervals at which we flush out "message repeated" messages,
136  * in seconds after previous message is logged.  After each flush,
137  * we move to the next interval until we reach the largest.
138  */
139 int	repeatinterval[] = { 30, 120, 600 };	/* # of secs before flush */
140 #define	MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
141 #define	REPEATTIME(f)	((f)->f_time + repeatinterval[(f)->f_repeatcount])
142 #define	BACKOFF(f)	{ if (++(f)->f_repeatcount > MAXREPEAT) \
143 				 (f)->f_repeatcount = MAXREPEAT; \
144 			}
145 
146 /* values for f_type */
147 #define F_UNUSED	0		/* unused entry */
148 #define F_FILE		1		/* regular file */
149 #define F_TTY		2		/* terminal */
150 #define F_CONSOLE	3		/* console terminal */
151 #define F_FORW		4		/* remote machine */
152 #define F_USERS		5		/* list of users */
153 #define F_WALL		6		/* everyone logged on */
154 
155 char	*TypeNames[7] = {
156 	"UNUSED",	"FILE",		"TTY",		"CONSOLE",
157 	"FORW",		"USERS",	"WALL"
158 };
159 
160 struct	filed *Files;
161 struct	filed consfile;
162 
163 int	Debug;			/* debug flag */
164 char	LocalHostName[MAXHOSTNAMELEN+1];	/* our hostname */
165 char	*LocalDomain;		/* our local domain name */
166 int	InetInuse = 0;		/* non-zero if INET sockets are being used */
167 int	finet;			/* Internet datagram socket */
168 int	LogPort;		/* port number for INET connections */
169 int	Initialized = 0;	/* set when we have initialized ourselves */
170 int	MarkInterval = 20 * 60;	/* interval between marks in seconds */
171 int	MarkSeq = 0;		/* mark sequence number */
172 
173 extern	int errno, sys_nerr;
174 extern	char *sys_errlist[];
175 extern	char *ctime(), *index(), *calloc();
176 
177 main(argc, argv)
178 	int argc;
179 	char **argv;
180 {
181 	register int i;
182 	register char *p;
183 	int funix, inetm, fklog, klogm, len;
184 	struct sockaddr_un sunx, fromunix;
185 	struct sockaddr_in sin, frominet;
186 	FILE *fp;
187 	int ch;
188 	char line[MSG_BSIZE + 1];
189 	extern int optind, die(), domark(), reapchild();
190 	extern char *optarg;
191 
192 	while ((ch = getopt(argc, argv, "df:m:p:")) != EOF)
193 		switch((char)ch) {
194 		case 'd':		/* debug */
195 			Debug++;
196 			break;
197 		case 'f':		/* configuration file */
198 			ConfFile = optarg;
199 			break;
200 		case 'm':		/* mark interval */
201 			MarkInterval = atoi(optarg) * 60;
202 			break;
203 		case 'p':		/* path */
204 			LogName = optarg;
205 			break;
206 		case '?':
207 		default:
208 			usage();
209 		}
210 	if (argc -= optind)
211 		usage();
212 
213 	if (!Debug) {
214 		if (fork())
215 			exit(0);
216 		for (i = 0; i < 10; i++)
217 			(void) close(i);
218 		(void) open("/", 0);
219 		(void) dup2(0, 1);
220 		(void) dup2(0, 2);
221 		untty();
222 	} else
223 		setlinebuf(stdout);
224 
225 	consfile.f_type = F_CONSOLE;
226 	(void) strcpy(consfile.f_un.f_fname, ctty);
227 	(void) gethostname(LocalHostName, sizeof LocalHostName);
228 	if (p = index(LocalHostName, '.')) {
229 		*p++ = '\0';
230 		LocalDomain = p;
231 	}
232 	else
233 		LocalDomain = "";
234 	(void) signal(SIGTERM, die);
235 	(void) signal(SIGINT, Debug ? die : SIG_IGN);
236 	(void) signal(SIGQUIT, Debug ? die : SIG_IGN);
237 	(void) signal(SIGCHLD, reapchild);
238 	(void) signal(SIGALRM, domark);
239 	(void) alarm(TIMERINTVL);
240 	(void) unlink(LogName);
241 
242 	sunx.sun_family = AF_UNIX;
243 	(void) strncpy(sunx.sun_path, LogName, sizeof sunx.sun_path);
244 	funix = socket(AF_UNIX, SOCK_DGRAM, 0);
245 	if (funix < 0 || bind(funix, (struct sockaddr *) &sunx,
246 	    sizeof(sunx.sun_family)+strlen(sunx.sun_path)) < 0 ||
247 	    chmod(LogName, 0666) < 0) {
248 		(void) sprintf(line, "cannot create %s", LogName);
249 		logerror(line);
250 		dprintf("cannot create %s (%d)\n", LogName, errno);
251 		die(0);
252 	}
253 	finet = socket(AF_INET, SOCK_DGRAM, 0);
254 	if (finet >= 0) {
255 		struct servent *sp;
256 
257 		sp = getservbyname("syslog", "udp");
258 		if (sp == NULL) {
259 			errno = 0;
260 			logerror("syslog/udp: unknown service");
261 			die(0);
262 		}
263 		sin.sin_family = AF_INET;
264 		sin.sin_port = LogPort = sp->s_port;
265 		if (bind(finet, &sin, sizeof(sin)) < 0) {
266 			logerror("bind");
267 			if (!Debug)
268 				die(0);
269 		} else {
270 			inetm = FDMASK(finet);
271 			InetInuse = 1;
272 		}
273 	}
274 	if ((fklog = open("/dev/klog", O_RDONLY)) >= 0)
275 		klogm = FDMASK(fklog);
276 	else {
277 		dprintf("can't open /dev/klog (%d)\n", errno);
278 		klogm = 0;
279 	}
280 
281 	/* tuck my process id away */
282 	fp = fopen(PidFile, "w");
283 	if (fp != NULL) {
284 		fprintf(fp, "%d\n", getpid());
285 		(void) fclose(fp);
286 	}
287 
288 	dprintf("off & running....\n");
289 
290 	init();
291 	(void) signal(SIGHUP, init);
292 
293 	for (;;) {
294 		int nfds, readfds = FDMASK(funix) | inetm | klogm;
295 
296 		errno = 0;
297 		dprintf("readfds = %#x\n", readfds);
298 		nfds = select(20, (fd_set *) &readfds, (fd_set *) NULL,
299 				  (fd_set *) NULL, (struct timeval *) NULL);
300 		if (nfds == 0)
301 			continue;
302 		if (nfds < 0) {
303 			if (errno != EINTR)
304 				logerror("select");
305 			continue;
306 		}
307 		dprintf("got a message (%d, %#x)\n", nfds, readfds);
308 		if (readfds & klogm) {
309 			i = read(fklog, line, sizeof(line) - 1);
310 			if (i > 0) {
311 				line[i] = '\0';
312 				printsys(line);
313 			} else if (i < 0 && errno != EINTR) {
314 				logerror("klog");
315 				fklog = -1;
316 				klogm = 0;
317 			}
318 		}
319 		if (readfds & FDMASK(funix)) {
320 			len = sizeof fromunix;
321 			i = recvfrom(funix, line, MAXLINE, 0,
322 				     (struct sockaddr *) &fromunix, &len);
323 			if (i > 0) {
324 				line[i] = '\0';
325 				printline(LocalHostName, line);
326 			} else if (i < 0 && errno != EINTR)
327 				logerror("recvfrom unix");
328 		}
329 		if (readfds & inetm) {
330 			len = sizeof frominet;
331 			i = recvfrom(finet, line, MAXLINE, 0, &frominet, &len);
332 			if (i > 0) {
333 				extern char *cvthname();
334 
335 				line[i] = '\0';
336 				printline(cvthname(&frominet), line);
337 			} else if (i < 0 && errno != EINTR)
338 				logerror("recvfrom inet");
339 		}
340 	}
341 }
342 
343 usage()
344 {
345 	fprintf(stderr, "usage: syslogd [-d] [-m markinterval] [-p path] [-f conffile]\n");
346 	exit(1);
347 }
348 
349 untty()
350 {
351 	int i;
352 
353 	if (!Debug) {
354 		i = open("/dev/tty", O_RDWR);
355 		if (i >= 0) {
356 			(void) ioctl(i, (int) TIOCNOTTY, (char *)0);
357 			(void) close(i);
358 		}
359 	}
360 }
361 
362 /*
363  * Take a raw input line, decode the message, and print the message
364  * on the appropriate log files.
365  */
366 
367 printline(hname, msg)
368 	char *hname;
369 	char *msg;
370 {
371 	register char *p, *q;
372 	register int c;
373 	char line[MAXLINE + 1];
374 	int pri;
375 
376 	/* test for special codes */
377 	pri = DEFUPRI;
378 	p = msg;
379 	if (*p == '<') {
380 		pri = 0;
381 		while (isdigit(*++p))
382 			pri = 10 * pri + (*p - '0');
383 		if (*p == '>')
384 			++p;
385 	}
386 	if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
387 		pri = DEFUPRI;
388 
389 	/* don't allow users to log kernel messages */
390 	if (LOG_FAC(pri) == LOG_KERN)
391 		pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
392 
393 	q = line;
394 
395 	while ((c = *p++ & 0177) != '\0' &&
396 	    q < &line[sizeof(line) - 1])
397 		if (c == '\n')
398 			*q++ = ' ';
399 		else if (iscntrl(c)) {
400 			*q++ = '^';
401 			*q++ = c ^ 0100;
402 		} else
403 			*q++ = c;
404 	*q = '\0';
405 
406 	logmsg(pri, line, hname, 0);
407 }
408 
409 /*
410  * Take a raw input line from /dev/klog, split and format similar to syslog().
411  */
412 
413 printsys(msg)
414 	char *msg;
415 {
416 	register char *p, *q;
417 	register int c;
418 	char line[MAXLINE + 1];
419 	int pri, flags;
420 	char *lp;
421 
422 	(void) sprintf(line, "vmunix: ");
423 	lp = line + strlen(line);
424 	for (p = msg; *p != '\0'; ) {
425 		flags = SYNC_FILE | ADDDATE;	/* fsync file after write */
426 		pri = DEFSPRI;
427 		if (*p == '<') {
428 			pri = 0;
429 			while (isdigit(*++p))
430 				pri = 10 * pri + (*p - '0');
431 			if (*p == '>')
432 				++p;
433 		} else {
434 			/* kernel printf's come out on console */
435 			flags |= IGN_CONS;
436 		}
437 		if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
438 			pri = DEFSPRI;
439 		q = lp;
440 		while (*p != '\0' && (c = *p++) != '\n' &&
441 		    q < &line[MAXLINE])
442 			*q++ = c;
443 		*q = '\0';
444 		logmsg(pri, line, LocalHostName, flags);
445 	}
446 }
447 
448 time_t	now;
449 
450 /*
451  * Log a message to the appropriate log files, users, etc. based on
452  * the priority.
453  */
454 
455 logmsg(pri, msg, from, flags)
456 	int pri;
457 	char *msg, *from;
458 	int flags;
459 {
460 	register struct filed *f;
461 	int fac, prilev;
462 	int omask, msglen;
463 	char *timestamp;
464 
465 	dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n", pri, flags, from, msg);
466 
467 	omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
468 
469 	/*
470 	 * Check to see if msg looks non-standard.
471 	 */
472 	msglen = strlen(msg);
473 	if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
474 	    msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
475 		flags |= ADDDATE;
476 
477 	(void) time(&now);
478 	if (flags & ADDDATE)
479 		timestamp = ctime(&now) + 4;
480 	else {
481 		timestamp = msg;
482 		msg += 16;
483 		msglen -= 16;
484 	}
485 
486 	/* extract facility and priority level */
487 	if (flags & MARK)
488 		fac = LOG_NFACILITIES;
489 	else
490 		fac = LOG_FAC(pri);
491 	prilev = LOG_PRI(pri);
492 
493 	/* log the message to the particular outputs */
494 	if (!Initialized) {
495 		f = &consfile;
496 		f->f_file = open(ctty, O_WRONLY);
497 
498 		if (f->f_file >= 0) {
499 			untty();
500 			fprintlog(f, flags, msg);
501 			(void) close(f->f_file);
502 		}
503 		(void) sigsetmask(omask);
504 		return;
505 	}
506 	for (f = Files; f; f = f->f_next) {
507 		/* skip messages that are incorrect priority */
508 		if (f->f_pmask[fac] < prilev || f->f_pmask[fac] == NOPRI)
509 			continue;
510 
511 		if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
512 			continue;
513 
514 		/* don't output marks to recently written files */
515 		if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
516 			continue;
517 
518 		/*
519 		 * suppress duplicate lines to this file
520 		 */
521 		if ((flags & MARK) == 0 && msglen == f->f_prevlen &&
522 		    !strcmp(msg, f->f_prevline) &&
523 		    !strcmp(from, f->f_prevhost)) {
524 			(void) strncpy(f->f_lasttime, timestamp, 15);
525 			f->f_prevcount++;
526 			dprintf("msg repeated %d times, %ld sec of %d\n",
527 			    f->f_prevcount, now - f->f_time,
528 			    repeatinterval[f->f_repeatcount]);
529 			/*
530 			 * If domark would have logged this by now,
531 			 * flush it now (so we don't hold isolated messages),
532 			 * but back off so we'll flush less often
533 			 * in the future.
534 			 */
535 			if (now > REPEATTIME(f)) {
536 				fprintlog(f, flags, (char *)NULL);
537 				BACKOFF(f);
538 			}
539 		} else {
540 			/* new line, save it */
541 			if (f->f_prevcount)
542 				fprintlog(f, 0, (char *)NULL);
543 			f->f_repeatcount = 0;
544 			(void) strncpy(f->f_lasttime, timestamp, 15);
545 			(void) strncpy(f->f_prevhost, from,
546 					sizeof(f->f_prevhost));
547 			if (msglen < MAXSVLINE) {
548 				f->f_prevlen = msglen;
549 				f->f_prevpri = pri;
550 				(void) strcpy(f->f_prevline, msg);
551 				fprintlog(f, flags, (char *)NULL);
552 			} else {
553 				f->f_prevline[0] = 0;
554 				f->f_prevlen = 0;
555 				fprintlog(f, flags, msg);
556 			}
557 		}
558 	}
559 	(void) sigsetmask(omask);
560 }
561 
562 fprintlog(f, flags, msg)
563 	register struct filed *f;
564 	int flags;
565 	char *msg;
566 {
567 	struct iovec iov[6];
568 	register struct iovec *v = iov;
569 	register int l;
570 	char line[MAXLINE + 1];
571 	char repbuf[80];
572 
573 	v->iov_base = f->f_lasttime;
574 	v->iov_len = 15;
575 	v++;
576 	v->iov_base = " ";
577 	v->iov_len = 1;
578 	v++;
579 	v->iov_base = f->f_prevhost;
580 	v->iov_len = strlen(v->iov_base);
581 	v++;
582 	v->iov_base = " ";
583 	v->iov_len = 1;
584 	v++;
585 	if (msg) {
586 		v->iov_base = msg;
587 		v->iov_len = strlen(msg);
588 	} else if (f->f_prevcount > 1) {
589 		(void) sprintf(repbuf, "last message repeated %d times",
590 		    f->f_prevcount);
591 		v->iov_base = repbuf;
592 		v->iov_len = strlen(repbuf);
593 	} else {
594 		v->iov_base = f->f_prevline;
595 		v->iov_len = f->f_prevlen;
596 	}
597 	v++;
598 
599 	dprintf("Logging to %s", TypeNames[f->f_type]);
600 	f->f_time = now;
601 
602 	switch (f->f_type) {
603 	case F_UNUSED:
604 		dprintf("\n");
605 		break;
606 
607 	case F_FORW:
608 		dprintf(" %s\n", f->f_un.f_forw.f_hname);
609 		(void) sprintf(line, "<%d>%.15s %s", f->f_prevpri,
610 			iov[0].iov_base, iov[4].iov_base);
611 		l = strlen(line);
612 		if (l > MAXLINE)
613 			l = MAXLINE;
614 		if (sendto(finet, line, l, 0, &f->f_un.f_forw.f_addr,
615 		    sizeof f->f_un.f_forw.f_addr) != l) {
616 			int e = errno;
617 			(void) close(f->f_file);
618 			f->f_type = F_UNUSED;
619 			errno = e;
620 			logerror("sendto");
621 		}
622 		break;
623 
624 	case F_CONSOLE:
625 		if (flags & IGN_CONS) {
626 			dprintf(" (ignored)\n");
627 			break;
628 		}
629 		/* FALLTHROUGH */
630 
631 	case F_TTY:
632 	case F_FILE:
633 		dprintf(" %s\n", f->f_un.f_fname);
634 		if (f->f_type != F_FILE) {
635 			v->iov_base = "\r\n";
636 			v->iov_len = 2;
637 		} else {
638 			v->iov_base = "\n";
639 			v->iov_len = 1;
640 		}
641 	again:
642 		if (writev(f->f_file, iov, 6) < 0) {
643 			int e = errno;
644 			(void) close(f->f_file);
645 			/*
646 			 * Check for EBADF on TTY's due to vhangup() XXX
647 			 */
648 			if (e == EBADF && f->f_type != F_FILE) {
649 				f->f_file = open(f->f_un.f_fname, O_WRONLY|O_APPEND);
650 				if (f->f_file < 0) {
651 					f->f_type = F_UNUSED;
652 					logerror(f->f_un.f_fname);
653 				} else {
654 					untty();
655 					goto again;
656 				}
657 			} else {
658 				f->f_type = F_UNUSED;
659 				errno = e;
660 				logerror(f->f_un.f_fname);
661 			}
662 		} else if (flags & SYNC_FILE)
663 			(void) fsync(f->f_file);
664 		break;
665 
666 	case F_USERS:
667 	case F_WALL:
668 		dprintf("\n");
669 		v->iov_base = "\r\n";
670 		v->iov_len = 2;
671 		wallmsg(f, iov);
672 		break;
673 	}
674 	f->f_prevcount = 0;
675 }
676 
677 jmp_buf ttybuf;
678 
679 endtty()
680 {
681 	longjmp(ttybuf, 1);
682 }
683 
684 /*
685  *  WALLMSG -- Write a message to the world at large
686  *
687  *	Write the specified message to either the entire
688  *	world, or a list of approved users.
689  */
690 
691 wallmsg(f, iov)
692 	register struct filed *f;
693 	struct iovec *iov;
694 {
695 	register char *p;
696 	register int i;
697 	int ttyf, len;
698 	FILE *uf;
699 	static int reenter = 0;
700 	struct utmp ut;
701 	char greetings[200];
702 
703 	if (reenter++)
704 		return;
705 
706 	/* open the user login file */
707 	if ((uf = fopen("/etc/utmp", "r")) == NULL) {
708 		logerror("/etc/utmp");
709 		reenter = 0;
710 		return;
711 	}
712 
713 	/*
714 	 * Might as well fork instead of using nonblocking I/O
715 	 * and doing notty().
716 	 */
717 	if (fork() == 0) {
718 		(void) signal(SIGTERM, SIG_DFL);
719 		(void) alarm(0);
720 		(void) signal(SIGALRM, endtty);
721 		(void) signal(SIGTTOU, SIG_IGN);
722 		(void) sigsetmask(0);
723 		(void) sprintf(greetings,
724 		    "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
725 			iov[2].iov_base, ctime(&now));
726 		len = strlen(greetings);
727 
728 		/* scan the user login file */
729 		while (fread((char *) &ut, sizeof ut, 1, uf) == 1) {
730 			/* is this slot used? */
731 			if (ut.ut_name[0] == '\0')
732 				continue;
733 
734 			/* should we send the message to this user? */
735 			if (f->f_type == F_USERS) {
736 				for (i = 0; i < MAXUNAMES; i++) {
737 					if (!f->f_un.f_uname[i][0]) {
738 						i = MAXUNAMES;
739 						break;
740 					}
741 					if (strncmp(f->f_un.f_uname[i],
742 					    ut.ut_name, UNAMESZ) == 0)
743 						break;
744 				}
745 				if (i >= MAXUNAMES)
746 					continue;
747 			}
748 
749 			/* compute the device name */
750 			p = "/dev/12345678";
751 			strncpy(&p[5], ut.ut_line, UNAMESZ);
752 
753 			if (f->f_type == F_WALL) {
754 				iov[0].iov_base = greetings;
755 				iov[0].iov_len = len;
756 				iov[1].iov_len = 0;
757 			}
758 			if (setjmp(ttybuf) == 0) {
759 				(void) alarm(15);
760 				/* open the terminal */
761 				ttyf = open(p, O_WRONLY);
762 				if (ttyf >= 0) {
763 					struct stat statb;
764 
765 					if (fstat(ttyf, &statb) == 0 &&
766 					    (statb.st_mode & S_IWRITE))
767 						(void) writev(ttyf, iov, 6);
768 					close(ttyf);
769 					ttyf = -1;
770 				}
771 			}
772 			(void) alarm(0);
773 		}
774 		exit(0);
775 	}
776 	/* close the user login file */
777 	(void) fclose(uf);
778 	reenter = 0;
779 }
780 
781 reapchild()
782 {
783 	union wait status;
784 
785 	while (wait3(&status, WNOHANG, (struct rusage *) NULL) > 0)
786 		;
787 }
788 
789 /*
790  * Return a printable representation of a host address.
791  */
792 char *
793 cvthname(f)
794 	struct sockaddr_in *f;
795 {
796 	struct hostent *hp;
797 	register char *p;
798 	extern char *inet_ntoa();
799 
800 	dprintf("cvthname(%s)\n", inet_ntoa(f->sin_addr));
801 
802 	if (f->sin_family != AF_INET) {
803 		dprintf("Malformed from address\n");
804 		return ("???");
805 	}
806 	hp = gethostbyaddr(&f->sin_addr, sizeof(struct in_addr), f->sin_family);
807 	if (hp == 0) {
808 		dprintf("Host name for your address (%s) unknown\n",
809 			inet_ntoa(f->sin_addr));
810 		return (inet_ntoa(f->sin_addr));
811 	}
812 	if ((p = index(hp->h_name, '.')) && strcmp(p + 1, LocalDomain) == 0)
813 		*p = '\0';
814 	return (hp->h_name);
815 }
816 
817 domark()
818 {
819 	register struct filed *f;
820 
821 	now = time(0);
822 	MarkSeq += TIMERINTVL;
823 	if (MarkSeq >= MarkInterval) {
824 		logmsg(LOG_INFO, "-- MARK --", LocalHostName, ADDDATE|MARK);
825 		MarkSeq = 0;
826 	}
827 
828 	for (f = Files; f; f = f->f_next) {
829 		if (f->f_prevcount && now >= REPEATTIME(f)) {
830 			dprintf("flush %s: repeated %d times, %d sec.\n",
831 			    TypeNames[f->f_type], f->f_prevcount,
832 			    repeatinterval[f->f_repeatcount]);
833 			fprintlog(f, 0, (char *)NULL);
834 			BACKOFF(f);
835 		}
836 	}
837 	(void) alarm(TIMERINTVL);
838 }
839 
840 /*
841  * Print syslogd errors some place.
842  */
843 logerror(type)
844 	char *type;
845 {
846 	char buf[100];
847 
848 	if (errno == 0)
849 		(void) sprintf(buf, "syslogd: %s", type);
850 	else if ((unsigned) errno > sys_nerr)
851 		(void) sprintf(buf, "syslogd: %s: error %d", type, errno);
852 	else
853 		(void) sprintf(buf, "syslogd: %s: %s", type, sys_errlist[errno]);
854 	errno = 0;
855 	dprintf("%s\n", buf);
856 	logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
857 }
858 
859 die(sig)
860 {
861 	register struct filed *f;
862 	char buf[100];
863 
864 	for (f = Files; f != NULL; f = f->f_next) {
865 		/* flush any pending output */
866 		if (f->f_prevcount)
867 			fprintlog(f, 0, (char *)NULL);
868 	}
869 	if (sig) {
870 		dprintf("syslogd: exiting on signal %d\n", sig);
871 		(void) sprintf(buf, "exiting on signal %d", sig);
872 		errno = 0;
873 		logerror(buf);
874 	}
875 	(void) unlink(LogName);
876 	exit(0);
877 }
878 
879 /*
880  *  INIT -- Initialize syslogd from configuration table
881  */
882 
883 init()
884 {
885 	register int i;
886 	register FILE *cf;
887 	register struct filed *f, *next, **nextp;
888 	register char *p;
889 	char cline[BUFSIZ];
890 
891 	dprintf("init\n");
892 
893 	/*
894 	 *  Close all open log files.
895 	 */
896 	Initialized = 0;
897 	for (f = Files; f != NULL; f = next) {
898 		/* flush any pending output */
899 		if (f->f_prevcount)
900 			fprintlog(f, 0, (char *)NULL);
901 
902 		switch (f->f_type) {
903 		  case F_FILE:
904 		  case F_TTY:
905 		  case F_CONSOLE:
906 			(void) close(f->f_file);
907 			break;
908 		}
909 		next = f->f_next;
910 		free((char *) f);
911 	}
912 	Files = NULL;
913 	nextp = &Files;
914 
915 	/* open the configuration file */
916 	if ((cf = fopen(ConfFile, "r")) == NULL) {
917 		dprintf("cannot open %s\n", ConfFile);
918 		*nextp = (struct filed *)calloc(1, sizeof(*f));
919 		cfline("*.ERR\t/dev/console", *nextp);
920 		(*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
921 		cfline("*.PANIC\t*", (*nextp)->f_next);
922 		Initialized = 1;
923 		return;
924 	}
925 
926 	/*
927 	 *  Foreach line in the conf table, open that file.
928 	 */
929 	f = NULL;
930 	while (fgets(cline, sizeof cline, cf) != NULL) {
931 		/*
932 		 * check for end-of-section, comments, strip off trailing
933 		 * spaces and newline character.
934 		 */
935 		for (p = cline; isspace(*p); ++p);
936 		if (*p == NULL || *p == '#')
937 			continue;
938 		for (p = index(cline, '\0'); isspace(*--p););
939 		*++p = '\0';
940 		f = (struct filed *)calloc(1, sizeof(*f));
941 		*nextp = f;
942 		nextp = &f->f_next;
943 		cfline(cline, f);
944 	}
945 
946 	/* close the configuration file */
947 	(void) fclose(cf);
948 
949 	Initialized = 1;
950 
951 	if (Debug) {
952 		for (f = Files; f; f = f->f_next) {
953 			for (i = 0; i <= LOG_NFACILITIES; i++)
954 				if (f->f_pmask[i] == NOPRI)
955 					printf("X ");
956 				else
957 					printf("%d ", f->f_pmask[i]);
958 			printf("%s: ", TypeNames[f->f_type]);
959 			switch (f->f_type) {
960 			case F_FILE:
961 			case F_TTY:
962 			case F_CONSOLE:
963 				printf("%s", f->f_un.f_fname);
964 				break;
965 
966 			case F_FORW:
967 				printf("%s", f->f_un.f_forw.f_hname);
968 				break;
969 
970 			case F_USERS:
971 				for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
972 					printf("%s, ", f->f_un.f_uname[i]);
973 				break;
974 			}
975 			printf("\n");
976 		}
977 	}
978 
979 	logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
980 	dprintf("syslogd: restarted\n");
981 }
982 
983 /*
984  * Crack a configuration file line
985  */
986 
987 struct code {
988 	char	*c_name;
989 	int	c_val;
990 };
991 
992 struct code	PriNames[] = {
993 	"panic",	LOG_EMERG,
994 	"emerg",	LOG_EMERG,
995 	"alert",	LOG_ALERT,
996 	"crit",		LOG_CRIT,
997 	"err",		LOG_ERR,
998 	"error",	LOG_ERR,
999 	"warn",		LOG_WARNING,
1000 	"warning",	LOG_WARNING,
1001 	"notice",	LOG_NOTICE,
1002 	"info",		LOG_INFO,
1003 	"debug",	LOG_DEBUG,
1004 	"none",		NOPRI,
1005 	NULL,		-1
1006 };
1007 
1008 struct code	FacNames[] = {
1009 	"kern",		LOG_KERN,
1010 	"user",		LOG_USER,
1011 	"mail",		LOG_MAIL,
1012 	"daemon",	LOG_DAEMON,
1013 	"auth",		LOG_AUTH,
1014 	"security",	LOG_AUTH,
1015 	"mark",		LOG_MARK,
1016 	"syslog",	LOG_SYSLOG,
1017 	"lpr",		LOG_LPR,
1018 	"news",		LOG_NEWS,
1019 	"uucp",		LOG_UUCP,
1020 	"local0",	LOG_LOCAL0,
1021 	"local1",	LOG_LOCAL1,
1022 	"local2",	LOG_LOCAL2,
1023 	"local3",	LOG_LOCAL3,
1024 	"local4",	LOG_LOCAL4,
1025 	"local5",	LOG_LOCAL5,
1026 	"local6",	LOG_LOCAL6,
1027 	"local7",	LOG_LOCAL7,
1028 	NULL,		-1
1029 };
1030 
1031 cfline(line, f)
1032 	char *line;
1033 	register struct filed *f;
1034 {
1035 	register char *p;
1036 	register char *q;
1037 	register int i;
1038 	char *bp;
1039 	int pri;
1040 	struct hostent *hp;
1041 	char buf[MAXLINE];
1042 
1043 	dprintf("cfline(%s)\n", line);
1044 
1045 	errno = 0;	/* keep sys_errlist stuff out of logerror messages */
1046 
1047 	/* clear out file entry */
1048 	bzero((char *) f, sizeof *f);
1049 	for (i = 0; i <= LOG_NFACILITIES; i++)
1050 		f->f_pmask[i] = NOPRI;
1051 
1052 	/* scan through the list of selectors */
1053 	for (p = line; *p && *p != '\t';) {
1054 
1055 		/* find the end of this facility name list */
1056 		for (q = p; *q && *q != '\t' && *q++ != '.'; )
1057 			continue;
1058 
1059 		/* collect priority name */
1060 		for (bp = buf; *q && !index("\t,;", *q); )
1061 			*bp++ = *q++;
1062 		*bp = '\0';
1063 
1064 		/* skip cruft */
1065 		while (index(", ;", *q))
1066 			q++;
1067 
1068 		/* decode priority name */
1069 		pri = decode(buf, PriNames);
1070 		if (pri < 0) {
1071 			char xbuf[200];
1072 
1073 			(void) sprintf(xbuf, "unknown priority name \"%s\"", buf);
1074 			logerror(xbuf);
1075 			return;
1076 		}
1077 
1078 		/* scan facilities */
1079 		while (*p && !index("\t.;", *p)) {
1080 			for (bp = buf; *p && !index("\t,;.", *p); )
1081 				*bp++ = *p++;
1082 			*bp = '\0';
1083 			if (*buf == '*')
1084 				for (i = 0; i < LOG_NFACILITIES; i++)
1085 					f->f_pmask[i] = pri;
1086 			else {
1087 				i = decode(buf, FacNames);
1088 				if (i < 0) {
1089 					char xbuf[200];
1090 
1091 					(void) sprintf(xbuf, "unknown facility name \"%s\"", buf);
1092 					logerror(xbuf);
1093 					return;
1094 				}
1095 				f->f_pmask[i >> 3] = pri;
1096 			}
1097 			while (*p == ',' || *p == ' ')
1098 				p++;
1099 		}
1100 
1101 		p = q;
1102 	}
1103 
1104 	/* skip to action part */
1105 	while (*p == '\t')
1106 		p++;
1107 
1108 	switch (*p)
1109 	{
1110 	case '@':
1111 		if (!InetInuse)
1112 			break;
1113 		(void) strcpy(f->f_un.f_forw.f_hname, ++p);
1114 		hp = gethostbyname(p);
1115 		if (hp == NULL) {
1116 			extern int h_errno, h_nerr;
1117 			extern char **h_errlist;
1118 
1119 			logerror((u_int)h_errno < h_nerr ?
1120 			    h_errlist[h_errno] : "Unknown error");
1121 			break;
1122 		}
1123 		bzero((char *) &f->f_un.f_forw.f_addr,
1124 			 sizeof f->f_un.f_forw.f_addr);
1125 		f->f_un.f_forw.f_addr.sin_family = AF_INET;
1126 		f->f_un.f_forw.f_addr.sin_port = LogPort;
1127 		bcopy(hp->h_addr, (char *) &f->f_un.f_forw.f_addr.sin_addr, hp->h_length);
1128 		f->f_type = F_FORW;
1129 		break;
1130 
1131 	case '/':
1132 		(void) strcpy(f->f_un.f_fname, p);
1133 		if ((f->f_file = open(p, O_WRONLY|O_APPEND)) < 0) {
1134 			f->f_file = F_UNUSED;
1135 			logerror(p);
1136 			break;
1137 		}
1138 		if (isatty(f->f_file)) {
1139 			f->f_type = F_TTY;
1140 			untty();
1141 		}
1142 		else
1143 			f->f_type = F_FILE;
1144 		if (strcmp(p, ctty) == 0)
1145 			f->f_type = F_CONSOLE;
1146 		break;
1147 
1148 	case '*':
1149 		f->f_type = F_WALL;
1150 		break;
1151 
1152 	default:
1153 		for (i = 0; i < MAXUNAMES && *p; i++) {
1154 			for (q = p; *q && *q != ','; )
1155 				q++;
1156 			(void) strncpy(f->f_un.f_uname[i], p, UNAMESZ);
1157 			if ((q - p) > UNAMESZ)
1158 				f->f_un.f_uname[i][UNAMESZ] = '\0';
1159 			else
1160 				f->f_un.f_uname[i][q - p] = '\0';
1161 			while (*q == ',' || *q == ' ')
1162 				q++;
1163 			p = q;
1164 		}
1165 		f->f_type = F_USERS;
1166 		break;
1167 	}
1168 }
1169 
1170 
1171 /*
1172  *  Decode a symbolic name to a numeric value
1173  */
1174 
1175 decode(name, codetab)
1176 	char *name;
1177 	struct code *codetab;
1178 {
1179 	register struct code *c;
1180 	register char *p;
1181 	char buf[40];
1182 
1183 	if (isdigit(*name))
1184 		return (atoi(name));
1185 
1186 	(void) strcpy(buf, name);
1187 	for (p = buf; *p; p++)
1188 		if (isupper(*p))
1189 			*p = tolower(*p);
1190 	for (c = codetab; c->c_name; c++)
1191 		if (!strcmp(buf, c->c_name))
1192 			return (c->c_val);
1193 
1194 	return (-1);
1195 }
1196