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: * 4. Neither the name of the University nor the names of its contributors
14: * may be used to endorse or promote products derived from this software
15: * without specific prior written permission.
16: *
17: * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18: * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19: * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20: * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21: * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22: * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23: * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24: * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25: * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26: * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27: * SUCH DAMAGE.
28: */
29:
30: #ifndef lint
31: static const char copyright[] =
32: "@(#) Copyright (c) 1983, 1988, 1993, 1994\n\
33: The Regents of the University of California. All rights reserved.\n";
34: #endif /* not lint */
35:
36: #ifndef lint
37: #if 0
38: static char sccsid[] = "@(#)syslogd.c 8.3 (Berkeley) 4/4/94";
39: #endif
40: #endif /* not lint */
41:
42: #include <sys/cdefs.h>
43: __FBSDID("$FreeBSD: src/usr.sbin/syslogd/syslogd.c,v 1.167 2010/08/07 16:20:12 olli Exp $");
44:
45: /*
46: * syslogd -- log system messages
47: *
48: * This program implements a system log. It takes a series of lines.
49: * Each line may have a priority, signified as "<n>" as
50: * the first characters of the line. If this is
51: * not present, a default priority is used.
52: *
53: * To kill syslogd, send a signal 15 (terminate). A signal 1 (hup) will
54: * cause it to reread its configuration file.
55: *
56: * Defined Constants:
57: *
58: * MAXLINE -- the maximum line length that can be handled.
59: * DEFUPRI -- the default priority for user messages
60: * DEFSPRI -- the default priority for kernel messages
61: *
62: * Author: Eric Allman
63: * extensive changes by Ralph Campbell
64: * more extensive changes by Eric Allman (again)
65: * Extension to log by program name as well as facility and priority
66: * by Peter da Silva.
67: * -u and -v by Harlan Stenn.
68: * Priority comparison code by Harlan Stenn.
69: */
70:
71: #define MAXLINE 1024 /* maximum line length */
72: #define MAXSVLINE 120 /* maximum saved line length */
73: #define DEFUPRI (LOG_USER|LOG_NOTICE)
74: #define DEFSPRI (LOG_KERN|LOG_CRIT)
75: #define TIMERINTVL 30 /* interval for checking flush, mark */
76: #define TTYMSGTIME 1 /* timeout passed to ttymsg */
77:
78: #include <sys/param.h>
79: #include <sys/ioctl.h>
80: #include <sys/mman.h>
81: #include <sys/stat.h>
82: #include <sys/wait.h>
83: #include <sys/socket.h>
84: #include <sys/queue.h>
85: #include <sys/uio.h>
86: #include <sys/un.h>
87: #include <sys/time.h>
88: #include <sys/resource.h>
89: #include <sys/syslimits.h>
90: #include <sys/types.h>
91:
92: #include <netinet/in.h>
93: #include <netdb.h>
94: #include <arpa/inet.h>
95:
96: #include <ctype.h>
97: #include <err.h>
98: #include <errno.h>
99: #include <fcntl.h>
100: #include <libutil.h>
101: #include <limits.h>
102: #include <paths.h>
103: #include <signal.h>
104: #include <stdio.h>
105: #include <stdlib.h>
106: #include <string.h>
107: #include <sysexits.h>
108: #include <unistd.h>
109: #if defined(__FreeBSD__) && (__FreeBSD__ > 8)
110: #include <utmpx.h>
111: #else
112: #include <utmp.h>
113: #endif
114:
115: #include "pathnames.h"
116:
117: // CPP:
118: #include "defs.h"
119: #include "clog.h"
120: #include <sys/mman.h>
121: #include <dirent.h>
122: // CPP::
123:
124: #define SYSLOG_NAMES
125: #include <sys/syslog.h>
126:
127: const char *ConfFile = _PATH_LOGCONF;
128: const char *PidFile = _PATH_LOGPID;
129: const char ctty[] = _PATH_CONSOLE;
130:
131: #define dprintf if (Debug) printf
132:
133: #define MAXUNAMES 20 /* maximum number of user names */
134:
135: /*
136: * Unix sockets.
137: * We have two default sockets, one with 666 permissions,
138: * and one for privileged programs.
139: */
140: struct funix {
141: int s;
142: const char *name;
143: mode_t mode;
144: STAILQ_ENTRY(funix) next;
145: };
146: struct funix funix_secure = { -1, _PATH_LOG_PRIV, S_IRUSR | S_IWUSR,
147: { NULL } };
148: struct funix funix_default = { -1, _PATH_LOG, DEFFILEMODE,
149: { &funix_secure } };
150:
151: STAILQ_HEAD(, funix) funixes = { &funix_default,
152: &(funix_secure.next.stqe_next) };
153:
154: /*
155: * Flags to logmsg().
156: */
157:
158: #define IGN_CONS 0x001 /* don't print on console */
159: #define SYNC_FILE 0x002 /* do fsync on file after printing */
160: #define ADDDATE 0x004 /* add a date to the message */
161: #define MARK 0x008 /* this message is a mark */
162: #define ISKERNEL 0x010 /* kernel generated message */
163:
164: /*
165: * This structure represents the files that will have log
166: * copies printed.
167: * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY
168: * or if f_type if F_PIPE and f_pid > 0.
169: */
170:
171: struct filed {
172: struct filed *f_next; /* next in linked list */
173: short f_type; /* entry type, see below */
174: short f_file; /* file descriptor */
175: time_t f_time; /* time this was last written */
176: char *f_host; /* host from which to recd. */
177: u_char f_pmask[LOG_NFACILITIES+1]; /* priority mask */
178: u_char f_pcmp[LOG_NFACILITIES+1]; /* compare priority */
179: #define PRI_LT 0x1
180: #define PRI_EQ 0x2
181: #define PRI_GT 0x4
182: char *f_program; /* program this applies to */
183: union {
184: char f_uname[MAXUNAMES][MAXLOGNAME];
185: struct {
186: char f_hname[MAXHOSTNAMELEN];
187: struct addrinfo *f_addr;
188:
189: } f_forw; /* forwarding address */
190: char f_fname[MAXPATHLEN];
191: struct {
192: char f_pname[MAXPATHLEN];
193: pid_t f_pid;
194: } f_pipe;
195: // CPP:
196: struct {
197: char f_rname[MAXPATHLEN];
198: struct clogFooter *f_footer;
199: size_t f_size;
200: } f_ring;
201: // CPP::
202: } f_un;
203: char f_prevline[MAXSVLINE]; /* last message logged */
204: char f_lasttime[16]; /* time of last occurrence */
205: char f_prevhost[MAXHOSTNAMELEN]; /* host from which recd. */
206: int f_prevpri; /* pri of f_prevline */
207: int f_prevlen; /* length of f_prevline */
208: int f_prevcount; /* repetition cnt of prevline */
209: u_int f_repeatcount; /* number of "repeated" msgs */
210: int f_flags; /* file-specific flags */
211: #define FFLAG_SYNC 0x01
212: #define FFLAG_NEEDSYNC 0x02
213: };
214:
215: /*
216: * Queue of about-to-be dead processes we should watch out for.
217: */
218:
219: TAILQ_HEAD(stailhead, deadq_entry) deadq_head;
220: struct stailhead *deadq_headp;
221:
222: struct deadq_entry {
223: pid_t dq_pid;
224: int dq_timeout;
225: TAILQ_ENTRY(deadq_entry) dq_entries;
226: };
227:
228: /*
229: * The timeout to apply to processes waiting on the dead queue. Unit
230: * of measure is `mark intervals', i.e. 20 minutes by default.
231: * Processes on the dead queue will be terminated after that time.
232: */
233:
234: #define DQ_TIMO_INIT 2
235:
236: typedef struct deadq_entry *dq_t;
237:
238:
239: /*
240: * Struct to hold records of network addresses that are allowed to log
241: * to us.
242: */
243: struct allowedpeer {
244: int isnumeric;
245: u_short port;
246: union {
247: struct {
248: struct sockaddr_storage addr;
249: struct sockaddr_storage mask;
250: } numeric;
251: char *name;
252: } u;
253: #define a_addr u.numeric.addr
254: #define a_mask u.numeric.mask
255: #define a_name u.name
256: };
257:
258:
259: /*
260: * Intervals at which we flush out "message repeated" messages,
261: * in seconds after previous message is logged. After each flush,
262: * we move to the next interval until we reach the largest.
263: */
264: int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */
265: #define MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
266: #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount])
267: #define BACKOFF(f) { if (++(f)->f_repeatcount > MAXREPEAT) \
268: (f)->f_repeatcount = MAXREPEAT; \
269: }
270:
271: /* values for f_type */
272: #define F_UNUSED 0 /* unused entry */
273: #define F_FILE 1 /* regular file */
274: #define F_TTY 2 /* terminal */
275: #define F_CONSOLE 3 /* console terminal */
276: #define F_FORW 4 /* remote machine */
277: #define F_USERS 5 /* list of users */
278: #define F_WALL 6 /* everyone logged on */
279: #define F_PIPE 7 /* pipe to program */
280: #define F_RING 8 /* ring buffer (circular log) */
281:
282: // CPP:
283: const char *TypeNames[] = {
284: "UNUSED", "FILE", "TTY", "CONSOLE",
285: "FORW", "USERS", "WALL", "PIPE",
286: "RING"
287: };
288: // CPP::
289:
290: static struct filed *Files; /* Log files that we write to */
291: static struct filed consfile; /* Console */
292:
293: static int Debug; /* debug flag */
294: static int resolve = 1; /* resolve hostname */
295: static char LocalHostName[MAXHOSTNAMELEN]; /* our hostname */
296: static const char *LocalDomain; /* our local domain name */
297: static int *finet; /* Internet datagram socket */
298: static int fklog = -1; /* /dev/klog */
299: static int Initialized; /* set when we have initialized ourselves */
300: static int MarkInterval = 20 * 60; /* interval between marks in seconds */
301: static int MarkSeq; /* mark sequence number */
302: static int SecureMode; /* when true, receive only unix domain socks */
303: #ifdef INET6
304: static int family = PF_UNSPEC; /* protocol family (IPv4, IPv6 or both) */
305: #else
306: static int family = PF_INET; /* protocol family (IPv4 only) */
307: #endif
308: static int mask_C1 = 1; /* mask characters from 0x80 - 0x9F */
309: static int send_to_all; /* send message to all IPv4/IPv6 addresses */
310: static int use_bootfile; /* log entire bootfile for every kern msg */
311: static int no_compress; /* don't compress messages (1=pipes, 2=all) */
312: static int logflags = O_WRONLY|O_APPEND; /* flags used to open log files */
313:
314: static char bootfile[MAXLINE+1]; /* booted kernel file */
315:
316: struct allowedpeer *AllowedPeers; /* List of allowed peers */
317: static int NumAllowed; /* Number of entries in AllowedPeers */
318: static int RemoteAddDate; /* Always set the date on remote messages */
319:
320: static int UniquePriority; /* Only log specified priority? */
321: static int LogFacPri; /* Put facility and priority in log message: */
322: /* 0=no, 1=numeric, 2=names */
323: static int KeepKernFac; /* Keep remotely logged kernel facility */
324: static int needdofsync = 0; /* Are any file(s) waiting to be fsynced? */
325: static struct pidfh *pfh;
326:
327: volatile sig_atomic_t MarkSet, WantDie;
328:
329: static int allowaddr(char *);
330: static void cfline(const char *, struct filed *,
331: const char *, const char *);
332: static const char *cvthname(struct sockaddr *);
333: static void deadq_enter(pid_t, const char *);
334: static int deadq_remove(pid_t);
335: static int decode(const char *, CODE *);
336: static void die(int);
337: static void dodie(int);
338: static void dofsync(void);
339: static void domark(int);
340: static void fprintlog(struct filed *, int, const char *);
341: static int *socksetup(int, char *);
342: static void init(int);
343: static void logerror(const char *);
344: static void logmsg(int, const char *, const char *, int);
345: static void log_deadchild(pid_t, int, const char *);
346: static void markit(void);
347: static int skip_message(const char *, const char *, int);
348: static void printline(const char *, char *, int);
349: static void printsys(char *);
350: static int p_open(const char *, pid_t *);
351: static void readklog(void);
352: static void reapchild(int);
353: static void usage(void);
354: static int validate(struct sockaddr *, const char *);
355: static void unmapped(struct sockaddr *);
356: static void wallmsg(struct filed *, struct iovec *, const int iovlen);
357: static int waitdaemon(int, int, int);
358: static void timedout(int);
359: static void double_rbuf(int);
360:
361: // CPP:
362: static const char *
363: ttymsg(struct iovec *iov, int iovcnt, const char *line, int tmout)
364: {
365: struct iovec localiov[7];
366: ssize_t left, wret;
367: int cnt, fd;
368: static char device[MAXNAMLEN] = _PATH_DEV;
369: static char errbuf[1024];
370: char *p;
371: int forked;
372:
373: forked = 0;
374: if (iovcnt > (int)(sizeof(localiov) / sizeof(localiov[0])))
375: return ("too many iov's (change code in wall/ttymsg.c)");
376:
377: p = device + sizeof(_PATH_DEV) - 1;
378: strlcpy(p, line, sizeof(device));
379: if (strncmp(p, "pts/", 4) == 0)
380: p += 4;
381: if (strchr(p, '/') != NULL) {
382: /* A slash is an attempt to break security... */
383: (void) snprintf(errbuf, sizeof(errbuf),
384: "Too many '/' in \"%s\"", device);
385: return (errbuf);
386: }
387:
388: /*
389: * open will fail on slip lines or exclusive-use lines
390: * if not running as root; not an error.
391: */
392: if ((fd = open(device, O_WRONLY|O_NONBLOCK, 0)) < 0) {
393: if (errno == EBUSY || errno == EACCES)
394: return (NULL);
395: (void) snprintf(errbuf, sizeof(errbuf), "%s: %s", device,
396: strerror(errno));
397: return (errbuf);
398: }
399:
400: for (cnt = 0, left = 0; cnt < iovcnt; ++cnt)
401: left += iov[cnt].iov_len;
402:
403: for (;;) {
404: wret = writev(fd, iov, iovcnt);
405: if (wret >= left)
406: break;
407: if (wret >= 0) {
408: left -= wret;
409: if (iov != localiov) {
410: bcopy(iov, localiov,
411: iovcnt * sizeof(struct iovec));
412: iov = localiov;
413: }
414: for (cnt = 0; (size_t)wret >= iov->iov_len; ++cnt) {
415: wret -= iov->iov_len;
416: ++iov;
417: --iovcnt;
418: }
419: if (wret) {
420: iov->iov_base = (char *)iov->iov_base + wret;
421: iov->iov_len -= wret;
422: }
423: continue;
424: }
425: if (errno == EWOULDBLOCK) {
426: int cpid;
427:
428: if (forked) {
429: (void) close(fd);
430: _exit(1);
431: }
432: cpid = fork();
433: if (cpid < 0) {
434: (void) snprintf(errbuf, sizeof(errbuf),
435: "fork: %s", strerror(errno));
436: (void) close(fd);
437: return (errbuf);
438: }
439: if (cpid) { /* parent */
440: (void) close(fd);
441: return (NULL);
442: }
443: forked++;
444: /* wait at most tmout seconds */
445: (void) signal(SIGALRM, SIG_DFL);
446: (void) signal(SIGTERM, SIG_DFL); /* XXX */
447: (void) sigsetmask(0);
448: (void) alarm((u_int)tmout);
449: (void) fcntl(fd, F_SETFL, 0); /* clear O_NONBLOCK */
450: continue;
451: }
452: /*
453: * We get ENODEV on a slip line if we're running as root,
454: * and EIO if the line just went away.
455: */
456: if (errno == ENODEV || errno == EIO)
457: break;
458: (void) close(fd);
459: if (forked)
460: _exit(1);
461: (void) snprintf(errbuf, sizeof(errbuf),
462: "%s: %s", device, strerror(errno));
463: return (errbuf);
464: }
465:
466: (void) close(fd);
467: if (forked)
468: _exit(0);
469: return (NULL);
470: }
471:
472: static ssize_t
473: rbwrite(struct filed *f, char *buf, size_t nbytes)
474: {
475: ssize_t err, out = 0;
476: size_t maxwrite = f->f_un.f_ring.f_footer->cf_max - f->f_un.f_ring.f_footer->cf_next;
477:
478: f->f_un.f_ring.f_footer->cf_lock = 1;
479: while (nbytes > 0) {
480: maxwrite = f->f_un.f_ring.f_footer->cf_max - f->f_un.f_ring.f_footer->cf_next;
481: if (maxwrite > nbytes)
482: maxwrite = nbytes;
483: err = pwrite(f->f_file, buf, maxwrite, f->f_un.f_ring.f_footer->cf_next);
484: if (err == -1) {
485: f->f_un.f_ring.f_footer->cf_lock = 0;
486: return -1;
487: }
488: nbytes -= err;
489: out += err;
490: buf += err;
491: f->f_un.f_ring.f_footer->cf_next += err;
492: if (f->f_un.f_ring.f_footer->cf_next == f->f_un.f_ring.f_footer->cf_max) {
493: f->f_un.f_ring.f_footer->cf_next = 0;
494: f->f_un.f_ring.f_footer->cf_wrap = 1;
495: }
496: }
497:
498: f->f_un.f_ring.f_footer->cf_lock = 0;
499: return out;
500: }
501: static ssize_t
502: rbwritev(struct filed *f, struct iovec *iov, int iovcnt)
503: {
504: register int i;
505: ssize_t err, out = 0;
506:
507: for(i = 0; i < iovcnt; i++) {
508: err = rbwrite(f, iov[i].iov_base, iov[i].iov_len);
509: if (err == -1)
510: return -1;
511: out += err;
512: }
513:
514: return out;
515: }
516: // CPP::
517:
518: int
519: main(int argc, char *argv[])
520: {
521: int ch, i, fdsrmax = 0, l;
522: struct sockaddr_un sunx, fromunix;
523: struct sockaddr_storage frominet;
524: fd_set *fdsr = NULL;
525: char line[MAXLINE + 1];
526: char *bindhostname;
527: const char *hname;
528: struct timeval tv, *tvp;
529: struct sigaction sact;
530: struct funix *fx, *fx1;
531: sigset_t mask;
532: pid_t ppid = 1, spid;
533: socklen_t len;
534:
535: if (madvise(NULL, 0, MADV_PROTECT) != 0)
536: dprintf("madvise() failed: %s\n", strerror(errno));
537:
538: bindhostname = NULL;
539: while ((ch = getopt(argc, argv, "468Aa:b:cCdf:kl:m:nop:P:sS:Tuv"))
540: != -1)
541: switch (ch) {
542: case '4':
543: family = PF_INET;
544: break;
545: #ifdef INET6
546: case '6':
547: family = PF_INET6;
548: break;
549: #endif
550: case '8':
551: mask_C1 = 0;
552: break;
553: case 'A':
554: send_to_all++;
555: break;
556: case 'a': /* allow specific network addresses only */
557: if (allowaddr(optarg) == -1)
558: usage();
559: break;
560: case 'b':
561: bindhostname = optarg;
562: break;
563: case 'c':
564: no_compress++;
565: break;
566: case 'C':
567: logflags |= O_CREAT;
568: break;
569: case 'd': /* debug */
570: Debug++;
571: break;
572: case 'f': /* configuration file */
573: ConfFile = optarg;
574: break;
575: case 'k': /* keep remote kern fac */
576: KeepKernFac = 1;
577: break;
578: case 'l':
579: {
580: long perml;
581: mode_t mode;
582: char *name, *ep;
583:
584: if (optarg[0] == '/') {
585: mode = DEFFILEMODE;
586: name = optarg;
587: } else if ((name = strchr(optarg, ':')) != NULL) {
588: *name++ = '\0';
589: if (name[0] != '/')
590: errx(1, "socket name must be absolute "
591: "path");
592: if (isdigit(*optarg)) {
593: perml = strtol(optarg, &ep, 8);
594: if (*ep || perml < 0 ||
595: perml & ~(S_IRWXU|S_IRWXG|S_IRWXO))
596: errx(1, "invalid mode %s, exiting",
597: optarg);
598: mode = (mode_t )perml;
599: } else
600: errx(1, "invalid mode %s, exiting",
601: optarg);
602: } else /* doesn't begin with '/', and no ':' */
603: errx(1, "can't parse path %s", optarg);
604:
605: if (strlen(name) >= sizeof(sunx.sun_path))
606: errx(1, "%s path too long, exiting", name);
607: if ((fx = malloc(sizeof(struct funix))) == NULL)
608: errx(1, "malloc failed");
609: fx->s = -1;
610: fx->name = name;
611: fx->mode = mode;
612: STAILQ_INSERT_TAIL(&funixes, fx, next);
613: break;
614: }
615: case 'm': /* mark interval */
616: MarkInterval = atoi(optarg) * 60;
617: break;
618: case 'n':
619: resolve = 0;
620: break;
621: case 'o':
622: use_bootfile = 1;
623: break;
624: case 'p': /* path */
625: if (strlen(optarg) >= sizeof(sunx.sun_path))
626: errx(1, "%s path too long, exiting", optarg);
627: funix_default.name = optarg;
628: break;
629: case 'P': /* path for alt. PID */
630: PidFile = optarg;
631: break;
632: case 's': /* no network mode */
633: SecureMode++;
634: break;
635: case 'S': /* path for privileged originator */
636: if (strlen(optarg) >= sizeof(sunx.sun_path))
637: errx(1, "%s path too long, exiting", optarg);
638: funix_secure.name = optarg;
639: break;
640: case 'T':
641: RemoteAddDate = 1;
642: break;
643: case 'u': /* only log specified priority */
644: UniquePriority++;
645: break;
646: case 'v': /* log facility and priority */
647: LogFacPri++;
648: break;
649: default:
650: usage();
651: }
652: if ((argc -= optind) != 0)
653: usage();
654:
655: pfh = pidfile_open(PidFile, 0600, &spid);
656: if (pfh == NULL) {
657: if (errno == EEXIST)
658: errx(1, "syslogd already running, pid: %d", spid);
659: warn("cannot open pid file");
660: }
661:
662: if (!Debug) {
663: ppid = waitdaemon(0, 0, 30);
664: if (ppid < 0) {
665: warn("could not become daemon");
666: pidfile_remove(pfh);
667: exit(1);
668: }
669: } else {
670: setlinebuf(stdout);
671: }
672:
673: if (NumAllowed)
674: endservent();
675:
676: consfile.f_type = F_CONSOLE;
677: (void)strlcpy(consfile.f_un.f_fname, ctty + sizeof _PATH_DEV - 1,
678: sizeof(consfile.f_un.f_fname));
679: (void)strlcpy(bootfile, getbootfile(), sizeof(bootfile));
680: (void)signal(SIGTERM, dodie);
681: (void)signal(SIGINT, Debug ? dodie : SIG_IGN);
682: (void)signal(SIGQUIT, Debug ? dodie : SIG_IGN);
683: /*
684: * We don't want the SIGCHLD and SIGHUP handlers to interfere
685: * with each other; they are likely candidates for being called
686: * simultaneously (SIGHUP closes pipe descriptor, process dies,
687: * SIGCHLD happens).
688: */
689: sigemptyset(&mask);
690: sigaddset(&mask, SIGHUP);
691: sact.sa_handler = reapchild;
692: sact.sa_mask = mask;
693: sact.sa_flags = SA_RESTART;
694: (void)sigaction(SIGCHLD, &sact, NULL);
695: (void)signal(SIGALRM, domark);
696: (void)signal(SIGPIPE, SIG_IGN); /* We'll catch EPIPE instead. */
697: (void)alarm(TIMERINTVL);
698:
699: TAILQ_INIT(&deadq_head);
700:
701: #ifndef SUN_LEN
702: #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
703: #endif
704: STAILQ_FOREACH_SAFE(fx, &funixes, next, fx1) {
705: (void)unlink(fx->name);
706: memset(&sunx, 0, sizeof(sunx));
707: sunx.sun_family = AF_LOCAL;
708: (void)strlcpy(sunx.sun_path, fx->name, sizeof(sunx.sun_path));
709: fx->s = socket(PF_LOCAL, SOCK_DGRAM, 0);
710: if (fx->s < 0 ||
711: bind(fx->s, (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
712: chmod(fx->name, fx->mode) < 0) {
713: (void)snprintf(line, sizeof line,
714: "cannot create %s", fx->name);
715: logerror(line);
716: dprintf("cannot create %s (%d)\n", fx->name, errno);
717: if (fx == &funix_default || fx == &funix_secure)
718: die(0);
719: else {
720: STAILQ_REMOVE(&funixes, fx, funix, next);
721: continue;
722: }
723: double_rbuf(fx->s);
724: }
725: }
726: if (SecureMode <= 1)
727: finet = socksetup(family, bindhostname);
728:
729: if (finet) {
730: if (SecureMode) {
731: for (i = 0; i < *finet; i++) {
732: if (shutdown(finet[i+1], SHUT_RD) < 0) {
733: logerror("shutdown");
734: if (!Debug)
735: die(0);
736: }
737: }
738: } else {
739: dprintf("listening on inet and/or inet6 socket\n");
740: }
741: dprintf("sending on inet and/or inet6 socket\n");
742: }
743:
744: if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) >= 0)
745: if (fcntl(fklog, F_SETFL, O_NONBLOCK) < 0)
746: fklog = -1;
747: if (fklog < 0)
748: dprintf("can't open %s (%d)\n", _PATH_KLOG, errno);
749:
750: /* tuck my process id away */
751: pidfile_write(pfh);
752:
753: dprintf("off & running....\n");
754:
755: init(0);
756: /* prevent SIGHUP and SIGCHLD handlers from running in parallel */
757: sigemptyset(&mask);
758: sigaddset(&mask, SIGCHLD);
759: sact.sa_handler = init;
760: sact.sa_mask = mask;
761: sact.sa_flags = SA_RESTART;
762: (void)sigaction(SIGHUP, &sact, NULL);
763:
764: tvp = &tv;
765: tv.tv_sec = tv.tv_usec = 0;
766:
767: if (fklog != -1 && fklog > fdsrmax)
768: fdsrmax = fklog;
769: if (finet && !SecureMode) {
770: for (i = 0; i < *finet; i++) {
771: if (finet[i+1] != -1 && finet[i+1] > fdsrmax)
772: fdsrmax = finet[i+1];
773: }
774: }
775: STAILQ_FOREACH(fx, &funixes, next)
776: if (fx->s > fdsrmax)
777: fdsrmax = fx->s;
778:
779: fdsr = (fd_set *)calloc(howmany(fdsrmax+1, NFDBITS),
780: sizeof(fd_mask));
781: if (fdsr == NULL)
782: errx(1, "calloc fd_set");
783:
784: for (;;) {
785: if (MarkSet)
786: markit();
787: if (WantDie)
788: die(WantDie);
789:
790: bzero(fdsr, howmany(fdsrmax+1, NFDBITS) *
791: sizeof(fd_mask));
792:
793: if (fklog != -1)
794: FD_SET(fklog, fdsr);
795: if (finet && !SecureMode) {
796: for (i = 0; i < *finet; i++) {
797: if (finet[i+1] != -1)
798: FD_SET(finet[i+1], fdsr);
799: }
800: }
801: STAILQ_FOREACH(fx, &funixes, next)
802: FD_SET(fx->s, fdsr);
803:
804: i = select(fdsrmax+1, fdsr, NULL, NULL,
805: needdofsync ? &tv : tvp);
806: switch (i) {
807: case 0:
808: dofsync();
809: needdofsync = 0;
810: if (tvp) {
811: tvp = NULL;
812: if (ppid != 1)
813: kill(ppid, SIGALRM);
814: }
815: continue;
816: case -1:
817: if (errno != EINTR)
818: logerror("select");
819: continue;
820: }
821: if (fklog != -1 && FD_ISSET(fklog, fdsr))
822: readklog();
823: if (finet && !SecureMode) {
824: for (i = 0; i < *finet; i++) {
825: if (FD_ISSET(finet[i+1], fdsr)) {
826: len = sizeof(frominet);
827: l = recvfrom(finet[i+1], line, MAXLINE,
828: 0, (struct sockaddr *)&frominet,
829: &len);
830: if (l > 0) {
831: line[l] = '\0';
832: hname = cvthname((struct sockaddr *)&frominet);
833: unmapped((struct sockaddr *)&frominet);
834: if (validate((struct sockaddr *)&frominet, hname))
835: printline(hname, line, RemoteAddDate ? ADDDATE : 0);
836: } else if (l < 0 && errno != EINTR)
837: logerror("recvfrom inet");
838: }
839: }
840: }
841: STAILQ_FOREACH(fx, &funixes, next) {
842: if (FD_ISSET(fx->s, fdsr)) {
843: len = sizeof(fromunix);
844: l = recvfrom(fx->s, line, MAXLINE, 0,
845: (struct sockaddr *)&fromunix, &len);
846: if (l > 0) {
847: line[l] = '\0';
848: printline(LocalHostName, line, 0);
849: } else if (l < 0 && errno != EINTR)
850: logerror("recvfrom unix");
851: }
852: }
853: }
854: if (fdsr)
855: free(fdsr);
856: }
857:
858: static void
859: unmapped(struct sockaddr *sa)
860: {
861: struct sockaddr_in6 *sin6;
862: struct sockaddr_in sin4;
863:
864: if (sa->sa_family != AF_INET6)
865: return;
866: if (sa->sa_len != sizeof(struct sockaddr_in6) ||
867: sizeof(sin4) > sa->sa_len)
868: return;
869: sin6 = (struct sockaddr_in6 *)sa;
870: if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
871: return;
872:
873: memset(&sin4, 0, sizeof(sin4));
874: sin4.sin_family = AF_INET;
875: sin4.sin_len = sizeof(struct sockaddr_in);
876: memcpy(&sin4.sin_addr, &sin6->sin6_addr.s6_addr[12],
877: sizeof(sin4.sin_addr));
878: sin4.sin_port = sin6->sin6_port;
879:
880: memcpy(sa, &sin4, sin4.sin_len);
881: }
882:
883: static void
884: usage(void)
885: {
886:
887: fprintf(stderr, "%s\n%s\n%s\n%s\n",
888: "usage: syslogd [-468ACcdknosTuv] [-a allowed_peer]",
889: " [-b bind_address] [-f config_file]",
890: " [-l [mode:]path] [-m mark_interval]",
891: " [-P pid_file] [-p log_socket]");
892: exit(1);
893: }
894:
895: /*
896: * Take a raw input line, decode the message, and print the message
897: * on the appropriate log files.
898: */
899: static void
900: printline(const char *hname, char *msg, int flags)
901: {
902: char *p, *q;
903: long n;
904: int c, pri;
905: char line[MAXLINE + 1];
906:
907: /* test for special codes */
908: p = msg;
909: pri = DEFUPRI;
910: if (*p == '<') {
911: errno = 0;
912: n = strtol(p + 1, &q, 10);
913: if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
914: p = q + 1;
915: pri = n;
916: }
917: }
918: if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
919: pri = DEFUPRI;
920:
921: /*
922: * Don't allow users to log kernel messages.
923: * NOTE: since LOG_KERN == 0 this will also match
924: * messages with no facility specified.
925: */
926: if ((pri & LOG_FACMASK) == LOG_KERN && !KeepKernFac)
927: pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
928:
929: q = line;
930:
931: while ((c = (unsigned char)*p++) != '\0' &&
932: q < &line[sizeof(line) - 4]) {
933: if (mask_C1 && (c & 0x80) && c < 0xA0) {
934: c &= 0x7F;
935: *q++ = 'M';
936: *q++ = '-';
937: }
938: if (isascii(c) && iscntrl(c)) {
939: if (c == '\n') {
940: *q++ = ' ';
941: } else if (c == '\t') {
942: *q++ = '\t';
943: } else {
944: *q++ = '^';
945: *q++ = c ^ 0100;
946: }
947: } else {
948: *q++ = c;
949: }
950: }
951: *q = '\0';
952:
953: logmsg(pri, line, hname, flags);
954: }
955:
956: /*
957: * Read /dev/klog while data are available, split into lines.
958: */
959: static void
960: readklog(void)
961: {
962: char *p, *q, line[MAXLINE + 1];
963: int len, i;
964:
965: len = 0;
966: for (;;) {
967: i = read(fklog, line + len, MAXLINE - 1 - len);
968: if (i > 0) {
969: line[i + len] = '\0';
970: } else {
971: if (i < 0 && errno != EINTR && errno != EAGAIN) {
972: logerror("klog");
973: fklog = -1;
974: }
975: break;
976: }
977:
978: for (p = line; (q = strchr(p, '\n')) != NULL; p = q + 1) {
979: *q = '\0';
980: printsys(p);
981: }
982: len = strlen(p);
983: if (len >= MAXLINE - 1) {
984: printsys(p);
985: len = 0;
986: }
987: if (len > 0)
988: memmove(line, p, len + 1);
989: }
990: if (len > 0)
991: printsys(line);
992: }
993:
994: /*
995: * Take a raw input line from /dev/klog, format similar to syslog().
996: */
997: static void
998: printsys(char *msg)
999: {
1000: char *p, *q;
1001: long n;
1002: int flags, isprintf, pri;
1003:
1004: flags = ISKERNEL | SYNC_FILE | ADDDATE; /* fsync after write */
1005: p = msg;
1006: pri = DEFSPRI;
1007: isprintf = 1;
1008: if (*p == '<') {
1009: errno = 0;
1010: n = strtol(p + 1, &q, 10);
1011: if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
1012: p = q + 1;
1013: pri = n;
1014: isprintf = 0;
1015: }
1016: }
1017: /*
1018: * Kernel printf's and LOG_CONSOLE messages have been displayed
1019: * on the console already.
1020: */
1021: if (isprintf || (pri & LOG_FACMASK) == LOG_CONSOLE)
1022: flags |= IGN_CONS;
1023: if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
1024: pri = DEFSPRI;
1025: logmsg(pri, p, LocalHostName, flags);
1026: }
1027:
1028: static time_t now;
1029:
1030: /*
1031: * Match a program or host name against a specification.
1032: * Return a non-0 value if the message must be ignored
1033: * based on the specification.
1034: */
1035: static int
1036: skip_message(const char *name, const char *spec, int checkcase)
1037: {
1038: const char *s;
1039: char prev, next;
1040: int exclude = 0;
1041: /* Behaviour on explicit match */
1042:
1043: if (spec == NULL)
1044: return 0;
1045: switch (*spec) {
1046: case '-':
1047: exclude = 1;
1048: /*FALLTHROUGH*/
1049: case '+':
1050: spec++;
1051: break;
1052: default:
1053: break;
1054: }
1055: if (checkcase)
1056: s = strstr (spec, name);
1057: else
1058: s = strcasestr (spec, name);
1059:
1060: if (s != NULL) {
1061: prev = (s == spec ? ',' : *(s - 1));
1062: next = *(s + strlen (name));
1063:
1064: if (prev == ',' && (next == '\0' || next == ','))
1065: /* Explicit match: skip iff the spec is an
1066: exclusive one. */
1067: return exclude;
1068: }
1069:
1070: /* No explicit match for this name: skip the message iff
1071: the spec is an inclusive one. */
1072: return !exclude;
1073: }
1074:
1075: /*
1076: * Log a message to the appropriate log files, users, etc. based on
1077: * the priority.
1078: */
1079: static void
1080: logmsg(int pri, const char *msg, const char *from, int flags)
1081: {
1082: struct filed *f;
1083: int i, fac, msglen, omask, prilev;
1084: const char *timestamp;
1085: char prog[NAME_MAX+1];
1086: char buf[MAXLINE+1];
1087:
1088: dprintf("logmsg: pri %o, flags %x, from %s, msg %s\n",
1089: pri, flags, from, msg);
1090:
1091: omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
1092:
1093: /*
1094: * Check to see if msg looks non-standard.
1095: */
1096: msglen = strlen(msg);
1097: if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
1098: msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
1099: flags |= ADDDATE;
1100:
1101: (void)time(&now);
1102: if (flags & ADDDATE) {
1103: timestamp = ctime(&now) + 4;
1104: } else {
1105: timestamp = msg;
1106: msg += 16;
1107: msglen -= 16;
1108: }
1109:
1110: /* skip leading blanks */
1111: while (isspace(*msg)) {
1112: msg++;
1113: msglen--;
1114: }
1115:
1116: /* extract facility and priority level */
1117: if (flags & MARK)
1118: fac = LOG_NFACILITIES;
1119: else
1120: fac = LOG_FAC(pri);
1121:
1122: /* Check maximum facility number. */
1123: if (fac > LOG_NFACILITIES) {
1124: (void)sigsetmask(omask);
1125: return;
1126: }
1127:
1128: prilev = LOG_PRI(pri);
1129:
1130: /* extract program name */
1131: for (i = 0; i < NAME_MAX; i++) {
1132: if (!isprint(msg[i]) || msg[i] == ':' || msg[i] == '[' ||
1133: msg[i] == '/' || isspace(msg[i]))
1134: break;
1135: prog[i] = msg[i];
1136: }
1137: prog[i] = 0;
1138:
1139: /* add kernel prefix for kernel messages */
1140: if (flags & ISKERNEL) {
1141: snprintf(buf, sizeof(buf), "%s: %s",
1142: use_bootfile ? bootfile : "kernel", msg);
1143: msg = buf;
1144: msglen = strlen(buf);
1145: }
1146:
1147: /* log the message to the particular outputs */
1148: if (!Initialized) {
1149: f = &consfile;
1150: /*
1151: * Open in non-blocking mode to avoid hangs during open
1152: * and close(waiting for the port to drain).
1153: */
1154: f->f_file = open(ctty, O_WRONLY | O_NONBLOCK, 0);
1155:
1156: if (f->f_file >= 0) {
1157: (void)strlcpy(f->f_lasttime, timestamp,
1158: sizeof(f->f_lasttime));
1159: fprintlog(f, flags, msg);
1160: (void)close(f->f_file);
1161: }
1162: (void)sigsetmask(omask);
1163: return;
1164: }
1165: for (f = Files; f; f = f->f_next) {
1166: /* skip messages that are incorrect priority */
1167: if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
1168: ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
1169: ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
1170: )
1171: || f->f_pmask[fac] == INTERNAL_NOPRI)
1172: continue;
1173:
1174: /* skip messages with the incorrect hostname */
1175: if (skip_message(from, f->f_host, 0))
1176: continue;
1177:
1178: /* skip messages with the incorrect program name */
1179: if (skip_message(prog, f->f_program, 1))
1180: continue;
1181:
1182: /* skip message to console if it has already been printed */
1183: if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
1184: continue;
1185:
1186: /* don't output marks to recently written files */
1187: if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1188: continue;
1189:
1190: /*
1191: * suppress duplicate lines to this file
1192: */
1193: if (no_compress - (f->f_type != F_PIPE) < 1 &&
1194: (flags & MARK) == 0 && msglen == f->f_prevlen &&
1195: f->f_prevline && !strcmp(msg, f->f_prevline) &&
1196: !strcasecmp(from, f->f_prevhost)) {
1197: (void)strlcpy(f->f_lasttime, timestamp,
1198: sizeof(f->f_lasttime));
1199: f->f_prevcount++;
1200: dprintf("msg repeated %d times, %ld sec of %d\n",
1201: f->f_prevcount, (long)(now - f->f_time),
1202: repeatinterval[f->f_repeatcount]);
1203: /*
1204: * If domark would have logged this by now,
1205: * flush it now (so we don't hold isolated messages),
1206: * but back off so we'll flush less often
1207: * in the future.
1208: */
1209: if (now > REPEATTIME(f)) {
1210: fprintlog(f, flags, (char *)NULL);
1211: BACKOFF(f);
1212: }
1213: } else {
1214: /* new line, save it */
1215: if (f->f_prevcount)
1216: fprintlog(f, 0, (char *)NULL);
1217: f->f_repeatcount = 0;
1218: f->f_prevpri = pri;
1219: (void)strlcpy(f->f_lasttime, timestamp,
1220: sizeof(f->f_lasttime));
1221: (void)strlcpy(f->f_prevhost, from,
1222: sizeof(f->f_prevhost));
1223: if (msglen < MAXSVLINE) {
1224: f->f_prevlen = msglen;
1225: (void)strlcpy(f->f_prevline, msg, sizeof(f->f_prevline));
1226: fprintlog(f, flags, (char *)NULL);
1227: } else {
1228: f->f_prevline[0] = 0;
1229: f->f_prevlen = 0;
1230: fprintlog(f, flags, msg);
1231: }
1232: }
1233: }
1234: (void)sigsetmask(omask);
1235: }
1236:
1237: static void
1238: dofsync(void)
1239: {
1240: struct filed *f;
1241:
1242: for (f = Files; f; f = f->f_next) {
1243: if ((f->f_type == F_FILE) &&
1244: (f->f_flags & FFLAG_NEEDSYNC)) {
1245: f->f_flags &= ~FFLAG_NEEDSYNC;
1246: (void)fsync(f->f_file);
1247: }
1248: }
1249: }
1250:
1251: #define IOV_SIZE 7
1252: static void
1253: fprintlog(struct filed *f, int flags, const char *msg)
1254: {
1255: struct iovec iov[IOV_SIZE];
1256: struct iovec *v;
1257: struct addrinfo *r;
1258: int i, l, lsent = 0;
1259: char line[MAXLINE + 1], repbuf[80], greetings[200], *wmsg = NULL;
1260: char nul[] = "", space[] = " ", lf[] = "\n", crlf[] = "\r\n";
1261: const char *msgret;
1262:
1263: v = iov;
1264: if (f->f_type == F_WALL) {
1265: v->iov_base = greetings;
1266: /* The time displayed is not synchornized with the other log
1267: * destinations (like messages). Following fragment was using
1268: * ctime(&now), which was updating the time every 30 sec.
1269: * With f_lasttime, time is synchronized correctly.
1270: */
1271: v->iov_len = snprintf(greetings, sizeof greetings,
1272: "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
1273: f->f_prevhost, f->f_lasttime);
1274: if (v->iov_len > 0)
1275: v++;
1276: v->iov_base = nul;
1277: v->iov_len = 0;
1278: v++;
1279: } else {
1280: v->iov_base = f->f_lasttime;
1281: v->iov_len = strlen(f->f_lasttime);
1282: v++;
1283: v->iov_base = space;
1284: v->iov_len = 1;
1285: v++;
1286: }
1287:
1288: if (LogFacPri) {
1289: static char fp_buf[30]; /* Hollow laugh */
1290: int fac = f->f_prevpri & LOG_FACMASK;
1291: int pri = LOG_PRI(f->f_prevpri);
1292: const char *f_s = NULL;
1293: char f_n[5]; /* Hollow laugh */
1294: const char *p_s = NULL;
1295: char p_n[5]; /* Hollow laugh */
1296:
1297: if (LogFacPri > 1) {
1298: CODE *c;
1299:
1300: for (c = facilitynames; c->c_name; c++) {
1301: if (c->c_val == fac) {
1302: f_s = c->c_name;
1303: break;
1304: }
1305: }
1306: for (c = prioritynames; c->c_name; c++) {
1307: if (c->c_val == pri) {
1308: p_s = c->c_name;
1309: break;
1310: }
1311: }
1312: }
1313: if (!f_s) {
1314: snprintf(f_n, sizeof f_n, "%d", LOG_FAC(fac));
1315: f_s = f_n;
1316: }
1317: if (!p_s) {
1318: snprintf(p_n, sizeof p_n, "%d", pri);
1319: p_s = p_n;
1320: }
1321: snprintf(fp_buf, sizeof fp_buf, "<%s.%s> ", f_s, p_s);
1322: v->iov_base = fp_buf;
1323: v->iov_len = strlen(fp_buf);
1324: } else {
1325: v->iov_base = nul;
1326: v->iov_len = 0;
1327: }
1328: v++;
1329:
1330: v->iov_base = f->f_prevhost;
1331: v->iov_len = strlen(v->iov_base);
1332: v++;
1333: v->iov_base = space;
1334: v->iov_len = 1;
1335: v++;
1336:
1337: if (msg) {
1338: wmsg = strdup(msg); /* XXX iov_base needs a `const' sibling. */
1339: if (wmsg == NULL) {
1340: logerror("strdup");
1341: exit(1);
1342: }
1343: v->iov_base = wmsg;
1344: v->iov_len = strlen(msg);
1345: } else if (f->f_prevcount > 1) {
1346: v->iov_base = repbuf;
1347: v->iov_len = snprintf(repbuf, sizeof repbuf,
1348: "last message repeated %d times", f->f_prevcount);
1349: } else if (f->f_prevline) {
1350: v->iov_base = f->f_prevline;
1351: v->iov_len = f->f_prevlen;
1352: } else {
1353: return;
1354: }
1355: v++;
1356:
1357: dprintf("Logging to %s", TypeNames[f->f_type]);
1358: f->f_time = now;
1359:
1360: switch (f->f_type) {
1361: int port;
1362: case F_UNUSED:
1363: dprintf("\n");
1364: break;
1365:
1366: case F_FORW:
1367: port = (int)ntohs(((struct sockaddr_in *)
1368: (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1369: if (port != 514) {
1370: dprintf(" %s:%d\n", f->f_un.f_forw.f_hname, port);
1371: } else {
1372: dprintf(" %s\n", f->f_un.f_forw.f_hname);
1373: }
1374: /* check for local vs remote messages */
1375: if (strcasecmp(f->f_prevhost, LocalHostName))
1376: l = snprintf(line, sizeof line - 1,
1377: "<%d>%.15s Forwarded from %s: %s",
1378: f->f_prevpri, (char *)iov[0].iov_base,
1379: f->f_prevhost, (char *)iov[5].iov_base);
1380: else
1381: l = snprintf(line, sizeof line - 1, "<%d>%.15s %s",
1382: f->f_prevpri, (char *)iov[0].iov_base,
1383: (char *)iov[5].iov_base);
1384: if (l < 0)
1385: l = 0;
1386: else if (l > MAXLINE)
1387: l = MAXLINE;
1388:
1389: if (finet) {
1390: for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
1391: for (i = 0; i < *finet; i++) {
1392: #if 0
1393: /*
1394: * should we check AF first, or just
1395: * trial and error? FWD
1396: */
1397: if (r->ai_family ==
1398: address_family_of(finet[i+1]))
1399: #endif
1400: lsent = sendto(finet[i+1], line, l, 0,
1401: r->ai_addr, r->ai_addrlen);
1402: if (lsent == l)
1403: break;
1404: }
1405: if (lsent == l && !send_to_all)
1406: break;
1407: }
1408: dprintf("lsent/l: %d/%d\n", lsent, l);
1409: if (lsent != l) {
1410: int e = errno;
1411: logerror("sendto");
1412: errno = e;
1413: switch (errno) {
1414: case ENOBUFS:
1415: case ENETDOWN:
1416: case EHOSTUNREACH:
1417: case EHOSTDOWN:
1418: break;
1419: /* case EBADF: */
1420: /* case EACCES: */
1421: /* case ENOTSOCK: */
1422: /* case EFAULT: */
1423: /* case EMSGSIZE: */
1424: /* case EAGAIN: */
1425: /* case ENOBUFS: */
1426: /* case ECONNREFUSED: */
1427: default:
1428: dprintf("removing entry\n");
1429: f->f_type = F_UNUSED;
1430: break;
1431: }
1432: }
1433: }
1434: break;
1435:
1436: case F_FILE:
1437: dprintf(" %s\n", f->f_un.f_fname);
1438: v->iov_base = lf;
1439: v->iov_len = 1;
1440: if (writev(f->f_file, iov, IOV_SIZE) < 0) {
1441: /*
1442: * If writev(2) fails for potentially transient errors
1443: * like the filesystem being full, ignore it.
1444: * Otherwise remove this logfile from the list.
1445: */
1446: if (errno != ENOSPC) {
1447: int e = errno;
1448: (void)close(f->f_file);
1449: f->f_type = F_UNUSED;
1450: errno = e;
1451: logerror(f->f_un.f_fname);
1452: }
1453: } else if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC)) {
1454: f->f_flags |= FFLAG_NEEDSYNC;
1455: needdofsync = 1;
1456: }
1457: break;
1458:
1459: // CPP:
1460: case F_RING:
1461: dprintf(" %s\n", f->f_un.f_ring.f_rname);
1462: v->iov_base = "\n";
1463: v->iov_len = 1;
1464: if (rbwritev(f, iov, 7) == -1) {
1465: int e = errno;
1466:
1467: munmap(f->f_un.f_ring.f_footer, sizeof(struct clogFooter));
1468: close(f->f_file);
1469: f->f_type = F_UNUSED;
1470: errno = e;
1471: logerror(f->f_un.f_fname);
1472: }
1473: break;
1474: // CPP::
1475:
1476: case F_PIPE:
1477: dprintf(" %s\n", f->f_un.f_pipe.f_pname);
1478: v->iov_base = lf;
1479: v->iov_len = 1;
1480: if (f->f_un.f_pipe.f_pid == 0) {
1481: if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
1482: &f->f_un.f_pipe.f_pid)) < 0) {
1483: f->f_type = F_UNUSED;
1484: logerror(f->f_un.f_pipe.f_pname);
1485: break;
1486: }
1487: }
1488: if (writev(f->f_file, iov, IOV_SIZE) < 0) {
1489: int e = errno;
1490: (void)close(f->f_file);
1491: if (f->f_un.f_pipe.f_pid > 0)
1492: deadq_enter(f->f_un.f_pipe.f_pid,
1493: f->f_un.f_pipe.f_pname);
1494: f->f_un.f_pipe.f_pid = 0;
1495: errno = e;
1496: logerror(f->f_un.f_pipe.f_pname);
1497: }
1498: break;
1499:
1500: case F_CONSOLE:
1501: if (flags & IGN_CONS) {
1502: dprintf(" (ignored)\n");
1503: break;
1504: }
1505: /* FALLTHROUGH */
1506:
1507: case F_TTY:
1508: dprintf(" %s%s\n", _PATH_DEV, f->f_un.f_fname);
1509: v->iov_base = crlf;
1510: v->iov_len = 2;
1511:
1512: errno = 0; /* ttymsg() only sometimes returns an errno */
1513: if ((msgret = ttymsg(iov, IOV_SIZE, f->f_un.f_fname, 10))) {
1514: f->f_type = F_UNUSED;
1515: logerror(msgret);
1516: }
1517: break;
1518:
1519: case F_USERS:
1520: case F_WALL:
1521: dprintf("\n");
1522: v->iov_base = crlf;
1523: v->iov_len = 2;
1524: wallmsg(f, iov, IOV_SIZE);
1525: break;
1526: }
1527: f->f_prevcount = 0;
1528: free(wmsg);
1529: }
1530:
1531: /*
1532: * WALLMSG -- Write a message to the world at large
1533: *
1534: * Write the specified message to either the entire
1535: * world, or a list of approved users.
1536: */
1537: static void
1538: wallmsg(struct filed *f, struct iovec *iov, const int iovlen)
1539: {
1540: static int reenter; /* avoid calling ourselves */
1541: int i;
1542: const char *p;
1543:
1544: if (reenter++)
1545: return;
1546: #if defined(__FreeBSD__) && (__FreeBSD__ > 8)
1547: struct utmpx *ut;
1548:
1549: setutxent();
1550: /* NOSTRICT */
1551: while ((ut = getutxent()) != NULL) {
1552: if (ut->ut_type != USER_PROCESS)
1553: continue;
1554: #else
1555: struct utmp ut_, *ut = &ut_;
1556: FILE *uf;
1557: char line[sizeof(ut_.ut_line) + 1];
1558:
1559: if ((uf = fopen(_PATH_UTMP, "r")) == NULL) {
1560: logerror(_PATH_UTMP);
1561: reenter = 0;
1562: return;
1563: }
1564: /* NOSTRICT */
1565: while (fread((char *)ut, sizeof(ut_), 1, uf) == 1) {
1566: if (ut->ut_name[0] == '\0')
1567: continue;
1568: /* We must use strncpy since ut_* may not be NUL terminated. */
1569: strncpy(line, ut->ut_line, sizeof(line) - 1);
1570: line[sizeof(line) - 1] = '\0';
1571: #endif
1572: if (f->f_type == F_WALL) {
1573: if ((p = ttymsg(iov, iovlen, ut->ut_line,
1574: TTYMSGTIME)) != NULL) {
1575: errno = 0; /* already in msg */
1576: logerror(p);
1577: }
1578: continue;
1579: }
1580: /* should we send the message to this user? */
1581: for (i = 0; i < MAXUNAMES; i++) {
1582: if (!f->f_un.f_uname[i][0])
1583: break;
1584: #if defined(__FreeBSD__) && (__FreeBSD__ > 8)
1585: if (!strcmp(f->f_un.f_uname[i], ut->ut_user)) {
1586: #else
1587: if (!strncmp(f->f_un.f_uname[i], ut->ut_name, UT_NAMESIZE)) {
1588: #endif
1589: if ((p = ttymsg(iov, iovlen, ut->ut_line,
1590: TTYMSGTIME)) != NULL) {
1591: errno = 0; /* already in msg */
1592: logerror(p);
1593: }
1594: break;
1595: }
1596: }
1597: }
1598: #if defined(__FreeBSD__) && (__FreeBSD__ > 8)
1599: endutxent();
1600: #else
1601: fclose(uf);
1602: #endif
1603: reenter = 0;
1604: }
1605:
1606: static void
1607: reapchild(int signo __unused)
1608: {
1609: int status;
1610: pid_t pid;
1611: struct filed *f;
1612:
1613: while ((pid = wait3(&status, WNOHANG, (struct rusage *)NULL)) > 0) {
1614: if (!Initialized)
1615: /* Don't tell while we are initting. */
1616: continue;
1617:
1618: /* First, look if it's a process from the dead queue. */
1619: if (deadq_remove(pid))
1620: goto oncemore;
1621:
1622: /* Now, look in list of active processes. */
1623: for (f = Files; f; f = f->f_next)
1624: if (f->f_type == F_PIPE &&
1625: f->f_un.f_pipe.f_pid == pid) {
1626: (void)close(f->f_file);
1627: f->f_un.f_pipe.f_pid = 0;
1628: log_deadchild(pid, status,
1629: f->f_un.f_pipe.f_pname);
1630: break;
1631: }
1632: oncemore:
1633: continue;
1634: }
1635: }
1636:
1637: /*
1638: * Return a printable representation of a host address.
1639: */
1640: static const char *
1641: cvthname(struct sockaddr *f)
1642: {
1643: int error, hl;
1644: sigset_t omask, nmask;
1645: static char hname[NI_MAXHOST], ip[NI_MAXHOST];
1646:
1647: error = getnameinfo((struct sockaddr *)f,
1648: ((struct sockaddr *)f)->sa_len,
1649: ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
1650: dprintf("cvthname(%s)\n", ip);
1651:
1652: if (error) {
1653: dprintf("Malformed from address %s\n", gai_strerror(error));
1654: return ("???");
1655: }
1656: if (!resolve)
1657: return (ip);
1658:
1659: sigemptyset(&nmask);
1660: sigaddset(&nmask, SIGHUP);
1661: sigprocmask(SIG_BLOCK, &nmask, &omask);
1662: error = getnameinfo((struct sockaddr *)f,
1663: ((struct sockaddr *)f)->sa_len,
1664: hname, sizeof hname, NULL, 0, NI_NAMEREQD);
1665: sigprocmask(SIG_SETMASK, &omask, NULL);
1666: if (error) {
1667: dprintf("Host name for your address (%s) unknown\n", ip);
1668: return (ip);
1669: }
1670: hl = strlen(hname);
1671: if (hl > 0 && hname[hl-1] == '.')
1672: hname[--hl] = '\0';
1673: trimdomain(hname, hl);
1674: return (hname);
1675: }
1676:
1677: static void
1678: dodie(int signo)
1679: {
1680:
1681: WantDie = signo;
1682: }
1683:
1684: static void
1685: domark(int signo __unused)
1686: {
1687:
1688: MarkSet = 1;
1689: }
1690:
1691: /*
1692: * Print syslogd errors some place.
1693: */
1694: static void
1695: logerror(const char *type)
1696: {
1697: char buf[512];
1698: static int recursed = 0;
1699:
1700: /* If there's an error while trying to log an error, give up. */
1701: if (recursed)
1702: return;
1703: recursed++;
1704: if (errno)
1705: (void)snprintf(buf,
1706: sizeof buf, "syslogd: %s: %s", type, strerror(errno));
1707: else
1708: (void)snprintf(buf, sizeof buf, "syslogd: %s", type);
1709: errno = 0;
1710: dprintf("%s\n", buf);
1711: logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1712: recursed--;
1713: }
1714:
1715: static void
1716: die(int signo)
1717: {
1718: struct filed *f;
1719: struct funix *fx;
1720: int was_initialized;
1721: char buf[100];
1722:
1723: was_initialized = Initialized;
1724: Initialized = 0; /* Don't log SIGCHLDs. */
1725: for (f = Files; f != NULL; f = f->f_next) {
1726: /* flush any pending output */
1727: if (f->f_prevcount)
1728: fprintlog(f, 0, (char *)NULL);
1729: if (f->f_type == F_PIPE && f->f_un.f_pipe.f_pid > 0) {
1730: (void)close(f->f_file);
1731: f->f_un.f_pipe.f_pid = 0;
1732: }
1733: }
1734: Initialized = was_initialized;
1735: if (signo) {
1736: dprintf("syslogd: exiting on signal %d\n", signo);
1737: (void)snprintf(buf, sizeof(buf), "exiting on signal %d", signo);
1738: errno = 0;
1739: logerror(buf);
1740: }
1741: STAILQ_FOREACH(fx, &funixes, next)
1742: (void)unlink(fx->name);
1743: pidfile_remove(pfh);
1744:
1745: exit(1);
1746: }
1747:
1748: /*
1749: * INIT -- Initialize syslogd from configuration table
1750: */
1751: static void
1752: init(int signo)
1753: {
1754: int i;
1755: FILE *cf;
1756: struct filed *f, *next, **nextp;
1757: char *p;
1758: char cline[LINE_MAX];
1759: char prog[NAME_MAX+1];
1760: char host[MAXHOSTNAMELEN];
1761: char oldLocalHostName[MAXHOSTNAMELEN];
1762: char hostMsg[2*MAXHOSTNAMELEN+40];
1763: char bootfileMsg[LINE_MAX];
1764:
1765: dprintf("init\n");
1766:
1767: /*
1768: * Load hostname (may have changed).
1769: */
1770: if (signo != 0)
1771: (void)strlcpy(oldLocalHostName, LocalHostName,
1772: sizeof(oldLocalHostName));
1773: if (gethostname(LocalHostName, sizeof(LocalHostName)))
1774: err(EX_OSERR, "gethostname() failed");
1775: if ((p = strchr(LocalHostName, '.')) != NULL) {
1776: *p++ = '\0';
1777: LocalDomain = p;
1778: } else {
1779: LocalDomain = "";
1780: }
1781:
1782: /*
1783: * Close all open log files.
1784: */
1785: Initialized = 0;
1786: for (f = Files; f != NULL; f = next) {
1787: /* flush any pending output */
1788: if (f->f_prevcount)
1789: fprintlog(f, 0, (char *)NULL);
1790:
1791: switch (f->f_type) {
1792: case F_FILE:
1793: case F_FORW:
1794: case F_CONSOLE:
1795: case F_TTY:
1796: (void)close(f->f_file);
1797: break;
1798: case F_PIPE:
1799: if (f->f_un.f_pipe.f_pid > 0) {
1800: (void)close(f->f_file);
1801: deadq_enter(f->f_un.f_pipe.f_pid,
1802: f->f_un.f_pipe.f_pname);
1803: }
1804: f->f_un.f_pipe.f_pid = 0;
1805: break;
1806: // CPP:
1807: case F_RING:
1808: munmap(f->f_un.f_ring.f_footer, sizeof(struct clogFooter));
1809: close(f->f_file);
1810: break;
1811: // CPP::
1812: }
1813: next = f->f_next;
1814: if (f->f_program) free(f->f_program);
1815: if (f->f_host) free(f->f_host);
1816: free((char *)f);
1817: }
1818: Files = NULL;
1819: nextp = &Files;
1820:
1821: /* open the configuration file */
1822: if ((cf = fopen(ConfFile, "r")) == NULL) {
1823: dprintf("cannot open %s\n", ConfFile);
1824: *nextp = (struct filed *)calloc(1, sizeof(*f));
1825: if (*nextp == NULL) {
1826: logerror("calloc");
1827: exit(1);
1828: }
1829: cfline("*.ERR\t/dev/console", *nextp, "*", "*");
1830: (*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1831: if ((*nextp)->f_next == NULL) {
1832: logerror("calloc");
1833: exit(1);
1834: }
1835: cfline("*.PANIC\t*", (*nextp)->f_next, "*", "*");
1836: Initialized = 1;
1837: return;
1838: }
1839:
1840: /*
1841: * Foreach line in the conf table, open that file.
1842: */
1843: f = NULL;
1844: (void)strlcpy(host, "*", sizeof(host));
1845: (void)strlcpy(prog, "*", sizeof(prog));
1846: while (fgets(cline, sizeof(cline), cf) != NULL) {
1847: /*
1848: * check for end-of-section, comments, strip off trailing
1849: * spaces and newline character. #!prog is treated specially:
1850: * following lines apply only to that program.
1851: */
1852: for (p = cline; isspace(*p); ++p)
1853: continue;
1854: if (*p == 0)
1855: continue;
1856: if (*p == '#') {
1857: p++;
1858: if (*p != '!' && *p != '+' && *p != '-')
1859: continue;
1860: }
1861: if (*p == '+' || *p == '-') {
1862: host[0] = *p++;
1863: while (isspace(*p))
1864: p++;
1865: if ((!*p) || (*p == '*')) {
1866: (void)strlcpy(host, "*", sizeof(host));
1867: continue;
1868: }
1869: if (*p == '@')
1870: p = LocalHostName;
1871: for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
1872: if (!isalnum(*p) && *p != '.' && *p != '-'
1873: && *p != ',' && *p != ':' && *p != '%')
1874: break;
1875: host[i] = *p++;
1876: }
1877: host[i] = '\0';
1878: continue;
1879: }
1880: if (*p == '!') {
1881: p++;
1882: while (isspace(*p)) p++;
1883: if ((!*p) || (*p == '*')) {
1884: (void)strlcpy(prog, "*", sizeof(prog));
1885: continue;
1886: }
1887: for (i = 0; i < NAME_MAX; i++) {
1888: if (!isprint(p[i]) || isspace(p[i]))
1889: break;
1890: prog[i] = p[i];
1891: }
1892: prog[i] = 0;
1893: continue;
1894: }
1895: for (p = cline + 1; *p != '\0'; p++) {
1896: if (*p != '#')
1897: continue;
1898: if (*(p - 1) == '\\') {
1899: strcpy(p - 1, p);
1900: p--;
1901: continue;
1902: }
1903: *p = '\0';
1904: break;
1905: }
1906: for (i = strlen(cline) - 1; i >= 0 && isspace(cline[i]); i--)
1907: cline[i] = '\0';
1908: f = (struct filed *)calloc(1, sizeof(*f));
1909: if (f == NULL) {
1910: logerror("calloc");
1911: exit(1);
1912: }
1913: *nextp = f;
1914: nextp = &f->f_next;
1915: cfline(cline, f, prog, host);
1916: }
1917:
1918: /* close the configuration file */
1919: (void)fclose(cf);
1920:
1921: Initialized = 1;
1922:
1923: if (Debug) {
1924: int port;
1925: for (f = Files; f; f = f->f_next) {
1926: for (i = 0; i <= LOG_NFACILITIES; i++)
1927: if (f->f_pmask[i] == INTERNAL_NOPRI)
1928: printf("X ");
1929: else
1930: printf("%d ", f->f_pmask[i]);
1931: printf("%s: ", TypeNames[f->f_type]);
1932: switch (f->f_type) {
1933: case F_FILE:
1934: printf("%s", f->f_un.f_fname);
1935: break;
1936:
1937: case F_CONSOLE:
1938: case F_TTY:
1939: printf("%s%s", _PATH_DEV, f->f_un.f_fname);
1940: break;
1941:
1942: case F_FORW:
1943: port = (int)ntohs(((struct sockaddr_in *)
1944: (f->f_un.f_forw.f_addr->ai_addr))->sin_port);
1945: if (port != 514) {
1946: printf("%s:%d",
1947: f->f_un.f_forw.f_hname, port);
1948: } else {
1949: printf("%s", f->f_un.f_forw.f_hname);
1950: }
1951: break;
1952:
1953: // CPP:
1954: case F_RING:
1955: printf("%s", f->f_un.f_ring.f_rname);
1956: break;
1957: // CPP::
1958:
1959: case F_PIPE:
1960: printf("%s", f->f_un.f_pipe.f_pname);
1961: break;
1962:
1963: case F_USERS:
1964: for (i = 0; i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1965: printf("%s, ", f->f_un.f_uname[i]);
1966: break;
1967: }
1968: if (f->f_program)
1969: printf(" (%s)", f->f_program);
1970: printf("\n");
1971: }
1972: }
1973:
1974: logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1975: dprintf("syslogd: restarted\n");
1976: /*
1977: * Log a change in hostname, but only on a restart.
1978: */
1979: if (signo != 0 && strcmp(oldLocalHostName, LocalHostName) != 0) {
1980: (void)snprintf(hostMsg, sizeof(hostMsg),
1981: "syslogd: hostname changed, \"%s\" to \"%s\"",
1982: oldLocalHostName, LocalHostName);
1983: logmsg(LOG_SYSLOG|LOG_INFO, hostMsg, LocalHostName, ADDDATE);
1984: dprintf("%s\n", hostMsg);
1985: }
1986: /*
1987: * Log the kernel boot file if we aren't going to use it as
1988: * the prefix, and if this is *not* a restart.
1989: */
1990: if (signo == 0 && !use_bootfile) {
1991: (void)snprintf(bootfileMsg, sizeof(bootfileMsg),
1992: "syslogd: kernel boot file is %s", bootfile);
1993: logmsg(LOG_KERN|LOG_INFO, bootfileMsg, LocalHostName, ADDDATE);
1994: dprintf("%s\n", bootfileMsg);
1995: }
1996: }
1997:
1998: /*
1999: * Crack a configuration file line
2000: */
2001: static void
2002: cfline(const char *line, struct filed *f, const char *prog, const char *host)
2003: {
2004: struct addrinfo hints, *res;
2005: int error, i, pri, syncfile;
2006: const char *p, *q;
2007: char *bp;
2008: char buf[MAXLINE], ebuf[100];
2009: struct stat sb;
2010:
2011: dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
2012:
2013: errno = 0; /* keep strerror() stuff out of logerror messages */
2014:
2015: /* clear out file entry */
2016: memset(f, 0, sizeof(*f));
2017: for (i = 0; i <= LOG_NFACILITIES; i++)
2018: f->f_pmask[i] = INTERNAL_NOPRI;
2019:
2020: /* save hostname if any */
2021: if (host && *host == '*')
2022: host = NULL;
2023: if (host) {
2024: int hl;
2025:
2026: f->f_host = strdup(host);
2027: if (f->f_host == NULL) {
2028: logerror("strdup");
2029: exit(1);
2030: }
2031: hl = strlen(f->f_host);
2032: if (hl > 0 && f->f_host[hl-1] == '.')
2033: f->f_host[--hl] = '\0';
2034: trimdomain(f->f_host, hl);
2035: }
2036:
2037: /* save program name if any */
2038: if (prog && *prog == '*')
2039: prog = NULL;
2040: if (prog) {
2041: f->f_program = strdup(prog);
2042: if (f->f_program == NULL) {
2043: logerror("strdup");
2044: exit(1);
2045: }
2046: }
2047:
2048: /* scan through the list of selectors */
2049: for (p = line; *p && *p != '\t' && *p != ' ';) {
2050: int pri_done;
2051: int pri_cmp;
2052: int pri_invert;
2053:
2054: /* find the end of this facility name list */
2055: for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; )
2056: continue;
2057:
2058: /* get the priority comparison */
2059: pri_cmp = 0;
2060: pri_done = 0;
2061: pri_invert = 0;
2062: if (*q == '!') {
2063: pri_invert = 1;
2064: q++;
2065: }
2066: while (!pri_done) {
2067: switch (*q) {
2068: case '<':
2069: pri_cmp |= PRI_LT;
2070: q++;
2071: break;
2072: case '=':
2073: pri_cmp |= PRI_EQ;
2074: q++;
2075: break;
2076: case '>':
2077: pri_cmp |= PRI_GT;
2078: q++;
2079: break;
2080: default:
2081: pri_done++;
2082: break;
2083: }
2084: }
2085:
2086: /* collect priority name */
2087: for (bp = buf; *q && !strchr("\t,; ", *q); )
2088: *bp++ = *q++;
2089: *bp = '\0';
2090:
2091: /* skip cruft */
2092: while (strchr(",;", *q))
2093: q++;
2094:
2095: /* decode priority name */
2096: if (*buf == '*') {
2097: pri = LOG_PRIMASK;
2098: pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
2099: } else {
2100: /* Ignore trailing spaces. */
2101: for (i = strlen(buf) - 1; i >= 0 && buf[i] == ' '; i--)
2102: buf[i] = '\0';
2103:
2104: pri = decode(buf, prioritynames);
2105: if (pri < 0) {
2106: (void)snprintf(ebuf, sizeof ebuf,
2107: "unknown priority name \"%s\"", buf);
2108: logerror(ebuf);
2109: return;
2110: }
2111: }
2112: if (!pri_cmp)
2113: pri_cmp = (UniquePriority)
2114: ? (PRI_EQ)
2115: : (PRI_EQ | PRI_GT)
2116: ;
2117: if (pri_invert)
2118: pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
2119:
2120: /* scan facilities */
2121: while (*p && !strchr("\t.; ", *p)) {
2122: for (bp = buf; *p && !strchr("\t,;. ", *p); )
2123: *bp++ = *p++;
2124: *bp = '\0';
2125:
2126: if (*buf == '*') {
2127: for (i = 0; i < LOG_NFACILITIES; i++) {
2128: f->f_pmask[i] = pri;
2129: f->f_pcmp[i] = pri_cmp;
2130: }
2131: } else {
2132: i = decode(buf, facilitynames);
2133: if (i < 0) {
2134: (void)snprintf(ebuf, sizeof ebuf,
2135: "unknown facility name \"%s\"",
2136: buf);
2137: logerror(ebuf);
2138: return;
2139: }
2140: f->f_pmask[i >> 3] = pri;
2141: f->f_pcmp[i >> 3] = pri_cmp;
2142: }
2143: while (*p == ',' || *p == ' ')
2144: p++;
2145: }
2146:
2147: p = q;
2148: }
2149:
2150: /* skip to action part */
2151: while (*p == '\t' || *p == ' ')
2152: p++;
2153:
2154: if (*p == '-') {
2155: syncfile = 0;
2156: p++;
2157: } else
2158: syncfile = 1;
2159:
2160: switch (*p) {
2161: case '@':
2162: {
2163: char *tp;
2164: /*
2165: * scan forward to see if there is a port defined.
2166: * so we can't use strlcpy..
2167: */
2168: i = sizeof(f->f_un.f_forw.f_hname);
2169: tp = f->f_un.f_forw.f_hname;
2170: p++;
2171:
2172: while (*p && (*p != ':') && (i-- > 0)) {
2173: *tp++ = *p++;
2174: }
2175: *tp = '\0';
2176: }
2177: /* See if we copied a domain and have a port */
2178: if (*p == ':')
2179: p++;
2180: else
2181: p = NULL;
2182:
2183: memset(&hints, 0, sizeof(hints));
2184: hints.ai_family = family;
2185: hints.ai_socktype = SOCK_DGRAM;
2186: error = getaddrinfo(f->f_un.f_forw.f_hname,
2187: p ? p : "syslog", &hints, &res);
2188: if (error) {
2189: logerror(gai_strerror(error));
2190: break;
2191: }
2192: f->f_un.f_forw.f_addr = res;
2193: f->f_type = F_FORW;
2194: break;
2195:
2196: case '/':
2197: if ((f->f_file = open(p, logflags, 0600)) < 0) {
2198: f->f_type = F_UNUSED;
2199: logerror(p);
2200: break;
2201: }
2202: if (syncfile)
2203: f->f_flags |= FFLAG_SYNC;
2204: if (isatty(f->f_file)) {
2205: if (strcmp(p, ctty) == 0)
2206: f->f_type = F_CONSOLE;
2207: else
2208: f->f_type = F_TTY;
2209: (void)strlcpy(f->f_un.f_fname, p + sizeof(_PATH_DEV) - 1,
2210: sizeof(f->f_un.f_fname));
2211: } else {
2212: (void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
2213: f->f_type = F_FILE;
2214: }
2215: break;
2216:
2217: // CPP:
2218: case '%':
2219: if ((f->f_file = open(p + 1, O_RDWR, 0)) < 0) {
2220: f->f_type = F_UNUSED;
2221: logerror(p + 1);
2222: break;
2223: }
2224: if (fstat(f->f_file, &sb) < 0) {
2225: close(f->f_file);
2226: f->f_type = F_UNUSED;
2227: logerror(p + 1);
2228: break;
2229: }
2230: f->f_un.f_ring.f_footer = mmap(NULL, sizeof(struct clogFooter), PROT_READ | PROT_WRITE, MAP_SHARED,
2231: f->f_file, sb.st_size - sizeof(struct clogFooter));
2232: if (!f->f_un.f_ring.f_footer) {
2233: close(f->f_file);
2234: f->f_type = F_UNUSED;
2235: logerror(p + 1);
2236: break;
2237: }
2238: if (memcmp(&(f->f_un.f_ring.f_footer->cf_magic), MAGIC, 4)) {
2239: munmap(f->f_un.f_ring.f_footer, sizeof(struct clogFooter));
2240: close(f->f_file);
2241: f->f_type = F_UNUSED;
2242: errno = ENODEV;
2243: logerror(p + 1);
2244: break;
2245: }
2246: f->f_un.f_ring.f_size = sb.st_size;
2247: strcpy(f->f_un.f_ring.f_rname, p + 1);
2248: f->f_type = F_RING;
2249: break;
2250: // CPP::
2251:
2252: case '|':
2253: f->f_un.f_pipe.f_pid = 0;
2254: (void)strlcpy(f->f_un.f_pipe.f_pname, p + 1,
2255: sizeof(f->f_un.f_pipe.f_pname));
2256: f->f_type = F_PIPE;
2257: break;
2258:
2259: case '*':
2260: f->f_type = F_WALL;
2261: break;
2262:
2263: default:
2264: for (i = 0; i < MAXUNAMES && *p; i++) {
2265: for (q = p; *q && *q != ','; )
2266: q++;
2267: (void)strncpy(f->f_un.f_uname[i], p, MAXLOGNAME - 1);
2268: if ((q - p) >= MAXLOGNAME)
2269: f->f_un.f_uname[i][MAXLOGNAME - 1] = '\0';
2270: else
2271: f->f_un.f_uname[i][q - p] = '\0';
2272: while (*q == ',' || *q == ' ')
2273: q++;
2274: p = q;
2275: }
2276: f->f_type = F_USERS;
2277: break;
2278: }
2279: }
2280:
2281:
2282: /*
2283: * Decode a symbolic name to a numeric value
2284: */
2285: static int
2286: decode(const char *name, CODE *codetab)
2287: {
2288: CODE *c;
2289: char *p, buf[40];
2290:
2291: if (isdigit(*name))
2292: return (atoi(name));
2293:
2294: for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
2295: if (isupper(*name))
2296: *p = tolower(*name);
2297: else
2298: *p = *name;
2299: }
2300: *p = '\0';
2301: for (c = codetab; c->c_name; c++)
2302: if (!strcmp(buf, c->c_name))
2303: return (c->c_val);
2304:
2305: return (-1);
2306: }
2307:
2308: static void
2309: markit(void)
2310: {
2311: struct filed *f;
2312: dq_t q, next;
2313:
2314: now = time((time_t *)NULL);
2315: MarkSeq += TIMERINTVL;
2316: if (MarkSeq >= MarkInterval) {
2317: logmsg(LOG_INFO, "-- MARK --",
2318: LocalHostName, ADDDATE|MARK);
2319: MarkSeq = 0;
2320: }
2321:
2322: for (f = Files; f; f = f->f_next) {
2323: if (f->f_prevcount && now >= REPEATTIME(f)) {
2324: dprintf("flush %s: repeated %d times, %d sec.\n",
2325: TypeNames[f->f_type], f->f_prevcount,
2326: repeatinterval[f->f_repeatcount]);
2327: fprintlog(f, 0, (char *)NULL);
2328: BACKOFF(f);
2329: }
2330: }
2331:
2332: /* Walk the dead queue, and see if we should signal somebody. */
2333: for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = next) {
2334: next = TAILQ_NEXT(q, dq_entries);
2335:
2336: switch (q->dq_timeout) {
2337: case 0:
2338: /* Already signalled once, try harder now. */
2339: if (kill(q->dq_pid, SIGKILL) != 0)
2340: (void)deadq_remove(q->dq_pid);
2341: break;
2342:
2343: case 1:
2344: /*
2345: * Timed out on dead queue, send terminate
2346: * signal. Note that we leave the removal
2347: * from the dead queue to reapchild(), which
2348: * will also log the event (unless the process
2349: * didn't even really exist, in case we simply
2350: * drop it from the dead queue).
2351: */
2352: if (kill(q->dq_pid, SIGTERM) != 0)
2353: (void)deadq_remove(q->dq_pid);
2354: /* FALLTHROUGH */
2355:
2356: default:
2357: q->dq_timeout--;
2358: }
2359: }
2360: MarkSet = 0;
2361: (void)alarm(TIMERINTVL);
2362: }
2363:
2364: /*
2365: * fork off and become a daemon, but wait for the child to come online
2366: * before returing to the parent, or we get disk thrashing at boot etc.
2367: * Set a timer so we don't hang forever if it wedges.
2368: */
2369: static int
2370: waitdaemon(int nochdir, int noclose, int maxwait)
2371: {
2372: int fd;
2373: int status;
2374: pid_t pid, childpid;
2375:
2376: switch (childpid = fork()) {
2377: case -1:
2378: return (-1);
2379: case 0:
2380: break;
2381: default:
2382: signal(SIGALRM, timedout);
2383: alarm(maxwait);
2384: while ((pid = wait3(&status, 0, NULL)) != -1) {
2385: if (WIFEXITED(status))
2386: errx(1, "child pid %d exited with return code %d",
2387: pid, WEXITSTATUS(status));
2388: if (WIFSIGNALED(status))
2389: errx(1, "child pid %d exited on signal %d%s",
2390: pid, WTERMSIG(status),
2391: WCOREDUMP(status) ? " (core dumped)" :
2392: "");
2393: if (pid == childpid) /* it's gone... */
2394: break;
2395: }
2396: exit(0);
2397: }
2398:
2399: if (setsid() == -1)
2400: return (-1);
2401:
2402: if (!nochdir)
2403: (void)chdir("/");
2404:
2405: if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2406: (void)dup2(fd, STDIN_FILENO);
2407: (void)dup2(fd, STDOUT_FILENO);
2408: (void)dup2(fd, STDERR_FILENO);
2409: if (fd > 2)
2410: (void)close (fd);
2411: }
2412: return (getppid());
2413: }
2414:
2415: /*
2416: * We get a SIGALRM from the child when it's running and finished doing it's
2417: * fsync()'s or O_SYNC writes for all the boot messages.
2418: *
2419: * We also get a signal from the kernel if the timer expires, so check to
2420: * see what happened.
2421: */
2422: static void
2423: timedout(int sig __unused)
2424: {
2425: int left;
2426: left = alarm(0);
2427: signal(SIGALRM, SIG_DFL);
2428: if (left == 0)
2429: errx(1, "timed out waiting for child");
2430: else
2431: _exit(0);
2432: }
2433:
2434: /*
2435: * Add `s' to the list of allowable peer addresses to accept messages
2436: * from.
2437: *
2438: * `s' is a string in the form:
2439: *
2440: * [*]domainname[:{servicename|portnumber|*}]
2441: *
2442: * or
2443: *
2444: * netaddr/maskbits[:{servicename|portnumber|*}]
2445: *
2446: * Returns -1 on error, 0 if the argument was valid.
2447: */
2448: static int
2449: allowaddr(char *s)
2450: {
2451: char *cp1, *cp2;
2452: struct allowedpeer ap;
2453: struct servent *se;
2454: int masklen = -1;
2455: struct addrinfo hints, *res;
2456: struct in_addr *addrp, *maskp;
2457: #ifdef INET6
2458: int i;
2459: u_int32_t *addr6p, *mask6p;
2460: #endif
2461: char ip[NI_MAXHOST];
2462:
2463: #ifdef INET6
2464: if (*s != '[' || (cp1 = strchr(s + 1, ']')) == NULL)
2465: #endif
2466: cp1 = s;
2467: if ((cp1 = strrchr(cp1, ':'))) {
2468: /* service/port provided */
2469: *cp1++ = '\0';
2470: if (strlen(cp1) == 1 && *cp1 == '*')
2471: /* any port allowed */
2472: ap.port = 0;
2473: else if ((se = getservbyname(cp1, "udp"))) {
2474: ap.port = ntohs(se->s_port);
2475: } else {
2476: ap.port = strtol(cp1, &cp2, 0);
2477: if (*cp2 != '\0')
2478: return (-1); /* port not numeric */
2479: }
2480: } else {
2481: if ((se = getservbyname("syslog", "udp")))
2482: ap.port = ntohs(se->s_port);
2483: else
2484: /* sanity, should not happen */
2485: ap.port = 514;
2486: }
2487:
2488: if ((cp1 = strchr(s, '/')) != NULL &&
2489: strspn(cp1 + 1, "0123456789") == strlen(cp1 + 1)) {
2490: *cp1 = '\0';
2491: if ((masklen = atoi(cp1 + 1)) < 0)
2492: return (-1);
2493: }
2494: #ifdef INET6
2495: if (*s == '[') {
2496: cp2 = s + strlen(s) - 1;
2497: if (*cp2 == ']') {
2498: ++s;
2499: *cp2 = '\0';
2500: } else {
2501: cp2 = NULL;
2502: }
2503: } else {
2504: cp2 = NULL;
2505: }
2506: #endif
2507: memset(&hints, 0, sizeof(hints));
2508: hints.ai_family = PF_UNSPEC;
2509: hints.ai_socktype = SOCK_DGRAM;
2510: hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2511: if (getaddrinfo(s, NULL, &hints, &res) == 0) {
2512: ap.isnumeric = 1;
2513: memcpy(&ap.a_addr, res->ai_addr, res->ai_addrlen);
2514: memset(&ap.a_mask, 0, sizeof(ap.a_mask));
2515: ap.a_mask.ss_family = res->ai_family;
2516: if (res->ai_family == AF_INET) {
2517: ap.a_mask.ss_len = sizeof(struct sockaddr_in);
2518: maskp = &((struct sockaddr_in *)&ap.a_mask)->sin_addr;
2519: addrp = &((struct sockaddr_in *)&ap.a_addr)->sin_addr;
2520: if (masklen < 0) {
2521: /* use default netmask */
2522: if (IN_CLASSA(ntohl(addrp->s_addr)))
2523: maskp->s_addr = htonl(IN_CLASSA_NET);
2524: else if (IN_CLASSB(ntohl(addrp->s_addr)))
2525: maskp->s_addr = htonl(IN_CLASSB_NET);
2526: else
2527: maskp->s_addr = htonl(IN_CLASSC_NET);
2528: } else if (masklen <= 32) {
2529: /* convert masklen to netmask */
2530: if (masklen == 0)
2531: maskp->s_addr = 0;
2532: else
2533: maskp->s_addr = htonl(~((1 << (32 - masklen)) - 1));
2534: } else {
2535: freeaddrinfo(res);
2536: return (-1);
2537: }
2538: /* Lose any host bits in the network number. */
2539: addrp->s_addr &= maskp->s_addr;
2540: }
2541: #ifdef INET6
2542: else if (res->ai_family == AF_INET6 && masklen <= 128) {
2543: ap.a_mask.ss_len = sizeof(struct sockaddr_in6);
2544: if (masklen < 0)
2545: masklen = 128;
2546: mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2547: /* convert masklen to netmask */
2548: while (masklen > 0) {
2549: if (masklen < 32) {
2550: *mask6p = htonl(~(0xffffffff >> masklen));
2551: break;
2552: }
2553: *mask6p++ = 0xffffffff;
2554: masklen -= 32;
2555: }
2556: /* Lose any host bits in the network number. */
2557: mask6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_mask)->sin6_addr;
2558: addr6p = (u_int32_t *)&((struct sockaddr_in6 *)&ap.a_addr)->sin6_addr;
2559: for (i = 0; i < 4; i++)
2560: addr6p[i] &= mask6p[i];
2561: }
2562: #endif
2563: else {
2564: freeaddrinfo(res);
2565: return (-1);
2566: }
2567: freeaddrinfo(res);
2568: } else {
2569: /* arg `s' is domain name */
2570: ap.isnumeric = 0;
2571: ap.a_name = s;
2572: if (cp1)
2573: *cp1 = '/';
2574: #ifdef INET6
2575: if (cp2) {
2576: *cp2 = ']';
2577: --s;
2578: }
2579: #endif
2580: }
2581:
2582: if (Debug) {
2583: printf("allowaddr: rule %d: ", NumAllowed);
2584: if (ap.isnumeric) {
2585: printf("numeric, ");
2586: getnameinfo((struct sockaddr *)&ap.a_addr,
2587: ((struct sockaddr *)&ap.a_addr)->sa_len,
2588: ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2589: printf("addr = %s, ", ip);
2590: getnameinfo((struct sockaddr *)&ap.a_mask,
2591: ((struct sockaddr *)&ap.a_mask)->sa_len,
2592: ip, sizeof ip, NULL, 0, NI_NUMERICHOST);
2593: printf("mask = %s; ", ip);
2594: } else {
2595: printf("domainname = %s; ", ap.a_name);
2596: }
2597: printf("port = %d\n", ap.port);
2598: }
2599:
2600: if ((AllowedPeers = realloc(AllowedPeers,
2601: ++NumAllowed * sizeof(struct allowedpeer)))
2602: == NULL) {
2603: logerror("realloc");
2604: exit(1);
2605: }
2606: memcpy(&AllowedPeers[NumAllowed - 1], &ap, sizeof(struct allowedpeer));
2607: return (0);
2608: }
2609:
2610: /*
2611: * Validate that the remote peer has permission to log to us.
2612: */
2613: static int
2614: validate(struct sockaddr *sa, const char *hname)
2615: {
2616: int i;
2617: size_t l1, l2;
2618: char *cp, name[NI_MAXHOST], ip[NI_MAXHOST], port[NI_MAXSERV];
2619: struct allowedpeer *ap;
2620: struct sockaddr_in *sin4, *a4p = NULL, *m4p = NULL;
2621: #ifdef INET6
2622: int j, reject;
2623: struct sockaddr_in6 *sin6, *a6p = NULL, *m6p = NULL;
2624: #endif
2625: struct addrinfo hints, *res;
2626: u_short sport;
2627:
2628: if (NumAllowed == 0)
2629: /* traditional behaviour, allow everything */
2630: return (1);
2631:
2632: (void)strlcpy(name, hname, sizeof(name));
2633: memset(&hints, 0, sizeof(hints));
2634: hints.ai_family = PF_UNSPEC;
2635: hints.ai_socktype = SOCK_DGRAM;
2636: hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST;
2637: if (getaddrinfo(name, NULL, &hints, &res) == 0)
2638: freeaddrinfo(res);
2639: else if (strchr(name, '.') == NULL) {
2640: strlcat(name, ".", sizeof name);
2641: strlcat(name, LocalDomain, sizeof name);
2642: }
2643: if (getnameinfo(sa, sa->sa_len, ip, sizeof ip, port, sizeof port,
2644: NI_NUMERICHOST | NI_NUMERICSERV) != 0)
2645: return (0); /* for safety, should not occur */
2646: dprintf("validate: dgram from IP %s, port %s, name %s;\n",
2647: ip, port, name);
2648: sport = atoi(port);
2649:
2650: /* now, walk down the list */
2651: for (i = 0, ap = AllowedPeers; i < NumAllowed; i++, ap++) {
2652: if (ap->port != 0 && ap->port != sport) {
2653: dprintf("rejected in rule %d due to port mismatch.\n", i);
2654: continue;
2655: }
2656:
2657: if (ap->isnumeric) {
2658: if (ap->a_addr.ss_family != sa->sa_family) {
2659: dprintf("rejected in rule %d due to address family mismatch.\n", i);
2660: continue;
2661: }
2662: if (ap->a_addr.ss_family == AF_INET) {
2663: sin4 = (struct sockaddr_in *)sa;
2664: a4p = (struct sockaddr_in *)&ap->a_addr;
2665: m4p = (struct sockaddr_in *)&ap->a_mask;
2666: if ((sin4->sin_addr.s_addr & m4p->sin_addr.s_addr)
2667: != a4p->sin_addr.s_addr) {
2668: dprintf("rejected in rule %d due to IP mismatch.\n", i);
2669: continue;
2670: }
2671: }
2672: #ifdef INET6
2673: else if (ap->a_addr.ss_family == AF_INET6) {
2674: sin6 = (struct sockaddr_in6 *)sa;
2675: a6p = (struct sockaddr_in6 *)&ap->a_addr;
2676: m6p = (struct sockaddr_in6 *)&ap->a_mask;
2677: if (a6p->sin6_scope_id != 0 &&
2678: sin6->sin6_scope_id != a6p->sin6_scope_id) {
2679: dprintf("rejected in rule %d due to scope mismatch.\n", i);
2680: continue;
2681: }
2682: reject = 0;
2683: for (j = 0; j < 16; j += 4) {
2684: if ((*(u_int32_t *)&sin6->sin6_addr.s6_addr[j] & *(u_int32_t *)&m6p->sin6_addr.s6_addr[j])
2685: != *(u_int32_t *)&a6p->sin6_addr.s6_addr[j]) {
2686: ++reject;
2687: break;
2688: }
2689: }
2690: if (reject) {
2691: dprintf("rejected in rule %d due to IP mismatch.\n", i);
2692: continue;
2693: }
2694: }
2695: #endif
2696: else
2697: continue;
2698: } else {
2699: cp = ap->a_name;
2700: l1 = strlen(name);
2701: if (*cp == '*') {
2702: /* allow wildmatch */
2703: cp++;
2704: l2 = strlen(cp);
2705: if (l2 > l1 || memcmp(cp, &name[l1 - l2], l2) != 0) {
2706: dprintf("rejected in rule %d due to name mismatch.\n", i);
2707: continue;
2708: }
2709: } else {
2710: /* exact match */
2711: l2 = strlen(cp);
2712: if (l2 != l1 || memcmp(cp, name, l1) != 0) {
2713: dprintf("rejected in rule %d due to name mismatch.\n", i);
2714: continue;
2715: }
2716: }
2717: }
2718: dprintf("accepted in rule %d.\n", i);
2719: return (1); /* hooray! */
2720: }
2721: return (0);
2722: }
2723:
2724: /*
2725: * Fairly similar to popen(3), but returns an open descriptor, as
2726: * opposed to a FILE *.
2727: */
2728: static int
2729: p_open(const char *prog, pid_t *rpid)
2730: {
2731: int pfd[2], nulldesc, i;
2732: pid_t pid;
2733: sigset_t omask, mask;
2734: char *argv[4]; /* sh -c cmd NULL */
2735: char errmsg[200];
2736:
2737: if (pipe(pfd) == -1)
2738: return (-1);
2739: if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1)
2740: /* we are royally screwed anyway */
2741: return (-1);
2742:
2743: sigemptyset(&mask);
2744: sigaddset(&mask, SIGALRM);
2745: sigaddset(&mask, SIGHUP);
2746: sigprocmask(SIG_BLOCK, &mask, &omask);
2747: switch ((pid = fork())) {
2748: case -1:
2749: sigprocmask(SIG_SETMASK, &omask, 0);
2750: close(nulldesc);
2751: return (-1);
2752:
2753: case 0:
2754: argv[0] = strdup("sh");
2755: argv[1] = strdup("-c");
2756: argv[2] = strdup(prog);
2757: argv[3] = NULL;
2758: if (argv[0] == NULL || argv[1] == NULL || argv[2] == NULL) {
2759: logerror("strdup");
2760: exit(1);
2761: }
2762:
2763: alarm(0);
2764: (void)setsid(); /* Avoid catching SIGHUPs. */
2765:
2766: /*
2767: * Throw away pending signals, and reset signal
2768: * behaviour to standard values.
2769: */
2770: signal(SIGALRM, SIG_IGN);
2771: signal(SIGHUP, SIG_IGN);
2772: sigprocmask(SIG_SETMASK, &omask, 0);
2773: signal(SIGPIPE, SIG_DFL);
2774: signal(SIGQUIT, SIG_DFL);
2775: signal(SIGALRM, SIG_DFL);
2776: signal(SIGHUP, SIG_DFL);
2777:
2778: dup2(pfd[0], STDIN_FILENO);
2779: dup2(nulldesc, STDOUT_FILENO);
2780: dup2(nulldesc, STDERR_FILENO);
2781: for (i = getdtablesize(); i > 2; i--)
2782: (void)close(i);
2783:
2784: (void)execvp(_PATH_BSHELL, argv);
2785: _exit(255);
2786: }
2787:
2788: sigprocmask(SIG_SETMASK, &omask, 0);
2789: close(nulldesc);
2790: close(pfd[0]);
2791: /*
2792: * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
2793: * supposed to get an EWOULDBLOCK on writev(2), which is
2794: * caught by the logic above anyway, which will in turn close
2795: * the pipe, and fork a new logging subprocess if necessary.
2796: * The stale subprocess will be killed some time later unless
2797: * it terminated itself due to closing its input pipe (so we
2798: * get rid of really dead puppies).
2799: */
2800: if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
2801: /* This is bad. */
2802: (void)snprintf(errmsg, sizeof errmsg,
2803: "Warning: cannot change pipe to PID %d to "
2804: "non-blocking behaviour.",
2805: (int)pid);
2806: logerror(errmsg);
2807: }
2808: *rpid = pid;
2809: return (pfd[1]);
2810: }
2811:
2812: static void
2813: deadq_enter(pid_t pid, const char *name)
2814: {
2815: dq_t p;
2816: int status;
2817:
2818: /*
2819: * Be paranoid, if we can't signal the process, don't enter it
2820: * into the dead queue (perhaps it's already dead). If possible,
2821: * we try to fetch and log the child's status.
2822: */
2823: if (kill(pid, 0) != 0) {
2824: if (waitpid(pid, &status, WNOHANG) > 0)
2825: log_deadchild(pid, status, name);
2826: return;
2827: }
2828:
2829: p = malloc(sizeof(struct deadq_entry));
2830: if (p == NULL) {
2831: logerror("malloc");
2832: exit(1);
2833: }
2834:
2835: p->dq_pid = pid;
2836: p->dq_timeout = DQ_TIMO_INIT;
2837: TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
2838: }
2839:
2840: static int
2841: deadq_remove(pid_t pid)
2842: {
2843: dq_t q;
2844:
2845: TAILQ_FOREACH(q, &deadq_head, dq_entries) {
2846: if (q->dq_pid == pid) {
2847: TAILQ_REMOVE(&deadq_head, q, dq_entries);
2848: free(q);
2849: return (1);
2850: }
2851: }
2852:
2853: return (0);
2854: }
2855:
2856: static void
2857: log_deadchild(pid_t pid, int status, const char *name)
2858: {
2859: int code;
2860: char buf[256];
2861: const char *reason;
2862:
2863: errno = 0; /* Keep strerror() stuff out of logerror messages. */
2864: if (WIFSIGNALED(status)) {
2865: reason = "due to signal";
2866: code = WTERMSIG(status);
2867: } else {
2868: reason = "with status";
2869: code = WEXITSTATUS(status);
2870: if (code == 0)
2871: return;
2872: }
2873: (void)snprintf(buf, sizeof buf,
2874: "Logging subprocess %d (%s) exited %s %d.",
2875: pid, name, reason, code);
2876: logerror(buf);
2877: }
2878:
2879: static int *
2880: socksetup(int af, char *bindhostname)
2881: {
2882: struct addrinfo hints, *res, *r;
2883: const char *bindservice;
2884: char *cp;
2885: int error, maxs, *s, *socks;
2886:
2887: /*
2888: * We have to handle this case for backwards compatibility:
2889: * If there are two (or more) colons but no '[' and ']',
2890: * assume this is an inet6 address without a service.
2891: */
2892: bindservice = "syslog";
2893: if (bindhostname != NULL) {
2894: #ifdef INET6
2895: if (*bindhostname == '[' &&
2896: (cp = strchr(bindhostname + 1, ']')) != NULL) {
2897: ++bindhostname;
2898: *cp = '\0';
2899: if (cp[1] == ':' && cp[2] != '\0')
2900: bindservice = cp + 2;
2901: } else {
2902: #endif
2903: cp = strchr(bindhostname, ':');
2904: if (cp != NULL && strchr(cp + 1, ':') == NULL) {
2905: *cp = '\0';
2906: if (cp[1] != '\0')
2907: bindservice = cp + 1;
2908: if (cp == bindhostname)
2909: bindhostname = NULL;
2910: }
2911: #ifdef INET6
2912: }
2913: #endif
2914: }
2915:
2916: memset(&hints, 0, sizeof(hints));
2917: hints.ai_flags = AI_PASSIVE;
2918: hints.ai_family = af;
2919: hints.ai_socktype = SOCK_DGRAM;
2920: error = getaddrinfo(bindhostname, bindservice, &hints, &res);
2921: if (error) {
2922: logerror(gai_strerror(error));
2923: errno = 0;
2924: die(0);
2925: }
2926:
2927: /* Count max number of sockets we may open */
2928: for (maxs = 0, r = res; r; r = r->ai_next, maxs++);
2929: socks = malloc((maxs+1) * sizeof(int));
2930: if (socks == NULL) {
2931: logerror("couldn't allocate memory for sockets");
2932: die(0);
2933: }
2934:
2935: *socks = 0; /* num of sockets counter at start of array */
2936: s = socks + 1;
2937: for (r = res; r; r = r->ai_next) {
2938: int on = 1;
2939: *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
2940: if (*s < 0) {
2941: logerror("socket");
2942: continue;
2943: }
2944: if (r->ai_family == AF_INET6) {
2945: if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY,
2946: (char *)&on, sizeof (on)) < 0) {
2947: logerror("setsockopt");
2948: close(*s);
2949: continue;
2950: }
2951: }
2952: if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR,
2953: (char *)&on, sizeof (on)) < 0) {
2954: logerror("setsockopt");
2955: close(*s);
2956: continue;
2957: }
2958: if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
2959: close(*s);
2960: logerror("bind");
2961: continue;
2962: }
2963:
2964: double_rbuf(*s);
2965:
2966: (*socks)++;
2967: s++;
2968: }
2969:
2970: if (*socks == 0) {
2971: free(socks);
2972: if (Debug)
2973: return (NULL);
2974: else
2975: die(0);
2976: }
2977: if (res)
2978: freeaddrinfo(res);
2979:
2980: return (socks);
2981: }
2982:
2983: static void
2984: double_rbuf(int fd)
2985: {
2986: socklen_t slen, len;
2987:
2988: if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, &slen) == 0) {
2989: len *= 2;
2990: setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &len, slen);
2991: }
2992: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>