xref: /original-bsd/usr.sbin/syslogd/syslogd.c (revision ca3b5b26)
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.31 (Berkeley) 04/02/89";
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 <sys/param.h>
57 #include <sys/syslog.h>
58 #include <sys/errno.h>
59 #include <sys/ioctl.h>
60 #include <sys/stat.h>
61 #include <sys/wait.h>
62 #include <sys/socket.h>
63 #include <sys/file.h>
64 #include <sys/msgbuf.h>
65 #include <sys/uio.h>
66 #include <sys/un.h>
67 #include <sys/time.h>
68 #include <sys/resource.h>
69 #include <sys/signal.h>
70 
71 #include <netinet/in.h>
72 #include <netdb.h>
73 
74 #include <utmp.h>
75 #include <setjmp.h>
76 #include <stdio.h>
77 #include <ctype.h>
78 #include <strings.h>
79 #include "pathnames.h"
80 
81 char	*LogName = _PATH_LOG;
82 char	*ConfFile = _PATH_LOGCONF;
83 char	*PidFile = _PATH_LOGPID;
84 char	ctty[] = _PATH_CONSOLE;
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 	bzero((char *)&sunx, sizeof(sunx));
243 	sunx.sun_family = AF_UNIX;
244 	(void) strncpy(sunx.sun_path, LogName, sizeof sunx.sun_path);
245 	funix = socket(AF_UNIX, SOCK_DGRAM, 0);
246 	if (funix < 0 || bind(funix, (struct sockaddr *) &sunx,
247 	    sizeof(sunx.sun_family)+sizeof(sunx.sun_len)+
248 	    strlen(sunx.sun_path)) < 0 ||
249 	    chmod(LogName, 0666) < 0) {
250 		(void) sprintf(line, "cannot create %s", LogName);
251 		logerror(line);
252 		dprintf("cannot create %s (%d)\n", LogName, errno);
253 		die(0);
254 	}
255 	finet = socket(AF_INET, SOCK_DGRAM, 0);
256 	if (finet >= 0) {
257 		struct servent *sp;
258 
259 		sp = getservbyname("syslog", "udp");
260 		if (sp == NULL) {
261 			errno = 0;
262 			logerror("syslog/udp: unknown service");
263 			die(0);
264 		}
265 		sin.sin_family = AF_INET;
266 		sin.sin_port = LogPort = sp->s_port;
267 		if (bind(finet, &sin, sizeof(sin)) < 0) {
268 			logerror("bind");
269 			if (!Debug)
270 				die(0);
271 		} else {
272 			inetm = FDMASK(finet);
273 			InetInuse = 1;
274 		}
275 	}
276 	if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) >= 0)
277 		klogm = FDMASK(fklog);
278 	else {
279 		dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
280 		klogm = 0;
281 	}
282 
283 	/* tuck my process id away */
284 	fp = fopen(PidFile, "w");
285 	if (fp != NULL) {
286 		fprintf(fp, "%d\n", getpid());
287 		(void) fclose(fp);
288 	}
289 
290 	dprintf("off & running....\n");
291 
292 	init();
293 	(void) signal(SIGHUP, init);
294 
295 	for (;;) {
296 		int nfds, readfds = FDMASK(funix) | inetm | klogm;
297 
298 		errno = 0;
299 		dprintf("readfds = %#x\n", readfds);
300 		nfds = select(20, (fd_set *) &readfds, (fd_set *) NULL,
301 				  (fd_set *) NULL, (struct timeval *) NULL);
302 		if (nfds == 0)
303 			continue;
304 		if (nfds < 0) {
305 			if (errno != EINTR)
306 				logerror("select");
307 			continue;
308 		}
309 		dprintf("got a message (%d, %#x)\n", nfds, readfds);
310 		if (readfds & klogm) {
311 			i = read(fklog, line, sizeof(line) - 1);
312 			if (i > 0) {
313 				line[i] = '\0';
314 				printsys(line);
315 			} else if (i < 0 && errno != EINTR) {
316 				logerror("klog");
317 				fklog = -1;
318 				klogm = 0;
319 			}
320 		}
321 		if (readfds & FDMASK(funix)) {
322 			len = sizeof fromunix;
323 			i = recvfrom(funix, line, MAXLINE, 0,
324 				     (struct sockaddr *) &fromunix, &len);
325 			if (i > 0) {
326 				line[i] = '\0';
327 				printline(LocalHostName, line);
328 			} else if (i < 0 && errno != EINTR)
329 				logerror("recvfrom unix");
330 		}
331 		if (readfds & inetm) {
332 			len = sizeof frominet;
333 			i = recvfrom(finet, line, MAXLINE, 0, &frominet, &len);
334 			if (i > 0) {
335 				extern char *cvthname();
336 
337 				line[i] = '\0';
338 				printline(cvthname(&frominet), line);
339 			} else if (i < 0 && errno != EINTR)
340 				logerror("recvfrom inet");
341 		}
342 	}
343 }
344 
345 usage()
346 {
347 	fprintf(stderr, "usage: syslogd [-d] [-m markinterval] [-p path] [-f conffile]\n");
348 	exit(1);
349 }
350 
351 untty()
352 {
353 	int i;
354 
355 	if (!Debug) {
356 		i = open("/dev/tty", O_RDWR);
357 		if (i >= 0) {
358 			(void) ioctl(i, (int) TIOCNOTTY, (char *)0);
359 			(void) close(i);
360 		}
361 	}
362 }
363 
364 /*
365  * Take a raw input line, decode the message, and print the message
366  * on the appropriate log files.
367  */
368 
369 printline(hname, msg)
370 	char *hname;
371 	char *msg;
372 {
373 	register char *p, *q;
374 	register int c;
375 	char line[MAXLINE + 1];
376 	int pri;
377 
378 	/* test for special codes */
379 	pri = DEFUPRI;
380 	p = msg;
381 	if (*p == '<') {
382 		pri = 0;
383 		while (isdigit(*++p))
384 			pri = 10 * pri + (*p - '0');
385 		if (*p == '>')
386 			++p;
387 	}
388 	if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
389 		pri = DEFUPRI;
390 
391 	/* don't allow users to log kernel messages */
392 	if (LOG_FAC(pri) == LOG_KERN)
393 		pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
394 
395 	q = line;
396 
397 	while ((c = *p++ & 0177) != '\0' &&
398 	    q < &line[sizeof(line) - 1])
399 		if (iscntrl(c))
400 			if (c == '\n')
401 				*q++ = ' ';
402 			else if (c == '\t')
403 				*q++ = '\t';
404 			else {
405 				*q++ = '^';
406 				*q++ = c ^ 0100;
407 			}
408 		else
409 			*q++ = c;
410 	*q = '\0';
411 
412 	logmsg(pri, line, hname, 0);
413 }
414 
415 /*
416  * Take a raw input line from /dev/klog, split and format similar to syslog().
417  */
418 
419 printsys(msg)
420 	char *msg;
421 {
422 	register char *p, *q;
423 	register int c;
424 	char line[MAXLINE + 1];
425 	int pri, flags;
426 	char *lp;
427 
428 	(void) sprintf(line, "vmunix: ");
429 	lp = line + strlen(line);
430 	for (p = msg; *p != '\0'; ) {
431 		flags = SYNC_FILE | ADDDATE;	/* fsync file after write */
432 		pri = DEFSPRI;
433 		if (*p == '<') {
434 			pri = 0;
435 			while (isdigit(*++p))
436 				pri = 10 * pri + (*p - '0');
437 			if (*p == '>')
438 				++p;
439 		} else {
440 			/* kernel printf's come out on console */
441 			flags |= IGN_CONS;
442 		}
443 		if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
444 			pri = DEFSPRI;
445 		q = lp;
446 		while (*p != '\0' && (c = *p++) != '\n' &&
447 		    q < &line[MAXLINE])
448 			*q++ = c;
449 		*q = '\0';
450 		logmsg(pri, line, LocalHostName, flags);
451 	}
452 }
453 
454 time_t	now;
455 
456 /*
457  * Log a message to the appropriate log files, users, etc. based on
458  * the priority.
459  */
460 
461 logmsg(pri, msg, from, flags)
462 	int pri;
463 	char *msg, *from;
464 	int flags;
465 {
466 	register struct filed *f;
467 	int fac, prilev;
468 	int omask, msglen;
469 	char *timestamp;
470 
471 	dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n", pri, flags, from, msg);
472 
473 	omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
474 
475 	/*
476 	 * Check to see if msg looks non-standard.
477 	 */
478 	msglen = strlen(msg);
479 	if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
480 	    msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
481 		flags |= ADDDATE;
482 
483 	(void) time(&now);
484 	if (flags & ADDDATE)
485 		timestamp = ctime(&now) + 4;
486 	else {
487 		timestamp = msg;
488 		msg += 16;
489 		msglen -= 16;
490 	}
491 
492 	/* extract facility and priority level */
493 	if (flags & MARK)
494 		fac = LOG_NFACILITIES;
495 	else
496 		fac = LOG_FAC(pri);
497 	prilev = LOG_PRI(pri);
498 
499 	/* log the message to the particular outputs */
500 	if (!Initialized) {
501 		f = &consfile;
502 		f->f_file = open(ctty, O_WRONLY);
503 
504 		if (f->f_file >= 0) {
505 			untty();
506 			fprintlog(f, flags, msg);
507 			(void) close(f->f_file);
508 		}
509 		(void) sigsetmask(omask);
510 		return;
511 	}
512 	for (f = Files; f; f = f->f_next) {
513 		/* skip messages that are incorrect priority */
514 		if (f->f_pmask[fac] < prilev || f->f_pmask[fac] == NOPRI)
515 			continue;
516 
517 		if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
518 			continue;
519 
520 		/* don't output marks to recently written files */
521 		if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
522 			continue;
523 
524 		/*
525 		 * suppress duplicate lines to this file
526 		 */
527 		if ((flags & MARK) == 0 && msglen == f->f_prevlen &&
528 		    !strcmp(msg, f->f_prevline) &&
529 		    !strcmp(from, f->f_prevhost)) {
530 			(void) strncpy(f->f_lasttime, timestamp, 15);
531 			f->f_prevcount++;
532 			dprintf("msg repeated %d times, %ld sec of %d\n",
533 			    f->f_prevcount, now - f->f_time,
534 			    repeatinterval[f->f_repeatcount]);
535 			/*
536 			 * If domark would have logged this by now,
537 			 * flush it now (so we don't hold isolated messages),
538 			 * but back off so we'll flush less often
539 			 * in the future.
540 			 */
541 			if (now > REPEATTIME(f)) {
542 				fprintlog(f, flags, (char *)NULL);
543 				BACKOFF(f);
544 			}
545 		} else {
546 			/* new line, save it */
547 			if (f->f_prevcount)
548 				fprintlog(f, 0, (char *)NULL);
549 			f->f_repeatcount = 0;
550 			(void) strncpy(f->f_lasttime, timestamp, 15);
551 			(void) strncpy(f->f_prevhost, from,
552 					sizeof(f->f_prevhost));
553 			if (msglen < MAXSVLINE) {
554 				f->f_prevlen = msglen;
555 				f->f_prevpri = pri;
556 				(void) strcpy(f->f_prevline, msg);
557 				fprintlog(f, flags, (char *)NULL);
558 			} else {
559 				f->f_prevline[0] = 0;
560 				f->f_prevlen = 0;
561 				fprintlog(f, flags, msg);
562 			}
563 		}
564 	}
565 	(void) sigsetmask(omask);
566 }
567 
568 fprintlog(f, flags, msg)
569 	register struct filed *f;
570 	int flags;
571 	char *msg;
572 {
573 	struct iovec iov[6];
574 	register struct iovec *v = iov;
575 	register int l;
576 	char line[MAXLINE + 1];
577 	char repbuf[80];
578 
579 	v->iov_base = f->f_lasttime;
580 	v->iov_len = 15;
581 	v++;
582 	v->iov_base = " ";
583 	v->iov_len = 1;
584 	v++;
585 	v->iov_base = f->f_prevhost;
586 	v->iov_len = strlen(v->iov_base);
587 	v++;
588 	v->iov_base = " ";
589 	v->iov_len = 1;
590 	v++;
591 	if (msg) {
592 		v->iov_base = msg;
593 		v->iov_len = strlen(msg);
594 	} else if (f->f_prevcount > 1) {
595 		(void) sprintf(repbuf, "last message repeated %d times",
596 		    f->f_prevcount);
597 		v->iov_base = repbuf;
598 		v->iov_len = strlen(repbuf);
599 	} else {
600 		v->iov_base = f->f_prevline;
601 		v->iov_len = f->f_prevlen;
602 	}
603 	v++;
604 
605 	dprintf("Logging to %s", TypeNames[f->f_type]);
606 	f->f_time = now;
607 
608 	switch (f->f_type) {
609 	case F_UNUSED:
610 		dprintf("\n");
611 		break;
612 
613 	case F_FORW:
614 		dprintf(" %s\n", f->f_un.f_forw.f_hname);
615 		(void) sprintf(line, "<%d>%.15s %s", f->f_prevpri,
616 			iov[0].iov_base, iov[4].iov_base);
617 		l = strlen(line);
618 		if (l > MAXLINE)
619 			l = MAXLINE;
620 		if (sendto(finet, line, l, 0, &f->f_un.f_forw.f_addr,
621 		    sizeof f->f_un.f_forw.f_addr) != l) {
622 			int e = errno;
623 			(void) close(f->f_file);
624 			f->f_type = F_UNUSED;
625 			errno = e;
626 			logerror("sendto");
627 		}
628 		break;
629 
630 	case F_CONSOLE:
631 		if (flags & IGN_CONS) {
632 			dprintf(" (ignored)\n");
633 			break;
634 		}
635 		/* FALLTHROUGH */
636 
637 	case F_TTY:
638 	case F_FILE:
639 		dprintf(" %s\n", f->f_un.f_fname);
640 		if (f->f_type != F_FILE) {
641 			v->iov_base = "\r\n";
642 			v->iov_len = 2;
643 		} else {
644 			v->iov_base = "\n";
645 			v->iov_len = 1;
646 		}
647 	again:
648 		if (writev(f->f_file, iov, 6) < 0) {
649 			int e = errno;
650 			(void) close(f->f_file);
651 			/*
652 			 * Check for EBADF on TTY's due to vhangup() XXX
653 			 */
654 			if (e == EBADF && f->f_type != F_FILE) {
655 				f->f_file = open(f->f_un.f_fname, O_WRONLY|O_APPEND);
656 				if (f->f_file < 0) {
657 					f->f_type = F_UNUSED;
658 					logerror(f->f_un.f_fname);
659 				} else {
660 					untty();
661 					goto again;
662 				}
663 			} else {
664 				f->f_type = F_UNUSED;
665 				errno = e;
666 				logerror(f->f_un.f_fname);
667 			}
668 		} else if (flags & SYNC_FILE)
669 			(void) fsync(f->f_file);
670 		break;
671 
672 	case F_USERS:
673 	case F_WALL:
674 		dprintf("\n");
675 		v->iov_base = "\r\n";
676 		v->iov_len = 2;
677 		wallmsg(f, iov);
678 		break;
679 	}
680 	f->f_prevcount = 0;
681 }
682 
683 jmp_buf ttybuf;
684 
685 endtty()
686 {
687 	longjmp(ttybuf, 1);
688 }
689 
690 /*
691  *  WALLMSG -- Write a message to the world at large
692  *
693  *	Write the specified message to either the entire
694  *	world, or a list of approved users.
695  */
696 
697 wallmsg(f, iov)
698 	register struct filed *f;
699 	struct iovec *iov;
700 {
701 	register char *p;
702 	register int i;
703 	int ttyf, len;
704 	FILE *uf;
705 	static int reenter = 0;
706 	struct utmp ut;
707 	char greetings[200];
708 
709 	if (reenter++)
710 		return;
711 
712 	/* open the user login file */
713 	if ((uf = fopen(_PATH_UTMP, "r")) == NULL) {
714 		logerror(_PATH_UTMP);
715 		reenter = 0;
716 		return;
717 	}
718 
719 	/*
720 	 * Might as well fork instead of using nonblocking I/O
721 	 * and doing notty().
722 	 */
723 	if (fork() == 0) {
724 		(void) signal(SIGTERM, SIG_DFL);
725 		(void) alarm(0);
726 		(void) signal(SIGALRM, endtty);
727 		(void) signal(SIGTTOU, SIG_IGN);
728 		(void) sigsetmask(0);
729 		(void) sprintf(greetings,
730 		    "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
731 			iov[2].iov_base, ctime(&now));
732 		len = strlen(greetings);
733 
734 		/* scan the user login file */
735 		while (fread((char *) &ut, sizeof ut, 1, uf) == 1) {
736 			/* is this slot used? */
737 			if (ut.ut_name[0] == '\0')
738 				continue;
739 
740 			/* should we send the message to this user? */
741 			if (f->f_type == F_USERS) {
742 				for (i = 0; i < MAXUNAMES; i++) {
743 					if (!f->f_un.f_uname[i][0]) {
744 						i = MAXUNAMES;
745 						break;
746 					}
747 					if (strncmp(f->f_un.f_uname[i],
748 					    ut.ut_name, UNAMESZ) == 0)
749 						break;
750 				}
751 				if (i >= MAXUNAMES)
752 					continue;
753 			}
754 
755 			/* compute the device name */
756 			p = "/dev/12345678";
757 			strncpy(&p[5], ut.ut_line, UNAMESZ);
758 
759 			if (f->f_type == F_WALL) {
760 				iov[0].iov_base = greetings;
761 				iov[0].iov_len = len;
762 				iov[1].iov_len = 0;
763 			}
764 			if (setjmp(ttybuf) == 0) {
765 				(void) alarm(15);
766 				/* open the terminal */
767 				ttyf = open(p, O_WRONLY);
768 				if (ttyf >= 0) {
769 					struct stat statb;
770 
771 					if (fstat(ttyf, &statb) == 0 &&
772 					    (statb.st_mode & S_IWRITE))
773 						(void) writev(ttyf, iov, 6);
774 					close(ttyf);
775 					ttyf = -1;
776 				}
777 			}
778 			(void) alarm(0);
779 		}
780 		exit(0);
781 	}
782 	/* close the user login file */
783 	(void) fclose(uf);
784 	reenter = 0;
785 }
786 
787 reapchild()
788 {
789 	union wait status;
790 
791 	while (wait3(&status, WNOHANG, (struct rusage *) NULL) > 0)
792 		;
793 }
794 
795 /*
796  * Return a printable representation of a host address.
797  */
798 char *
799 cvthname(f)
800 	struct sockaddr_in *f;
801 {
802 	struct hostent *hp;
803 	register char *p;
804 	extern char *inet_ntoa();
805 
806 	dprintf("cvthname(%s)\n", inet_ntoa(f->sin_addr));
807 
808 	if (f->sin_family != AF_INET) {
809 		dprintf("Malformed from address\n");
810 		return ("???");
811 	}
812 	hp = gethostbyaddr(&f->sin_addr, sizeof(struct in_addr), f->sin_family);
813 	if (hp == 0) {
814 		dprintf("Host name for your address (%s) unknown\n",
815 			inet_ntoa(f->sin_addr));
816 		return (inet_ntoa(f->sin_addr));
817 	}
818 	if ((p = index(hp->h_name, '.')) && strcmp(p + 1, LocalDomain) == 0)
819 		*p = '\0';
820 	return (hp->h_name);
821 }
822 
823 domark()
824 {
825 	register struct filed *f;
826 
827 	now = time(0);
828 	MarkSeq += TIMERINTVL;
829 	if (MarkSeq >= MarkInterval) {
830 		logmsg(LOG_INFO, "-- MARK --", LocalHostName, ADDDATE|MARK);
831 		MarkSeq = 0;
832 	}
833 
834 	for (f = Files; f; f = f->f_next) {
835 		if (f->f_prevcount && now >= REPEATTIME(f)) {
836 			dprintf("flush %s: repeated %d times, %d sec.\n",
837 			    TypeNames[f->f_type], f->f_prevcount,
838 			    repeatinterval[f->f_repeatcount]);
839 			fprintlog(f, 0, (char *)NULL);
840 			BACKOFF(f);
841 		}
842 	}
843 	(void) alarm(TIMERINTVL);
844 }
845 
846 /*
847  * Print syslogd errors some place.
848  */
849 logerror(type)
850 	char *type;
851 {
852 	char buf[100];
853 
854 	if (errno == 0)
855 		(void) sprintf(buf, "syslogd: %s", type);
856 	else if ((unsigned) errno > sys_nerr)
857 		(void) sprintf(buf, "syslogd: %s: error %d", type, errno);
858 	else
859 		(void) sprintf(buf, "syslogd: %s: %s", type, sys_errlist[errno]);
860 	errno = 0;
861 	dprintf("%s\n", buf);
862 	logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
863 }
864 
865 die(sig)
866 {
867 	register struct filed *f;
868 	char buf[100];
869 
870 	for (f = Files; f != NULL; f = f->f_next) {
871 		/* flush any pending output */
872 		if (f->f_prevcount)
873 			fprintlog(f, 0, (char *)NULL);
874 	}
875 	if (sig) {
876 		dprintf("syslogd: exiting on signal %d\n", sig);
877 		(void) sprintf(buf, "exiting on signal %d", sig);
878 		errno = 0;
879 		logerror(buf);
880 	}
881 	(void) unlink(LogName);
882 	exit(0);
883 }
884 
885 /*
886  *  INIT -- Initialize syslogd from configuration table
887  */
888 
889 init()
890 {
891 	register int i;
892 	register FILE *cf;
893 	register struct filed *f, *next, **nextp;
894 	register char *p;
895 	char cline[BUFSIZ];
896 
897 	dprintf("init\n");
898 
899 	/*
900 	 *  Close all open log files.
901 	 */
902 	Initialized = 0;
903 	for (f = Files; f != NULL; f = next) {
904 		/* flush any pending output */
905 		if (f->f_prevcount)
906 			fprintlog(f, 0, (char *)NULL);
907 
908 		switch (f->f_type) {
909 		  case F_FILE:
910 		  case F_TTY:
911 		  case F_CONSOLE:
912 		  case F_FORW:
913 			(void) close(f->f_file);
914 			break;
915 		}
916 		next = f->f_next;
917 		free((char *) f);
918 	}
919 	Files = NULL;
920 	nextp = &Files;
921 
922 	/* open the configuration file */
923 	if ((cf = fopen(ConfFile, "r")) == NULL) {
924 		dprintf("cannot open %s\n", ConfFile);
925 		*nextp = (struct filed *)calloc(1, sizeof(*f));
926 		cfline("*.ERR\t/dev/console", *nextp);
927 		(*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
928 		cfline("*.PANIC\t*", (*nextp)->f_next);
929 		Initialized = 1;
930 		return;
931 	}
932 
933 	/*
934 	 *  Foreach line in the conf table, open that file.
935 	 */
936 	f = NULL;
937 	while (fgets(cline, sizeof cline, cf) != NULL) {
938 		/*
939 		 * check for end-of-section, comments, strip off trailing
940 		 * spaces and newline character.
941 		 */
942 		for (p = cline; isspace(*p); ++p);
943 		if (*p == NULL || *p == '#')
944 			continue;
945 		for (p = index(cline, '\0'); isspace(*--p););
946 		*++p = '\0';
947 		f = (struct filed *)calloc(1, sizeof(*f));
948 		*nextp = f;
949 		nextp = &f->f_next;
950 		cfline(cline, f);
951 	}
952 
953 	/* close the configuration file */
954 	(void) fclose(cf);
955 
956 	Initialized = 1;
957 
958 	if (Debug) {
959 		for (f = Files; f; f = f->f_next) {
960 			for (i = 0; i <= LOG_NFACILITIES; i++)
961 				if (f->f_pmask[i] == NOPRI)
962 					printf("X ");
963 				else
964 					printf("%d ", f->f_pmask[i]);
965 			printf("%s: ", TypeNames[f->f_type]);
966 			switch (f->f_type) {
967 			case F_FILE:
968 			case F_TTY:
969 			case F_CONSOLE:
970 				printf("%s", f->f_un.f_fname);
971 				break;
972 
973 			case F_FORW:
974 				printf("%s", f->f_un.f_forw.f_hname);
975 				break;
976 
977 			case F_USERS:
978 				for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
979 					printf("%s, ", f->f_un.f_uname[i]);
980 				break;
981 			}
982 			printf("\n");
983 		}
984 	}
985 
986 	logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
987 	dprintf("syslogd: restarted\n");
988 }
989 
990 /*
991  * Crack a configuration file line
992  */
993 
994 struct code {
995 	char	*c_name;
996 	int	c_val;
997 };
998 
999 struct code	PriNames[] = {
1000 	"panic",	LOG_EMERG,
1001 	"emerg",	LOG_EMERG,
1002 	"alert",	LOG_ALERT,
1003 	"crit",		LOG_CRIT,
1004 	"err",		LOG_ERR,
1005 	"error",	LOG_ERR,
1006 	"warn",		LOG_WARNING,
1007 	"warning",	LOG_WARNING,
1008 	"notice",	LOG_NOTICE,
1009 	"info",		LOG_INFO,
1010 	"debug",	LOG_DEBUG,
1011 	"none",		NOPRI,
1012 	NULL,		-1
1013 };
1014 
1015 struct code	FacNames[] = {
1016 	"kern",		LOG_KERN,
1017 	"user",		LOG_USER,
1018 	"mail",		LOG_MAIL,
1019 	"daemon",	LOG_DAEMON,
1020 	"auth",		LOG_AUTH,
1021 	"security",	LOG_AUTH,
1022 	"mark",		LOG_MARK,
1023 	"syslog",	LOG_SYSLOG,
1024 	"lpr",		LOG_LPR,
1025 	"news",		LOG_NEWS,
1026 	"uucp",		LOG_UUCP,
1027 	"local0",	LOG_LOCAL0,
1028 	"local1",	LOG_LOCAL1,
1029 	"local2",	LOG_LOCAL2,
1030 	"local3",	LOG_LOCAL3,
1031 	"local4",	LOG_LOCAL4,
1032 	"local5",	LOG_LOCAL5,
1033 	"local6",	LOG_LOCAL6,
1034 	"local7",	LOG_LOCAL7,
1035 	NULL,		-1
1036 };
1037 
1038 cfline(line, f)
1039 	char *line;
1040 	register struct filed *f;
1041 {
1042 	register char *p;
1043 	register char *q;
1044 	register int i;
1045 	char *bp;
1046 	int pri;
1047 	struct hostent *hp;
1048 	char buf[MAXLINE];
1049 
1050 	dprintf("cfline(%s)\n", line);
1051 
1052 	errno = 0;	/* keep sys_errlist stuff out of logerror messages */
1053 
1054 	/* clear out file entry */
1055 	bzero((char *) f, sizeof *f);
1056 	for (i = 0; i <= LOG_NFACILITIES; i++)
1057 		f->f_pmask[i] = NOPRI;
1058 
1059 	/* scan through the list of selectors */
1060 	for (p = line; *p && *p != '\t';) {
1061 
1062 		/* find the end of this facility name list */
1063 		for (q = p; *q && *q != '\t' && *q++ != '.'; )
1064 			continue;
1065 
1066 		/* collect priority name */
1067 		for (bp = buf; *q && !index("\t,;", *q); )
1068 			*bp++ = *q++;
1069 		*bp = '\0';
1070 
1071 		/* skip cruft */
1072 		while (index(", ;", *q))
1073 			q++;
1074 
1075 		/* decode priority name */
1076 		pri = decode(buf, PriNames);
1077 		if (pri < 0) {
1078 			char xbuf[200];
1079 
1080 			(void) sprintf(xbuf, "unknown priority name \"%s\"", buf);
1081 			logerror(xbuf);
1082 			return;
1083 		}
1084 
1085 		/* scan facilities */
1086 		while (*p && !index("\t.;", *p)) {
1087 			for (bp = buf; *p && !index("\t,;.", *p); )
1088 				*bp++ = *p++;
1089 			*bp = '\0';
1090 			if (*buf == '*')
1091 				for (i = 0; i < LOG_NFACILITIES; i++)
1092 					f->f_pmask[i] = pri;
1093 			else {
1094 				i = decode(buf, FacNames);
1095 				if (i < 0) {
1096 					char xbuf[200];
1097 
1098 					(void) sprintf(xbuf, "unknown facility name \"%s\"", buf);
1099 					logerror(xbuf);
1100 					return;
1101 				}
1102 				f->f_pmask[i >> 3] = pri;
1103 			}
1104 			while (*p == ',' || *p == ' ')
1105 				p++;
1106 		}
1107 
1108 		p = q;
1109 	}
1110 
1111 	/* skip to action part */
1112 	while (*p == '\t')
1113 		p++;
1114 
1115 	switch (*p)
1116 	{
1117 	case '@':
1118 		if (!InetInuse)
1119 			break;
1120 		(void) strcpy(f->f_un.f_forw.f_hname, ++p);
1121 		hp = gethostbyname(p);
1122 		if (hp == NULL) {
1123 			extern int h_errno, h_nerr;
1124 			extern char **h_errlist;
1125 
1126 			logerror((u_int)h_errno < h_nerr ?
1127 			    h_errlist[h_errno] : "Unknown error");
1128 			break;
1129 		}
1130 		bzero((char *) &f->f_un.f_forw.f_addr,
1131 			 sizeof f->f_un.f_forw.f_addr);
1132 		f->f_un.f_forw.f_addr.sin_family = AF_INET;
1133 		f->f_un.f_forw.f_addr.sin_port = LogPort;
1134 		bcopy(hp->h_addr, (char *) &f->f_un.f_forw.f_addr.sin_addr, hp->h_length);
1135 		f->f_type = F_FORW;
1136 		break;
1137 
1138 	case '/':
1139 		(void) strcpy(f->f_un.f_fname, p);
1140 		if ((f->f_file = open(p, O_WRONLY|O_APPEND)) < 0) {
1141 			f->f_file = F_UNUSED;
1142 			logerror(p);
1143 			break;
1144 		}
1145 		if (isatty(f->f_file)) {
1146 			f->f_type = F_TTY;
1147 			untty();
1148 		}
1149 		else
1150 			f->f_type = F_FILE;
1151 		if (strcmp(p, ctty) == 0)
1152 			f->f_type = F_CONSOLE;
1153 		break;
1154 
1155 	case '*':
1156 		f->f_type = F_WALL;
1157 		break;
1158 
1159 	default:
1160 		for (i = 0; i < MAXUNAMES && *p; i++) {
1161 			for (q = p; *q && *q != ','; )
1162 				q++;
1163 			(void) strncpy(f->f_un.f_uname[i], p, UNAMESZ);
1164 			if ((q - p) > UNAMESZ)
1165 				f->f_un.f_uname[i][UNAMESZ] = '\0';
1166 			else
1167 				f->f_un.f_uname[i][q - p] = '\0';
1168 			while (*q == ',' || *q == ' ')
1169 				q++;
1170 			p = q;
1171 		}
1172 		f->f_type = F_USERS;
1173 		break;
1174 	}
1175 }
1176 
1177 
1178 /*
1179  *  Decode a symbolic name to a numeric value
1180  */
1181 
1182 decode(name, codetab)
1183 	char *name;
1184 	struct code *codetab;
1185 {
1186 	register struct code *c;
1187 	register char *p;
1188 	char buf[40];
1189 
1190 	if (isdigit(*name))
1191 		return (atoi(name));
1192 
1193 	(void) strcpy(buf, name);
1194 	for (p = buf; *p; p++)
1195 		if (isupper(*p))
1196 			*p = tolower(*p);
1197 	for (c = codetab; c->c_name; c++)
1198 		if (!strcmp(buf, c->c_name))
1199 			return (c->c_val);
1200 
1201 	return (-1);
1202 }
1203