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