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