syslogd.c revision 1.30 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.30 1999/12/02 16:17:30 itojun 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/poll.h>
85 #include <sys/un.h>
86 #include <sys/time.h>
87 #include <sys/resource.h>
88 #include <sys/sysctl.h>
89
90 #include <netinet/in.h>
91 #include <netdb.h>
92 #include <arpa/inet.h>
93
94 #include <ctype.h>
95 #include <errno.h>
96 #include <fcntl.h>
97 #include <setjmp.h>
98 #include <signal.h>
99 #include <stdio.h>
100 #include <stdlib.h>
101 #include <string.h>
102 #include <unistd.h>
103 #include <utmp.h>
104 #include <util.h>
105 #include "pathnames.h"
106
107 #define SYSLOG_NAMES
108 #include <sys/syslog.h>
109
110 char *ConfFile = _PATH_LOGCONF;
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 addrinfo *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, finet6; /* 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 char **LogPaths; /* array of pathnames to read messages from */
196
197 void cfline __P((char *, struct filed *));
198 char *cvthname __P((struct sockaddr_storage *));
199 int decode __P((const char *, CODE *));
200 void die __P((int));
201 void domark __P((int));
202 void fprintlog __P((struct filed *, int, char *));
203 int getmsgbufsize __P((void));
204 int socksetup __P((int));
205 void init __P((int));
206 void logerror __P((char *));
207 void logmsg __P((int, char *, char *, int));
208 void printline __P((char *, char *));
209 void printsys __P((char *));
210 void reapchild __P((int));
211 void usage __P((void));
212 void wallmsg __P((struct filed *, struct iovec *));
213 int main __P((int, char *[]));
214 void logpath_add __P((char ***, int *, int *, char *));
215 void logpath_fileadd __P((char ***, int *, int *, char *));
216
217 int
218 main(argc, argv)
219 int argc;
220 char *argv[];
221 {
222 int ch, *funix, i, j, fklog, len, linesize;
223 int nfinetix, nfinet6ix, nfklogix, nfunixbaseix, nfds;
224 int funixsize = 0, funixmaxsize = 0;
225 struct sockaddr_un sunx, fromunix;
226 struct sockaddr_storage frominet;
227 char *p, *line, **pp;
228 struct pollfd *readfds;
229
230 while ((ch = getopt(argc, argv, "dsf:m:p:P:")) != -1)
231 switch(ch) {
232 case 'd': /* debug */
233 Debug++;
234 break;
235 case 'f': /* configuration file */
236 ConfFile = optarg;
237 break;
238 case 'm': /* mark interval */
239 MarkInterval = atoi(optarg) * 60;
240 break;
241 case 'p': /* path */
242 logpath_add(&LogPaths, &funixsize,
243 &funixmaxsize, optarg);
244 break;
245 case 'P': /* file of paths */
246 logpath_fileadd(&LogPaths, &funixsize,
247 &funixmaxsize, optarg);
248 break;
249 case 's': /* no network mode */
250 SecureMode++;
251 break;
252 case '?':
253 default:
254 usage();
255 }
256 if ((argc -= optind) != 0)
257 usage();
258
259 if (!Debug)
260 (void)daemon(0, 0);
261 else
262 setlinebuf(stdout);
263
264 consfile.f_type = F_CONSOLE;
265 (void)strcpy(consfile.f_un.f_fname, ctty);
266 (void)gethostname(LocalHostName, sizeof(LocalHostName));
267 LocalHostName[sizeof(LocalHostName) - 1] = '\0';
268 if ((p = strchr(LocalHostName, '.')) != NULL) {
269 *p++ = '\0';
270 LocalDomain = p;
271 } else
272 LocalDomain = "";
273 linesize = getmsgbufsize();
274 if (linesize < MAXLINE)
275 linesize = MAXLINE;
276 linesize++;
277 line = malloc(linesize);
278 if (line == NULL) {
279 logerror("couldn't allocate line buffer");
280 die(0);
281 }
282 (void)signal(SIGTERM, die);
283 (void)signal(SIGINT, Debug ? die : SIG_IGN);
284 (void)signal(SIGQUIT, Debug ? die : SIG_IGN);
285 (void)signal(SIGCHLD, reapchild);
286 (void)signal(SIGALRM, domark);
287 (void)alarm(TIMERINTVL);
288
289 #ifndef SUN_LEN
290 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
291 #endif
292 if (funixsize == 0)
293 logpath_add(&LogPaths, &funixsize,
294 &funixmaxsize, _PATH_LOG);
295 funix = (int *)malloc(sizeof(int) * funixsize);
296 if (funix == NULL) {
297 logerror("couldn't allocate funix descriptors");
298 die(0);
299 }
300 for (j = 0, pp = LogPaths; *pp; pp++, j++) {
301 dprintf("making unix dgram socket %s\n", *pp);
302 unlink(*pp);
303 memset(&sunx, 0, sizeof(sunx));
304 sunx.sun_family = AF_LOCAL;
305 (void)strncpy(sunx.sun_path, *pp, sizeof(sunx.sun_path));
306 funix[j] = socket(AF_LOCAL, SOCK_DGRAM, 0);
307 if (funix[j] < 0 || bind(funix[j],
308 (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
309 chmod(*pp, 0666) < 0) {
310 int serrno = errno;
311 (void)snprintf(line, sizeof line,
312 "cannot create %s", *pp);
313 errno = serrno;
314 logerror(line);
315 errno = serrno;
316 dprintf("cannot create %s (%d)\n", *pp, errno);
317 die(0);
318 }
319 dprintf("listening on unix dgram socket %s\n", *pp);
320 }
321
322 if (!SecureMode) {
323 finet = socksetup(AF_INET);
324 #ifdef INET6
325 finet6 = socksetup(AF_INET6);
326 #else
327 finet6 = -1;
328 #endif
329 }
330 else {
331 finet = -1;
332 finet6 = -1;
333 }
334
335 if (finet >= 0) {
336 dprintf("listening on inet socket\n");
337 InetInuse = 1;
338 }
339 if (finet6 >= 0) {
340 dprintf("listening on inet6 socket\n");
341 InetInuse = 1;
342 }
343
344 if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) < 0) {
345 dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
346 } else {
347 dprintf("listening on kernel log %s\n", _PATH_KLOG);
348 }
349
350 /* tuck my process id away, if i'm not in debug mode */
351 if (Debug == 0)
352 pidfile(NULL);
353
354 dprintf("off & running....\n");
355
356 init(0);
357 (void)signal(SIGHUP, init);
358
359 /* setup pollfd set. */
360 readfds = (struct pollfd *)malloc(sizeof(struct pollfd) *
361 (funixsize + 2));
362 if (readfds == NULL) {
363 logerror("couldn't allocate pollfds");
364 die(0);
365 }
366 nfds = 0;
367 if (fklog >= 0) {
368 nfklogix = nfds++;
369 readfds[nfklogix].fd = fklog;
370 readfds[nfklogix].events = POLLIN | POLLPRI;
371 }
372 if (finet >= 0) {
373 nfinetix = nfds++;
374 readfds[nfinetix].fd = finet;
375 readfds[nfinetix].events = POLLIN | POLLPRI;
376 }
377 if (finet6 >= 0) {
378 nfinet6ix = nfds++;
379 readfds[nfinet6ix].fd = finet6;
380 readfds[nfinet6ix].events = POLLIN | POLLPRI;
381 }
382 nfunixbaseix = nfds;
383 for (j = 0, pp = LogPaths; *pp; pp++) {
384 readfds[nfds].fd = funix[j++];
385 readfds[nfds++].events = POLLIN | POLLPRI;
386 }
387
388 for (;;) {
389 int rv;
390
391 rv = poll(readfds, nfds, INFTIM);
392 if (rv == 0)
393 continue;
394 if (rv < 0) {
395 if (errno != EINTR)
396 logerror("poll");
397 continue;
398 }
399 dprintf("got a message (%d)\n", rv);
400 if (fklog >= 0 &&
401 (readfds[nfklogix].revents & (POLLIN | POLLPRI))) {
402 dprintf("kernel log active\n");
403 i = read(fklog, line, linesize - 1);
404 if (i > 0) {
405 line[i] = '\0';
406 printsys(line);
407 } else if (i < 0 && errno != EINTR) {
408 logerror("klog");
409 fklog = -1;
410 }
411 }
412 for (j = 0, pp = LogPaths; *pp; pp++, j++) {
413 if ((readfds[nfunixbaseix + j].revents &
414 (POLLIN | POLLPRI)) == 0)
415 continue;
416
417 dprintf("unix socket (%s) active\n", *pp);
418 len = sizeof(fromunix);
419 i = recvfrom(funix[j], line, MAXLINE, 0,
420 (struct sockaddr *)&fromunix, &len);
421 if (i > 0) {
422 line[i] = '\0';
423 printline(LocalHostName, line);
424 } else if (i < 0 && errno != EINTR) {
425 char buf[MAXPATHLEN];
426 int serrno = errno;
427
428 (void)snprintf(buf, sizeof buf,
429 "recvfrom unix %s", *pp);
430 errno = serrno;
431 logerror(buf);
432 }
433 }
434 if (finet >= 0 &&
435 (readfds[nfinetix].revents & (POLLIN | POLLPRI))) {
436 dprintf("inet socket active\n");
437 len = sizeof(frominet);
438 i = recvfrom(finet, line, MAXLINE, 0,
439 (struct sockaddr *)&frominet, &len);
440 if (i > 0) {
441 line[i] = '\0';
442 printline(cvthname(&frominet), line);
443 } else if (i < 0 && errno != EINTR)
444 logerror("recvfrom inet");
445 }
446 if (finet6 >= 0 &&
447 (readfds[nfinet6ix].revents & (POLLIN | POLLPRI))) {
448 dprintf("inet6 socket active\n");
449 len = sizeof(frominet);
450 i = recvfrom(finet6, line, MAXLINE, 0,
451 (struct sockaddr *)&frominet, &len);
452 if (i > 0) {
453 line[i] = '\0';
454 printline(cvthname(&frominet), line);
455 } else if (i < 0 && errno != EINTR)
456 logerror("recvfrom inet6");
457 }
458 }
459 }
460
461 void
462 usage()
463 {
464
465 (void)fprintf(stderr,
466 "usage: syslogd [-f conffile] [-m markinterval] [-p logpath1] [-p logpath2 ..]\n");
467 exit(1);
468 }
469
470 /*
471 * given a pointer to an array of char *'s, a pointer to it's current
472 * size and current allocated max size, and a new char * to add, add
473 * it, update everything as necessary, possibly allocating a new array
474 */
475 void
476 logpath_add(lp, szp, maxszp, new)
477 char ***lp;
478 int *szp;
479 int *maxszp;
480 char *new;
481 {
482
483 dprintf("adding %s to the %p logpath list\n", new, *lp);
484 if (*szp == *maxszp) {
485 if (*maxszp == 0) {
486 *maxszp = 4; /* start of with enough for now */
487 *lp = NULL;
488 }
489 else
490 *maxszp *= 2;
491 *lp = realloc(*lp, sizeof(char *) * (*maxszp + 1));
492 if (*lp == NULL) {
493 logerror("couldn't allocate line buffer");
494 die(0);
495 }
496 }
497 (*lp)[(*szp)++] = new;
498 (*lp)[(*szp)] = NULL; /* always keep it NULL terminated */
499 }
500
501 /* do a file of log sockets */
502 void
503 logpath_fileadd(lp, szp, maxszp, file)
504 char ***lp;
505 int *szp;
506 int *maxszp;
507 char *file;
508 {
509 FILE *fp;
510 char *line;
511 size_t len;
512
513 fp = fopen(file, "r");
514 if (fp == NULL) {
515 int serrno = errno;
516
517 dprintf("can't open %s (%d)\n", file, errno);
518 errno = serrno;
519 logerror("could not open socket file list");
520 die(0);
521 }
522
523 while ((line = fgetln(fp, &len))) {
524 line[len - 1] = 0;
525 logpath_add(lp, szp, maxszp, line);
526 }
527 fclose(fp);
528 }
529
530 /*
531 * Take a raw input line, decode the message, and print the message
532 * on the appropriate log files.
533 */
534 void
535 printline(hname, msg)
536 char *hname;
537 char *msg;
538 {
539 int c, pri;
540 char *p, *q, line[MAXLINE + 1];
541
542 /* test for special codes */
543 pri = DEFUPRI;
544 p = msg;
545 if (*p == '<') {
546 pri = 0;
547 while (isdigit(*++p))
548 pri = 10 * pri + (*p - '0');
549 if (*p == '>')
550 ++p;
551 }
552 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
553 pri = DEFUPRI;
554
555 /* don't allow users to log kernel messages */
556 if (LOG_FAC(pri) == LOG_KERN)
557 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
558
559 q = line;
560
561 while ((c = *p++ & 0177) != '\0' &&
562 q < &line[sizeof(line) - 1])
563 if (iscntrl(c))
564 if (c == '\n')
565 *q++ = ' ';
566 else if (c == '\t')
567 *q++ = '\t';
568 else {
569 *q++ = '^';
570 *q++ = c ^ 0100;
571 }
572 else
573 *q++ = c;
574 *q = '\0';
575
576 logmsg(pri, line, hname, 0);
577 }
578
579 /*
580 * Take a raw input line from /dev/klog, split and format similar to syslog().
581 */
582 void
583 printsys(msg)
584 char *msg;
585 {
586 int c, pri, flags;
587 char *lp, *p, *q, line[MAXLINE + 1];
588
589 (void)strcpy(line, _PATH_UNIX);
590 (void)strcat(line, ": ");
591 lp = line + strlen(line);
592 for (p = msg; *p != '\0'; ) {
593 flags = SYNC_FILE | ADDDATE; /* fsync file after write */
594 pri = DEFSPRI;
595 if (*p == '<') {
596 pri = 0;
597 while (isdigit(*++p))
598 pri = 10 * pri + (*p - '0');
599 if (*p == '>')
600 ++p;
601 } else {
602 /* kernel printf's come out on console */
603 flags |= IGN_CONS;
604 }
605 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
606 pri = DEFSPRI;
607 q = lp;
608 while (*p != '\0' && (c = *p++) != '\n' &&
609 q < &line[MAXLINE])
610 *q++ = c;
611 *q = '\0';
612 logmsg(pri, line, LocalHostName, flags);
613 }
614 }
615
616 time_t now;
617
618 /*
619 * Log a message to the appropriate log files, users, etc. based on
620 * the priority.
621 */
622 void
623 logmsg(pri, msg, from, flags)
624 int pri;
625 char *msg, *from;
626 int flags;
627 {
628 struct filed *f;
629 int fac, msglen, omask, prilev;
630 char *timestamp;
631
632 dprintf("logmsg: pri 0%o, flags 0x%x, from %s, msg %s\n",
633 pri, flags, from, msg);
634
635 omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
636
637 /*
638 * Check to see if msg looks non-standard.
639 */
640 msglen = strlen(msg);
641 if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
642 msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
643 flags |= ADDDATE;
644
645 (void)time(&now);
646 if (flags & ADDDATE)
647 timestamp = ctime(&now) + 4;
648 else {
649 timestamp = msg;
650 msg += 16;
651 msglen -= 16;
652 }
653
654 /* extract facility and priority level */
655 if (flags & MARK)
656 fac = LOG_NFACILITIES;
657 else
658 fac = LOG_FAC(pri);
659 prilev = LOG_PRI(pri);
660
661 /* log the message to the particular outputs */
662 if (!Initialized) {
663 f = &consfile;
664 f->f_file = open(ctty, O_WRONLY, 0);
665
666 if (f->f_file >= 0) {
667 fprintlog(f, flags, msg);
668 (void)close(f->f_file);
669 }
670 (void)sigsetmask(omask);
671 return;
672 }
673 for (f = Files; f; f = f->f_next) {
674 /* skip messages that are incorrect priority */
675 if (f->f_pmask[fac] < prilev ||
676 f->f_pmask[fac] == INTERNAL_NOPRI)
677 continue;
678
679 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
680 continue;
681
682 /* don't output marks to recently written files */
683 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
684 continue;
685
686 /*
687 * suppress duplicate lines to this file
688 */
689 if ((flags & MARK) == 0 && msglen == f->f_prevlen &&
690 !strcmp(msg, f->f_prevline) &&
691 !strcmp(from, f->f_prevhost)) {
692 (void)strncpy(f->f_lasttime, timestamp, 15);
693 f->f_prevcount++;
694 dprintf("msg repeated %d times, %ld sec of %d\n",
695 f->f_prevcount, (long)(now - f->f_time),
696 repeatinterval[f->f_repeatcount]);
697 /*
698 * If domark would have logged this by now,
699 * flush it now (so we don't hold isolated messages),
700 * but back off so we'll flush less often
701 * in the future.
702 */
703 if (now > REPEATTIME(f)) {
704 fprintlog(f, flags, (char *)NULL);
705 BACKOFF(f);
706 }
707 } else {
708 /* new line, save it */
709 if (f->f_prevcount)
710 fprintlog(f, 0, (char *)NULL);
711 f->f_repeatcount = 0;
712 f->f_prevpri = pri;
713 (void)strncpy(f->f_lasttime, timestamp, 15);
714 (void)strncpy(f->f_prevhost, from,
715 sizeof(f->f_prevhost));
716 if (msglen < MAXSVLINE) {
717 f->f_prevlen = msglen;
718 (void)strcpy(f->f_prevline, msg);
719 fprintlog(f, flags, (char *)NULL);
720 } else {
721 f->f_prevline[0] = 0;
722 f->f_prevlen = 0;
723 fprintlog(f, flags, msg);
724 }
725 }
726 }
727 (void)sigsetmask(omask);
728 }
729
730 void
731 fprintlog(f, flags, msg)
732 struct filed *f;
733 int flags;
734 char *msg;
735 {
736 struct iovec iov[6];
737 struct iovec *v;
738 struct addrinfo *r;
739 int l, lsent;
740 char line[MAXLINE + 1], repbuf[80], greetings[200];
741
742 v = iov;
743 if (f->f_type == F_WALL) {
744 v->iov_base = greetings;
745 v->iov_len = snprintf(greetings, sizeof greetings,
746 "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
747 f->f_prevhost, ctime(&now));
748 v++;
749 v->iov_base = "";
750 v->iov_len = 0;
751 v++;
752 } else {
753 v->iov_base = f->f_lasttime;
754 v->iov_len = 15;
755 v++;
756 v->iov_base = " ";
757 v->iov_len = 1;
758 v++;
759 }
760 v->iov_base = f->f_prevhost;
761 v->iov_len = strlen(v->iov_base);
762 v++;
763 v->iov_base = " ";
764 v->iov_len = 1;
765 v++;
766
767 if (msg) {
768 v->iov_base = msg;
769 v->iov_len = strlen(msg);
770 } else if (f->f_prevcount > 1) {
771 v->iov_base = repbuf;
772 v->iov_len = snprintf(repbuf, sizeof repbuf,
773 "last message repeated %d times", f->f_prevcount);
774 } else {
775 v->iov_base = f->f_prevline;
776 v->iov_len = f->f_prevlen;
777 }
778 v++;
779
780 dprintf("Logging to %s", TypeNames[f->f_type]);
781 f->f_time = now;
782
783 switch (f->f_type) {
784 case F_UNUSED:
785 dprintf("\n");
786 break;
787
788 case F_FORW:
789 dprintf(" %s\n", f->f_un.f_forw.f_hname);
790 /* check for local vs remote messages (from FreeBSD PR#bin/7055) */
791 if (strcmp(f->f_prevhost, LocalHostName)) {
792 l = snprintf(line, sizeof(line) - 1,
793 "<%d>%.15s [%s]: %s",
794 f->f_prevpri, (char *) iov[0].iov_base,
795 f->f_prevhost, (char *) iov[4].iov_base);
796 } else {
797 l = snprintf(line, sizeof(line) - 1, "<%d>%.15s %s",
798 f->f_prevpri, (char *) iov[0].iov_base,
799 (char *) iov[4].iov_base);
800 }
801 if (l > MAXLINE)
802 l = MAXLINE;
803 if (finet >= 0 || finet6 >= 0) {
804 for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
805 if (r->ai_family == AF_INET)
806 lsent = sendto(finet, line, l, 0, r->ai_addr, r->ai_addrlen);
807 #ifdef INET6
808 if (r->ai_family == AF_INET6)
809 lsent = sendto(finet6, line, l, 0, r->ai_addr, r->ai_addrlen);
810 #endif
811 if (lsent == l)
812 break;
813 }
814 if (lsent != l) {
815 f->f_type = F_UNUSED;
816 logerror("sendto");
817 }
818 }
819 break;
820
821 case F_CONSOLE:
822 if (flags & IGN_CONS) {
823 dprintf(" (ignored)\n");
824 break;
825 }
826 /* FALLTHROUGH */
827
828 case F_TTY:
829 case F_FILE:
830 dprintf(" %s\n", f->f_un.f_fname);
831 if (f->f_type != F_FILE) {
832 v->iov_base = "\r\n";
833 v->iov_len = 2;
834 } else {
835 v->iov_base = "\n";
836 v->iov_len = 1;
837 }
838 again:
839 if (writev(f->f_file, iov, 6) < 0) {
840 int e = errno;
841 (void)close(f->f_file);
842 /*
843 * Check for errors on TTY's due to loss of tty
844 */
845 if ((e == EIO || e == EBADF) && f->f_type != F_FILE) {
846 f->f_file = open(f->f_un.f_fname,
847 O_WRONLY|O_APPEND, 0);
848 if (f->f_file < 0) {
849 f->f_type = F_UNUSED;
850 logerror(f->f_un.f_fname);
851 } else
852 goto again;
853 } else {
854 f->f_type = F_UNUSED;
855 errno = e;
856 logerror(f->f_un.f_fname);
857 }
858 } else if (flags & SYNC_FILE)
859 (void)fsync(f->f_file);
860 break;
861
862 case F_USERS:
863 case F_WALL:
864 dprintf("\n");
865 v->iov_base = "\r\n";
866 v->iov_len = 2;
867 wallmsg(f, iov);
868 break;
869 }
870 f->f_prevcount = 0;
871 }
872
873 /*
874 * WALLMSG -- Write a message to the world at large
875 *
876 * Write the specified message to either the entire
877 * world, or a list of approved users.
878 */
879 void
880 wallmsg(f, iov)
881 struct filed *f;
882 struct iovec *iov;
883 {
884 static int reenter; /* avoid calling ourselves */
885 FILE *uf;
886 struct utmp ut;
887 int i;
888 char *p;
889 char line[sizeof(ut.ut_line) + 1];
890
891 if (reenter++)
892 return;
893 if ((uf = fopen(_PATH_UTMP, "r")) == NULL) {
894 logerror(_PATH_UTMP);
895 reenter = 0;
896 return;
897 }
898 /* NOSTRICT */
899 while (fread((char *)&ut, sizeof(ut), 1, uf) == 1) {
900 if (ut.ut_name[0] == '\0')
901 continue;
902 strncpy(line, ut.ut_line, sizeof(ut.ut_line));
903 line[sizeof(ut.ut_line)] = '\0';
904 if (f->f_type == F_WALL) {
905 if ((p = ttymsg(iov, 6, line, TTYMSGTIME)) != NULL) {
906 errno = 0; /* already in msg */
907 logerror(p);
908 }
909 continue;
910 }
911 /* should we send the message to this user? */
912 for (i = 0; i < MAXUNAMES; i++) {
913 if (!f->f_un.f_uname[i][0])
914 break;
915 if (!strncmp(f->f_un.f_uname[i], ut.ut_name,
916 UT_NAMESIZE)) {
917 if ((p = ttymsg(iov, 6, line, TTYMSGTIME))
918 != NULL) {
919 errno = 0; /* already in msg */
920 logerror(p);
921 }
922 break;
923 }
924 }
925 }
926 (void)fclose(uf);
927 reenter = 0;
928 }
929
930 void
931 reapchild(signo)
932 int signo;
933 {
934 union wait status;
935
936 while (wait3((int *)&status, WNOHANG, (struct rusage *)NULL) > 0)
937 ;
938 }
939
940 /*
941 * Return a printable representation of a host address.
942 */
943 char *
944 cvthname(f)
945 struct sockaddr_storage *f;
946 {
947 int error;
948 char *p;
949 #ifdef KAME_SCOPEID
950 const int niflag = NI_DGRAM | NI_WITHSCOPEID;
951 #else
952 const int niflag = NI_DGRAM;
953 #endif
954 static char host[NI_MAXHOST], ip[NI_MAXHOST];
955
956 error = getnameinfo((struct sockaddr*)f, ((struct sockaddr*)f)->sa_len,
957 ip, NI_MAXHOST, NULL, 0, NI_NUMERICHOST|niflag);
958
959 dprintf("cvthname(%s)\n", ip);
960
961 if (error) {
962 dprintf("Malformed from address %s\n", gai_strerror(error));
963 return ("???");
964 }
965
966 error = getnameinfo((struct sockaddr*)f, ((struct sockaddr*)f)->sa_len,
967 host, NI_MAXHOST, NULL, 0, niflag);
968 if (error) {
969 dprintf("Host name for your address (%s) unknown\n", ip);
970 return (ip);
971 }
972 if ((p = strchr(host, '.')) && strcmp(p + 1, LocalDomain) == 0)
973 *p = '\0';
974 return (host);
975 }
976
977 void
978 domark(signo)
979 int signo;
980 {
981 struct filed *f;
982
983 now = time((time_t *)NULL);
984 MarkSeq += TIMERINTVL;
985 if (MarkSeq >= MarkInterval) {
986 logmsg(LOG_INFO, "-- MARK --", LocalHostName, ADDDATE|MARK);
987 MarkSeq = 0;
988 }
989
990 for (f = Files; f; f = f->f_next) {
991 if (f->f_prevcount && now >= REPEATTIME(f)) {
992 dprintf("flush %s: repeated %d times, %d sec.\n",
993 TypeNames[f->f_type], f->f_prevcount,
994 repeatinterval[f->f_repeatcount]);
995 fprintlog(f, 0, (char *)NULL);
996 BACKOFF(f);
997 }
998 }
999 (void)alarm(TIMERINTVL);
1000 }
1001
1002 /*
1003 * Print syslogd errors some place.
1004 */
1005 void
1006 logerror(type)
1007 char *type;
1008 {
1009 char buf[100];
1010
1011 if (errno)
1012 (void)snprintf(buf,
1013 sizeof(buf), "syslogd: %s: %s", type, strerror(errno));
1014 else
1015 (void)snprintf(buf, sizeof(buf), "syslogd: %s", type);
1016 errno = 0;
1017 dprintf("%s\n", buf);
1018 logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1019 }
1020
1021 void
1022 die(signo)
1023 int signo;
1024 {
1025 struct filed *f;
1026 char buf[100], **p;
1027
1028 for (f = Files; f != NULL; f = f->f_next) {
1029 /* flush any pending output */
1030 if (f->f_prevcount)
1031 fprintlog(f, 0, (char *)NULL);
1032 }
1033 if (signo) {
1034 dprintf("syslogd: exiting on signal %d\n", signo);
1035 (void)snprintf(buf, sizeof buf, "exiting on signal %d", signo);
1036 errno = 0;
1037 logerror(buf);
1038 }
1039 for (p = LogPaths; p && *p; p++)
1040 unlink(*p);
1041 exit(0);
1042 }
1043
1044 /*
1045 * INIT -- Initialize syslogd from configuration table
1046 */
1047 void
1048 init(signo)
1049 int signo;
1050 {
1051 int i;
1052 FILE *cf;
1053 struct filed *f, *next, **nextp;
1054 char *p;
1055 char cline[LINE_MAX];
1056
1057 dprintf("init\n");
1058
1059 /*
1060 * Close all open log files.
1061 */
1062 Initialized = 0;
1063 for (f = Files; f != NULL; f = next) {
1064 /* flush any pending output */
1065 if (f->f_prevcount)
1066 fprintlog(f, 0, (char *)NULL);
1067
1068 switch (f->f_type) {
1069 case F_FILE:
1070 case F_TTY:
1071 case F_CONSOLE:
1072 (void)close(f->f_file);
1073 break;
1074 }
1075 next = f->f_next;
1076 free((char *)f);
1077 }
1078 Files = NULL;
1079 nextp = &Files;
1080
1081 /* open the configuration file */
1082 if ((cf = fopen(ConfFile, "r")) == NULL) {
1083 dprintf("cannot open %s\n", ConfFile);
1084 *nextp = (struct filed *)calloc(1, sizeof(*f));
1085 cfline("*.ERR\t/dev/console", *nextp);
1086 (*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1087 cfline("*.PANIC\t*", (*nextp)->f_next);
1088 Initialized = 1;
1089 return;
1090 }
1091
1092 /*
1093 * Foreach line in the conf table, open that file.
1094 */
1095 f = NULL;
1096 while (fgets(cline, sizeof(cline), cf) != NULL) {
1097 /*
1098 * check for end-of-section, comments, strip off trailing
1099 * spaces and newline character.
1100 */
1101 for (p = cline; isspace(*p); ++p)
1102 continue;
1103 if (*p == '\0' || *p == '#')
1104 continue;
1105 for (p = strchr(cline, '\0'); isspace(*--p);)
1106 continue;
1107 *++p = '\0';
1108 f = (struct filed *)calloc(1, sizeof(*f));
1109 *nextp = f;
1110 nextp = &f->f_next;
1111 cfline(cline, f);
1112 }
1113
1114 /* close the configuration file */
1115 (void)fclose(cf);
1116
1117 Initialized = 1;
1118
1119 if (Debug) {
1120 for (f = Files; f; f = f->f_next) {
1121 for (i = 0; i <= LOG_NFACILITIES; i++)
1122 if (f->f_pmask[i] == INTERNAL_NOPRI)
1123 printf("X ");
1124 else
1125 printf("%d ", f->f_pmask[i]);
1126 printf("%s: ", TypeNames[f->f_type]);
1127 switch (f->f_type) {
1128 case F_FILE:
1129 case F_TTY:
1130 case F_CONSOLE:
1131 printf("%s", f->f_un.f_fname);
1132 break;
1133
1134 case F_FORW:
1135 printf("%s", f->f_un.f_forw.f_hname);
1136 break;
1137
1138 case F_USERS:
1139 for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1140 printf("%s, ", f->f_un.f_uname[i]);
1141 break;
1142 }
1143 printf("\n");
1144 }
1145 }
1146
1147 logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1148 dprintf("syslogd: restarted\n");
1149 }
1150
1151 /*
1152 * Crack a configuration file line
1153 */
1154 void
1155 cfline(line, f)
1156 char *line;
1157 struct filed *f;
1158 {
1159 struct addrinfo hints, *res;
1160 int error, i, pri;
1161 char *bp, *p, *q;
1162 char buf[MAXLINE], ebuf[100];
1163
1164 dprintf("cfline(%s)\n", line);
1165
1166 errno = 0; /* keep strerror() stuff out of logerror messages */
1167
1168 /* clear out file entry */
1169 memset(f, 0, sizeof(*f));
1170 for (i = 0; i <= LOG_NFACILITIES; i++)
1171 f->f_pmask[i] = INTERNAL_NOPRI;
1172
1173 /* scan through the list of selectors */
1174 for (p = line; *p && *p != '\t';) {
1175
1176 /* find the end of this facility name list */
1177 for (q = p; *q && *q != '\t' && *q++ != '.'; )
1178 continue;
1179
1180 /* collect priority name */
1181 for (bp = buf; *q && !strchr("\t,;", *q); )
1182 *bp++ = *q++;
1183 *bp = '\0';
1184
1185 /* skip cruft */
1186 while (strchr(", ;", *q))
1187 q++;
1188
1189 /* decode priority name */
1190 if (*buf == '*')
1191 pri = LOG_PRIMASK + 1;
1192 else {
1193 pri = decode(buf, prioritynames);
1194 if (pri < 0) {
1195 (void)snprintf(ebuf, sizeof ebuf,
1196 "unknown priority name \"%s\"", buf);
1197 logerror(ebuf);
1198 return;
1199 }
1200 }
1201
1202 /* scan facilities */
1203 while (*p && !strchr("\t.;", *p)) {
1204 for (bp = buf; *p && !strchr("\t,;.", *p); )
1205 *bp++ = *p++;
1206 *bp = '\0';
1207 if (*buf == '*')
1208 for (i = 0; i < LOG_NFACILITIES; i++)
1209 f->f_pmask[i] = pri;
1210 else {
1211 i = decode(buf, facilitynames);
1212 if (i < 0) {
1213 (void)snprintf(ebuf, sizeof ebuf,
1214 "unknown facility name \"%s\"",
1215 buf);
1216 logerror(ebuf);
1217 return;
1218 }
1219 f->f_pmask[i >> 3] = pri;
1220 }
1221 while (*p == ',' || *p == ' ')
1222 p++;
1223 }
1224
1225 p = q;
1226 }
1227
1228 /* skip to action part */
1229 while (*p == '\t')
1230 p++;
1231
1232 switch (*p)
1233 {
1234 case '@':
1235 if (!InetInuse)
1236 break;
1237 (void)strcpy(f->f_un.f_forw.f_hname, ++p);
1238 memset(&hints, 0, sizeof(hints));
1239 hints.ai_family = AF_UNSPEC;
1240 hints.ai_socktype = SOCK_DGRAM;
1241 hints.ai_protocol = 0;
1242 error = getaddrinfo(f->f_un.f_forw.f_hname, "syslog", &hints, &res);
1243 if (error) {
1244 logerror(gai_strerror(error));
1245 break;
1246 }
1247 f->f_un.f_forw.f_addr = res;
1248 f->f_type = F_FORW;
1249 break;
1250
1251 case '/':
1252 (void)strcpy(f->f_un.f_fname, p);
1253 if ((f->f_file = open(p, O_WRONLY|O_APPEND, 0)) < 0) {
1254 f->f_type = F_UNUSED;
1255 logerror(p);
1256 break;
1257 }
1258 if (isatty(f->f_file))
1259 f->f_type = F_TTY;
1260 else
1261 f->f_type = F_FILE;
1262 if (strcmp(p, ctty) == 0)
1263 f->f_type = F_CONSOLE;
1264 break;
1265
1266 case '*':
1267 f->f_type = F_WALL;
1268 break;
1269
1270 default:
1271 for (i = 0; i < MAXUNAMES && *p; i++) {
1272 for (q = p; *q && *q != ','; )
1273 q++;
1274 (void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
1275 if ((q - p) > UT_NAMESIZE)
1276 f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
1277 else
1278 f->f_un.f_uname[i][q - p] = '\0';
1279 while (*q == ',' || *q == ' ')
1280 q++;
1281 p = q;
1282 }
1283 f->f_type = F_USERS;
1284 break;
1285 }
1286 }
1287
1288
1289 /*
1290 * Decode a symbolic name to a numeric value
1291 */
1292 int
1293 decode(name, codetab)
1294 const char *name;
1295 CODE *codetab;
1296 {
1297 CODE *c;
1298 char *p, buf[40];
1299
1300 if (isdigit(*name))
1301 return (atoi(name));
1302
1303 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
1304 if (isupper(*name))
1305 *p = tolower(*name);
1306 else
1307 *p = *name;
1308 }
1309 *p = '\0';
1310 for (c = codetab; c->c_name; c++)
1311 if (!strcmp(buf, c->c_name))
1312 return (c->c_val);
1313
1314 return (-1);
1315 }
1316
1317 /*
1318 * Retrieve the size of the kernel message buffer, via sysctl.
1319 */
1320 int
1321 getmsgbufsize()
1322 {
1323 int msgbufsize, mib[2];
1324 size_t size;
1325
1326 mib[0] = CTL_KERN;
1327 mib[1] = KERN_MSGBUFSIZE;
1328 size = sizeof msgbufsize;
1329 if (sysctl(mib, 2, &msgbufsize, &size, NULL, 0) == -1) {
1330 dprintf("couldn't get kern.msgbufsize\n");
1331 return (0);
1332 }
1333 return (msgbufsize);
1334 }
1335
1336 int
1337 socksetup(af)
1338 int af;
1339 {
1340 struct addrinfo hints, *res;
1341 int error, sock;
1342
1343 memset(&hints, 0, sizeof(hints));
1344 hints.ai_flags = AI_PASSIVE;
1345 hints.ai_family = af;
1346 hints.ai_socktype = SOCK_DGRAM;
1347 error = getaddrinfo(NULL, "syslog", &hints, &res);
1348 if (error) {
1349 logerror(gai_strerror(error));
1350 errno = 0;
1351 die(0);
1352 }
1353 if (res->ai_next)
1354 logerror("resolved to multiple addr");
1355 else {
1356 sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
1357 if (sock >= 0) {
1358 if (bind(sock, res->ai_addr, res->ai_addrlen) < 0) {
1359 close (sock);
1360 sock = -1;
1361 logerror("bind");
1362 if (!Debug)
1363 die(0);
1364 }
1365 }
1366 }
1367 if (res)
1368 freeaddrinfo(res);
1369
1370 return(sock);
1371 }
1372