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