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