syslogd.c revision 1.82 1 /* $NetBSD: syslogd.c,v 1.82 2006/09/16 17:05:32 christos 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.82 2006/09/16 17:05:32 christos 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 * Extension to log by program name as well as facility and priority
67 * by Peter da Silva.
68 * -U and -v by Harlan Stenn.
69 * Priority comparison code by Harlan Stenn.
70 */
71
72 #define MAXLINE 1024 /* maximum line length */
73 #define MAXSVLINE 120 /* maximum saved line length */
74 #define DEFUPRI (LOG_USER|LOG_NOTICE)
75 #define DEFSPRI (LOG_KERN|LOG_NOTICE)
76 #define TIMERINTVL 30 /* interval for checking flush, mark */
77 #define TTYMSGTIME 1 /* timeout passed to ttymsg */
78
79 #include <sys/param.h>
80 #include <sys/socket.h>
81 #include <sys/sysctl.h>
82 #include <sys/types.h>
83 #include <sys/un.h>
84 #include <sys/wait.h>
85 #include <sys/queue.h>
86 #include <sys/event.h>
87
88 #include <netinet/in.h>
89
90 #include <assert.h>
91 #include <ctype.h>
92 #include <errno.h>
93 #include <fcntl.h>
94 #include <grp.h>
95 #include <locale.h>
96 #include <netdb.h>
97 #include <pwd.h>
98 #include <signal.h>
99 #include <stdarg.h>
100 #include <stdio.h>
101 #include <stdlib.h>
102 #include <string.h>
103 #include <unistd.h>
104 #include <util.h>
105
106 #include "utmpentry.h"
107 #include "pathnames.h"
108
109 #define SYSLOG_NAMES
110 #include <sys/syslog.h>
111
112 #ifdef LIBWRAP
113 #include <tcpd.h>
114
115 int allow_severity = LOG_AUTH|LOG_INFO;
116 int deny_severity = LOG_AUTH|LOG_WARNING;
117 #endif
118
119 char *ConfFile = _PATH_LOGCONF;
120 char ctty[] = _PATH_CONSOLE;
121
122 #define FDMASK(fd) (1 << (fd))
123
124 #define dprintf if (Debug) printf
125
126 #define MAXUNAMES 20 /* maximum number of user names */
127
128 /*
129 * Flags to logmsg().
130 */
131
132 #define IGN_CONS 0x001 /* don't print on console */
133 #define SYNC_FILE 0x002 /* do fsync on file after printing */
134 #define ADDDATE 0x004 /* add a date to the message */
135 #define MARK 0x008 /* this message is a mark */
136 #define ISKERNEL 0x010 /* kernel generated message */
137
138 /*
139 * This structure represents the files that will have log
140 * copies printed.
141 * We require f_file to be valid if f_type is F_FILE, F_CONSOLE, F_TTY,
142 * or if f_type is F_PIPE and f_pid > 0.
143 */
144
145 struct filed {
146 struct filed *f_next; /* next in linked list */
147 short f_type; /* entry type, see below */
148 short f_file; /* file descriptor */
149 time_t f_time; /* time this was last written */
150 char *f_host; /* host from which to record */
151 u_char f_pmask[LOG_NFACILITIES+1]; /* priority mask */
152 u_char f_pcmp[LOG_NFACILITIES+1]; /* compare priority */
153 #define PRI_LT 0x1
154 #define PRI_EQ 0x2
155 #define PRI_GT 0x4
156 char *f_program; /* program this applies to */
157 union {
158 char f_uname[MAXUNAMES][UT_NAMESIZE+1];
159 struct {
160 char f_hname[MAXHOSTNAMELEN];
161 struct addrinfo *f_addr;
162 } f_forw; /* forwarding address */
163 char f_fname[MAXPATHLEN];
164 struct {
165 char f_pname[MAXPATHLEN];
166 pid_t f_pid;
167 } f_pipe;
168 } f_un;
169 char f_prevline[MAXSVLINE]; /* last message logged */
170 char f_lasttime[16]; /* time of last occurrence */
171 char f_prevhost[MAXHOSTNAMELEN]; /* host from which recd. */
172 int f_prevpri; /* pri of f_prevline */
173 int f_prevlen; /* length of f_prevline */
174 int f_prevcount; /* repetition cnt of prevline */
175 int f_repeatcount; /* number of "repeated" msgs */
176 int f_lasterror; /* last error on writev() */
177 int f_flags; /* file-specific flags */
178 #define FFLAG_SYNC 0x01
179 };
180
181 /*
182 * Queue of about-to-be-dead processes we should watch out for.
183 */
184 TAILQ_HEAD(, deadq_entry) deadq_head = TAILQ_HEAD_INITIALIZER(deadq_head);
185
186 typedef struct deadq_entry {
187 pid_t dq_pid;
188 int dq_timeout;
189 TAILQ_ENTRY(deadq_entry) dq_entries;
190 } *dq_t;
191
192 /*
193 * The timeout to apply to processes waiting on the dead queue. Unit
194 * of measure is "mark intervals", i.e. 20 minutes by default.
195 * Processes on the dead queue will be terminated after that time.
196 */
197 #define DQ_TIMO_INIT 2
198
199 /*
200 * Intervals at which we flush out "message repeated" messages,
201 * in seconds after previous message is logged. After each flush,
202 * we move to the next interval until we reach the largest.
203 */
204 int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */
205 #define MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
206 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount])
207 #define BACKOFF(f) { if (++(f)->f_repeatcount > MAXREPEAT) \
208 (f)->f_repeatcount = MAXREPEAT; \
209 }
210
211 /* values for f_type */
212 #define F_UNUSED 0 /* unused entry */
213 #define F_FILE 1 /* regular file */
214 #define F_TTY 2 /* terminal */
215 #define F_CONSOLE 3 /* console terminal */
216 #define F_FORW 4 /* remote machine */
217 #define F_USERS 5 /* list of users */
218 #define F_WALL 6 /* everyone logged on */
219 #define F_PIPE 7 /* pipe to program */
220
221 char *TypeNames[8] = {
222 "UNUSED", "FILE", "TTY", "CONSOLE",
223 "FORW", "USERS", "WALL", "PIPE"
224 };
225
226 struct filed *Files;
227 struct filed consfile;
228
229 int Debug; /* debug flag */
230 int daemonized = 0; /* we are not daemonized yet */
231 char LocalHostName[MAXHOSTNAMELEN]; /* our hostname */
232 char oldLocalHostName[MAXHOSTNAMELEN];/* previous hostname */
233 char *LocalDomain; /* our local domain name */
234 size_t LocalDomainLen; /* length of LocalDomain */
235 int *finet = NULL; /* Internet datagram sockets */
236 int Initialized; /* set when we have initialized ourselves */
237 int ShuttingDown; /* set when we die() */
238 int MarkInterval = 20 * 60; /* interval between marks in seconds */
239 int MarkSeq = 0; /* mark sequence number */
240 int SecureMode = 0; /* listen only on unix domain socks */
241 int UseNameService = 1; /* make domain name queries */
242 int NumForwards = 0; /* number of forwarding actions in conf file */
243 char **LogPaths; /* array of pathnames to read messages from */
244 int NoRepeat = 0; /* disable "repeated"; log always */
245 int RemoteAddDate = 0; /* always add date to messages from network */
246 int SyncKernel = 0; /* write kernel messages synchronously */
247 int UniquePriority = 0; /* only log specified priority */
248 int LogFacPri = 0; /* put facility and priority in log messages: */
249 /* 0=no, 1=numeric, 2=names */
250
251 void cfline(char *, struct filed *, char *, char *);
252 char *cvthname(struct sockaddr_storage *);
253 void deadq_enter(pid_t, const char *);
254 int deadq_remove(pid_t);
255 int decode(const char *, CODE *);
256 void die(struct kevent *); /* SIGTERM kevent dispatch routine */
257 void domark(struct kevent *);/* timer kevent dispatch routine */
258 void fprintlog(struct filed *, int, char *);
259 int getmsgbufsize(void);
260 int* socksetup(int, const char *);
261 void init(struct kevent *); /* SIGHUP kevent dispatch routine */
262 void logerror(const char *, ...);
263 void logmsg(int, char *, char *, int);
264 void log_deadchild(pid_t, int, const char *);
265 int matches_spec(const char *, const char *,
266 char *(*)(const char *, const char *));
267 void printline(char *, char *, int);
268 void printsys(char *);
269 int p_open(char *, pid_t *);
270 void trim_localdomain(char *);
271 void reapchild(struct kevent *); /* SIGCHLD kevent dispatch routine */
272 void usage(void);
273 void wallmsg(struct filed *, struct iovec *, size_t);
274 int main(int, char *[]);
275 void logpath_add(char ***, int *, int *, char *);
276 void logpath_fileadd(char ***, int *, int *, char *);
277
278 static int fkq;
279
280 static struct kevent *allocevchange(void);
281 static int wait_for_events(struct kevent *, size_t);
282
283 static void dispatch_read_klog(struct kevent *);
284 static void dispatch_read_finet(struct kevent *);
285 static void dispatch_read_funix(struct kevent *);
286
287 /*
288 * Global line buffer. Since we only process one event at a time,
289 * a global one will do.
290 */
291 static char *linebuf;
292 static size_t linebufsize;
293 static const char *bindhostname = NULL;
294
295 #define A_CNT(x) (sizeof((x)) / sizeof((x)[0]))
296
297 int
298 main(int argc, char *argv[])
299 {
300 int ch, *funix, j, fklog;
301 int funixsize = 0, funixmaxsize = 0;
302 struct kevent events[16];
303 struct sockaddr_un sunx;
304 char **pp;
305 struct kevent *ev;
306 uid_t uid = 0;
307 gid_t gid = 0;
308 char *user = NULL;
309 char *group = NULL;
310 char *root = "/";
311 char *endp;
312 struct group *gr;
313 struct passwd *pw;
314 unsigned long l;
315
316 (void)setlocale(LC_ALL, "");
317
318 while ((ch = getopt(argc, argv, "b:dnsSf:m:p:P:ru:g:t:TUv")) != -1)
319 switch(ch) {
320 case 'b':
321 bindhostname = optarg;
322 break;
323 case 'd': /* debug */
324 Debug++;
325 break;
326 case 'f': /* configuration file */
327 ConfFile = optarg;
328 break;
329 case 'g':
330 group = optarg;
331 if (*group == '\0')
332 usage();
333 break;
334 case 'm': /* mark interval */
335 MarkInterval = atoi(optarg) * 60;
336 break;
337 case 'n': /* turn off DNS queries */
338 UseNameService = 0;
339 break;
340 case 'p': /* path */
341 logpath_add(&LogPaths, &funixsize,
342 &funixmaxsize, optarg);
343 break;
344 case 'P': /* file of paths */
345 logpath_fileadd(&LogPaths, &funixsize,
346 &funixmaxsize, optarg);
347 break;
348 case 'r': /* disable "repeated" compression */
349 NoRepeat++;
350 break;
351 case 's': /* no network listen mode */
352 SecureMode++;
353 break;
354 case 'S':
355 SyncKernel = 1;
356 break;
357 case 't':
358 root = optarg;
359 if (*root == '\0')
360 usage();
361 break;
362 case 'T':
363 RemoteAddDate = 1;
364 break;
365 case 'u':
366 user = optarg;
367 if (*user == '\0')
368 usage();
369 break;
370 case 'U': /* only log specified priority */
371 UniquePriority = 1;
372 break;
373 case 'v': /* log facility and priority */
374 if (LogFacPri < 2)
375 LogFacPri++;
376 break;
377 default:
378 usage();
379 }
380 if ((argc -= optind) != 0)
381 usage();
382
383 setlinebuf(stdout);
384
385 if (user != NULL) {
386 if (isdigit((unsigned char)*user)) {
387 errno = 0;
388 endp = NULL;
389 l = strtoul(user, &endp, 0);
390 if (errno || *endp != '\0')
391 goto getuser;
392 uid = (uid_t)l;
393 if (uid != l) {
394 errno = 0;
395 logerror("UID out of range");
396 die(NULL);
397 }
398 } else {
399 getuser:
400 if ((pw = getpwnam(user)) != NULL) {
401 uid = pw->pw_uid;
402 } else {
403 errno = 0;
404 logerror("Cannot find user `%s'", user);
405 die(NULL);
406 }
407 }
408 }
409
410 if (group != NULL) {
411 if (isdigit((unsigned char)*group)) {
412 errno = 0;
413 endp = NULL;
414 l = strtoul(group, &endp, 0);
415 if (errno || *endp != '\0')
416 goto getgroup;
417 gid = (gid_t)l;
418 if (gid != l) {
419 errno = 0;
420 logerror("GID out of range");
421 die(NULL);
422 }
423 } else {
424 getgroup:
425 if ((gr = getgrnam(group)) != NULL) {
426 gid = gr->gr_gid;
427 } else {
428 errno = 0;
429 logerror("Cannot find group `%s'", group);
430 die(NULL);
431 }
432 }
433 }
434
435 if (access(root, F_OK | R_OK)) {
436 logerror("Cannot access `%s'", root);
437 die(NULL);
438 }
439
440 consfile.f_type = F_CONSOLE;
441 (void)strlcpy(consfile.f_un.f_fname, ctty,
442 sizeof(consfile.f_un.f_fname));
443 linebufsize = getmsgbufsize();
444 if (linebufsize < MAXLINE)
445 linebufsize = MAXLINE;
446 linebufsize++;
447 linebuf = malloc(linebufsize);
448 if (linebuf == NULL) {
449 logerror("Couldn't allocate line buffer");
450 die(NULL);
451 }
452
453 #ifndef SUN_LEN
454 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
455 #endif
456 if (funixsize == 0)
457 logpath_add(&LogPaths, &funixsize,
458 &funixmaxsize, _PATH_LOG);
459 funix = (int *)malloc(sizeof(int) * funixsize);
460 if (funix == NULL) {
461 logerror("Couldn't allocate funix descriptors");
462 die(NULL);
463 }
464 for (j = 0, pp = LogPaths; *pp; pp++, j++) {
465 dprintf("Making unix dgram socket `%s'\n", *pp);
466 unlink(*pp);
467 memset(&sunx, 0, sizeof(sunx));
468 sunx.sun_family = AF_LOCAL;
469 (void)strncpy(sunx.sun_path, *pp, sizeof(sunx.sun_path));
470 funix[j] = socket(AF_LOCAL, SOCK_DGRAM, 0);
471 if (funix[j] < 0 || bind(funix[j],
472 (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
473 chmod(*pp, 0666) < 0) {
474 logerror("Cannot create `%s'", *pp);
475 die(NULL);
476 }
477 dprintf("Listening on unix dgram socket `%s'\n", *pp);
478 }
479
480 if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) < 0) {
481 dprintf("Can't open `%s' (%d)\n", _PATH_KLOG, errno);
482 } else {
483 dprintf("Listening on kernel log `%s'\n", _PATH_KLOG);
484 }
485
486 /*
487 * All files are open, we can drop privileges and chroot
488 */
489 dprintf("Attempt to chroot to `%s'\n", root);
490 if (chroot(root)) {
491 logerror("Failed to chroot to `%s'", root);
492 die(NULL);
493 }
494 dprintf("Attempt to set GID/EGID to `%d'\n", gid);
495 if (setgid(gid) || setegid(gid)) {
496 logerror("Failed to set gid to `%d'", gid);
497 die(NULL);
498 }
499 dprintf("Attempt to set UID/EUID to `%d'\n", uid);
500 if (setuid(uid) || seteuid(uid)) {
501 logerror("Failed to set uid to `%d'", uid);
502 die(NULL);
503 }
504
505 /*
506 * We cannot detach from the terminal before we are sure we won't
507 * have a fatal error, because error message would not go to the
508 * terminal and would not be logged because syslogd dies.
509 * All die() calls are behind us, we can call daemon()
510 */
511 if (!Debug) {
512 (void)daemon(0, 0);
513 daemonized = 1;
514
515 /* tuck my process id away, if i'm not in debug mode */
516 pidfile(NULL);
517 }
518
519 /*
520 * Create the global kernel event descriptor.
521 *
522 * NOTE: We MUST do this after daemon(), bacause the kqueue()
523 * API dictates that kqueue descriptors are not inherited
524 * across forks (lame!).
525 */
526 if ((fkq = kqueue()) < 0) {
527 logerror("Cannot create event queue");
528 die(NULL); /* XXX This error is lost! */
529 }
530
531 /*
532 * We must read the configuration file for the first time
533 * after the kqueue descriptor is created, because we install
534 * events during this process.
535 */
536 init(NULL);
537
538 /*
539 * Always exit on SIGTERM. Also exit on SIGINT and SIGQUIT
540 * if we're debugging.
541 */
542 (void)signal(SIGTERM, SIG_IGN);
543 (void)signal(SIGINT, SIG_IGN);
544 (void)signal(SIGQUIT, SIG_IGN);
545 ev = allocevchange();
546 EV_SET(ev, SIGTERM, EVFILT_SIGNAL, EV_ADD | EV_ENABLE, 0, 0,
547 (intptr_t) die);
548 if (Debug) {
549 ev = allocevchange();
550 EV_SET(ev, SIGINT, EVFILT_SIGNAL, EV_ADD | EV_ENABLE, 0, 0,
551 (intptr_t) die);
552
553 ev = allocevchange();
554 EV_SET(ev, SIGQUIT, EVFILT_SIGNAL, EV_ADD | EV_ENABLE, 0, 0,
555 (intptr_t) die);
556 }
557
558 ev = allocevchange();
559 EV_SET(ev, SIGCHLD, EVFILT_SIGNAL, EV_ADD | EV_ENABLE, 0, 0,
560 (intptr_t) reapchild);
561
562 ev = allocevchange();
563 EV_SET(ev, 0, EVFILT_TIMER, EV_ADD | EV_ENABLE, 0,
564 TIMERINTVL * 1000 /* seconds -> ms */, (intptr_t) domark);
565
566 (void)signal(SIGPIPE, SIG_IGN); /* We'll catch EPIPE instead. */
567
568 /* Re-read configuration on SIGHUP. */
569 (void) signal(SIGHUP, SIG_IGN);
570 ev = allocevchange();
571 EV_SET(ev, SIGHUP, EVFILT_SIGNAL, EV_ADD | EV_ENABLE, 0, 0,
572 (intptr_t) init);
573
574 if (fklog >= 0) {
575 ev = allocevchange();
576 EV_SET(ev, fklog, EVFILT_READ, EV_ADD | EV_ENABLE,
577 0, 0, (intptr_t) dispatch_read_klog);
578 }
579 for (j = 0, pp = LogPaths; *pp; pp++, j++) {
580 ev = allocevchange();
581 EV_SET(ev, funix[j], EVFILT_READ, EV_ADD | EV_ENABLE,
582 0, 0, (intptr_t) dispatch_read_funix);
583 }
584
585 dprintf("Off & running....\n");
586
587 for (;;) {
588 void (*handler)(struct kevent *);
589 int i, rv;
590
591 rv = wait_for_events(events, A_CNT(events));
592 if (rv == 0)
593 continue;
594 if (rv < 0) {
595 if (errno != EINTR)
596 logerror("kevent() failed");
597 continue;
598 }
599 dprintf("Got an event (%d)\n", rv);
600 for (i = 0; i < rv; i++) {
601 handler = (void *) events[i].udata;
602 (*handler)(&events[i]);
603 }
604 }
605 }
606
607 void
608 usage(void)
609 {
610
611 (void)fprintf(stderr,
612 "usage: %s [-dnrSsTUv] [-b bind_address] [-f config_file] [-g group]\n"
613 "\t[-m mark_interval] [-P file_list] [-p log_socket\n"
614 "\t[-p log_socket2 ...]] [-t chroot_dir] [-u user]\n",
615 getprogname());
616 exit(1);
617 }
618
619 /*
620 * Dispatch routine for reading /dev/klog
621 */
622 static void
623 dispatch_read_klog(struct kevent *ev)
624 {
625 ssize_t rv;
626 int fd = ev->ident;
627
628 dprintf("Kernel log active\n");
629
630 rv = read(fd, linebuf, linebufsize - 1);
631 if (rv > 0) {
632 linebuf[rv] = '\0';
633 printsys(linebuf);
634 } else if (rv < 0 && errno != EINTR) {
635 /*
636 * /dev/klog has croaked. Disable the event
637 * so it won't bother us again.
638 */
639 struct kevent *cev = allocevchange();
640 logerror("klog failed");
641 EV_SET(cev, fd, EVFILT_READ, EV_DISABLE,
642 0, 0, (intptr_t) dispatch_read_klog);
643 }
644 }
645
646 /*
647 * Dispatch routine for reading Unix domain sockets.
648 */
649 static void
650 dispatch_read_funix(struct kevent *ev)
651 {
652 struct sockaddr_un myname, fromunix;
653 ssize_t rv;
654 socklen_t sunlen;
655 int fd = ev->ident;
656
657 sunlen = sizeof(myname);
658 if (getsockname(fd, (struct sockaddr *)&myname, &sunlen) != 0) {
659 /*
660 * This should never happen, so ensure that it doesn't
661 * happen again.
662 */
663 struct kevent *cev = allocevchange();
664 logerror("getsockname() unix failed");
665 EV_SET(cev, fd, EVFILT_READ, EV_DISABLE,
666 0, 0, (intptr_t) dispatch_read_funix);
667 return;
668 }
669
670 dprintf("Unix socket (%s) active\n", myname.sun_path);
671
672 sunlen = sizeof(fromunix);
673 rv = recvfrom(fd, linebuf, MAXLINE, 0,
674 (struct sockaddr *)&fromunix, &sunlen);
675 if (rv > 0) {
676 linebuf[rv] = '\0';
677 printline(LocalHostName, linebuf, 0);
678 } else if (rv < 0 && errno != EINTR) {
679 logerror("recvfrom() unix `%s'", myname.sun_path);
680 }
681 }
682
683 /*
684 * Dispatch routine for reading Internet sockets.
685 */
686 static void
687 dispatch_read_finet(struct kevent *ev)
688 {
689 #ifdef LIBWRAP
690 struct request_info req;
691 #endif
692 struct sockaddr_storage frominet;
693 ssize_t rv;
694 socklen_t len;
695 int fd = ev->ident;
696 int reject = 0;
697
698 dprintf("inet socket active\n");
699
700 #ifdef LIBWRAP
701 request_init(&req, RQ_DAEMON, "syslogd", RQ_FILE, fd, NULL);
702 fromhost(&req);
703 reject = !hosts_access(&req);
704 if (reject)
705 dprintf("access denied\n");
706 #endif
707
708 len = sizeof(frominet);
709 rv = recvfrom(fd, linebuf, MAXLINE, 0,
710 (struct sockaddr *)&frominet, &len);
711 if (rv == 0 || (rv < 0 && errno == EINTR))
712 return;
713 else if (rv < 0) {
714 logerror("recvfrom inet");
715 return;
716 }
717
718 linebuf[rv] = '\0';
719 if (!reject)
720 printline(cvthname(&frominet), linebuf,
721 RemoteAddDate ? ADDDATE : 0);
722 }
723
724 /*
725 * given a pointer to an array of char *'s, a pointer to its current
726 * size and current allocated max size, and a new char * to add, add
727 * it, update everything as necessary, possibly allocating a new array
728 */
729 void
730 logpath_add(char ***lp, int *szp, int *maxszp, char *new)
731 {
732 char **nlp;
733 int newmaxsz;
734
735 dprintf("Adding `%s' to the %p logpath list\n", new, *lp);
736 if (*szp == *maxszp) {
737 if (*maxszp == 0) {
738 newmaxsz = 4; /* start of with enough for now */
739 *lp = NULL;
740 } else
741 newmaxsz = *maxszp * 2;
742 nlp = realloc(*lp, sizeof(char *) * (newmaxsz + 1));
743 if (nlp == NULL) {
744 logerror("Couldn't allocate line buffer");
745 die(NULL);
746 }
747 *lp = nlp;
748 *maxszp = newmaxsz;
749 }
750 if (((*lp)[(*szp)++] = strdup(new)) == NULL) {
751 logerror("Couldn't allocate logpath");
752 die(NULL);
753 }
754 (*lp)[(*szp)] = NULL; /* always keep it NULL terminated */
755 }
756
757 /* do a file of log sockets */
758 void
759 logpath_fileadd(char ***lp, int *szp, int *maxszp, char *file)
760 {
761 FILE *fp;
762 char *line;
763 size_t len;
764
765 fp = fopen(file, "r");
766 if (fp == NULL) {
767 logerror("Could not open socket file list `%s'", file);
768 die(NULL);
769 }
770
771 while ((line = fgetln(fp, &len))) {
772 line[len - 1] = 0;
773 logpath_add(lp, szp, maxszp, line);
774 }
775 fclose(fp);
776 }
777
778 /*
779 * Take a raw input line, decode the message, and print the message
780 * on the appropriate log files.
781 */
782 void
783 printline(char *hname, char *msg, int flags)
784 {
785 int c, pri;
786 char *p, *q, line[MAXLINE + 1];
787 long n;
788
789 /* test for special codes */
790 pri = DEFUPRI;
791 p = msg;
792 if (*p == '<') {
793 errno = 0;
794 n = strtol(p + 1, &q, 10);
795 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
796 p = q + 1;
797 pri = (int)n;
798 }
799 }
800 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
801 pri = DEFUPRI;
802
803 /*
804 * Don't allow users to log kernel messages.
805 * NOTE: Since LOG_KERN == 0, this will also match
806 * messages with no facility specified.
807 */
808 if ((pri & LOG_FACMASK) == LOG_KERN)
809 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
810
811 q = line;
812
813 while ((c = *p++) != '\0' &&
814 q < &line[sizeof(line) - 2]) {
815 c &= 0177;
816 if (iscntrl(c))
817 if (c == '\n')
818 *q++ = ' ';
819 else if (c == '\t')
820 *q++ = '\t';
821 else {
822 *q++ = '^';
823 *q++ = c ^ 0100;
824 }
825 else
826 *q++ = c;
827 }
828 *q = '\0';
829
830 logmsg(pri, line, hname, flags);
831 }
832
833 /*
834 * Take a raw input line from /dev/klog, split and format similar to syslog().
835 */
836 void
837 printsys(char *msg)
838 {
839 int n, pri, flags, is_printf;
840 char *p, *q;
841
842 for (p = msg; *p != '\0'; ) {
843 flags = ISKERNEL | ADDDATE;
844 if (SyncKernel)
845 flags |= SYNC_FILE;
846 pri = DEFSPRI;
847 is_printf = 1;
848 if (*p == '<') {
849 errno = 0;
850 n = (int)strtol(p + 1, &q, 10);
851 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
852 p = q + 1;
853 pri = n;
854 is_printf = 0;
855 }
856 }
857 if (is_printf) {
858 /* kernel printf's come out on console */
859 flags |= IGN_CONS;
860 }
861 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
862 pri = DEFSPRI;
863 for (q = p; *q != '\0' && *q != '\n'; q++)
864 /* look for end of line */;
865 if (*q != '\0')
866 *q++ = '\0';
867 logmsg(pri, p, LocalHostName, flags);
868 p = q;
869 }
870 }
871
872 time_t now;
873
874 /*
875 * Check to see if `name' matches the provided specification, using the
876 * specified strstr function.
877 */
878 int
879 matches_spec(const char *name, const char *spec,
880 char *(*check)(const char *, const char *))
881 {
882 const char *s;
883 char prev, next;
884
885 if ((s = (*check)(spec, name)) != NULL) {
886 prev = s == spec ? ',' : *(s - 1);
887 next = *(s + strlen(name));
888
889 if (prev == ',' && (next == '\0' || next == ','))
890 return (1);
891 }
892
893 return (0);
894 }
895
896 /*
897 * Log a message to the appropriate log files, users, etc. based on
898 * the priority.
899 */
900 void
901 logmsg(int pri, char *msg, char *from, int flags)
902 {
903 struct filed *f;
904 int fac, msglen, omask, prilev, i;
905 char *timestamp;
906 char prog[NAME_MAX + 1];
907 char buf[MAXLINE + 1];
908
909 dprintf("logmsg: pri 0%o, flags 0x%x, from %s, msg %s\n",
910 pri, flags, from, msg);
911
912 omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
913
914 /*
915 * Check to see if msg looks non-standard.
916 */
917 msglen = strlen(msg);
918 if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
919 msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
920 flags |= ADDDATE;
921
922 (void)time(&now);
923 if (flags & ADDDATE)
924 timestamp = ctime(&now) + 4;
925 else {
926 timestamp = msg;
927 msg += 16;
928 msglen -= 16;
929 }
930
931 /* skip leading whitespace */
932 while (isspace((unsigned char)*msg)) {
933 msg++;
934 msglen--;
935 }
936
937 /* extract facility and priority level */
938 if (flags & MARK)
939 fac = LOG_NFACILITIES;
940 else
941 fac = LOG_FAC(pri);
942 prilev = LOG_PRI(pri);
943
944 /* extract program name */
945 for (i = 0; i < NAME_MAX; i++) {
946 if (!isprint((unsigned char)msg[i]) ||
947 msg[i] == ':' || msg[i] == '[')
948 break;
949 prog[i] = msg[i];
950 }
951 prog[i] = '\0';
952
953 /* add kernel prefix for kernel messages */
954 if (flags & ISKERNEL) {
955 snprintf(buf, sizeof(buf), "%s: %s",
956 _PATH_UNIX, msg);
957 msg = buf;
958 msglen = strlen(buf);
959 }
960
961 /* log the message to the particular outputs */
962 if (!Initialized) {
963 f = &consfile;
964 f->f_file = open(ctty, O_WRONLY, 0);
965
966 if (f->f_file >= 0) {
967 (void)strncpy(f->f_lasttime, timestamp, 15);
968 fprintlog(f, flags, msg);
969 (void)close(f->f_file);
970 }
971 (void)sigsetmask(omask);
972 return;
973 }
974 for (f = Files; f; f = f->f_next) {
975 /* skip messages that are incorrect priority */
976 if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
977 ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
978 ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
979 )
980 || f->f_pmask[fac] == INTERNAL_NOPRI)
981 continue;
982
983 /* skip messages with the incorrect host name */
984 if (f->f_host != NULL) {
985 switch (f->f_host[0]) {
986 case '+':
987 if (! matches_spec(from, f->f_host + 1,
988 strcasestr))
989 continue;
990 break;
991 case '-':
992 if (matches_spec(from, f->f_host + 1,
993 strcasestr))
994 continue;
995 break;
996 }
997 }
998
999 /* skip messages with the incorrect program name */
1000 if (f->f_program != NULL) {
1001 switch (f->f_program[0]) {
1002 case '+':
1003 if (! matches_spec(prog, f->f_program + 1,
1004 strstr))
1005 continue;
1006 break;
1007 case '-':
1008 if (matches_spec(prog, f->f_program + 1,
1009 strstr))
1010 continue;
1011 break;
1012 default:
1013 if (! matches_spec(prog, f->f_program,
1014 strstr))
1015 continue;
1016 break;
1017 }
1018 }
1019
1020 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
1021 continue;
1022
1023 /* don't output marks to recently written files */
1024 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1025 continue;
1026
1027 /*
1028 * suppress duplicate lines to this file unless NoRepeat
1029 */
1030 if ((flags & MARK) == 0 && msglen == f->f_prevlen &&
1031 !NoRepeat &&
1032 !strcmp(msg, f->f_prevline) &&
1033 !strcasecmp(from, f->f_prevhost)) {
1034 (void)strncpy(f->f_lasttime, timestamp, 15);
1035 f->f_prevcount++;
1036 dprintf("Msg repeated %d times, %ld sec of %d\n",
1037 f->f_prevcount, (long)(now - f->f_time),
1038 repeatinterval[f->f_repeatcount]);
1039 /*
1040 * If domark would have logged this by now,
1041 * flush it now (so we don't hold isolated messages),
1042 * but back off so we'll flush less often
1043 * in the future.
1044 */
1045 if (now > REPEATTIME(f)) {
1046 fprintlog(f, flags, (char *)NULL);
1047 BACKOFF(f);
1048 }
1049 } else {
1050 /* new line, save it */
1051 if (f->f_prevcount)
1052 fprintlog(f, 0, (char *)NULL);
1053 f->f_repeatcount = 0;
1054 f->f_prevpri = pri;
1055 (void)strncpy(f->f_lasttime, timestamp, 15);
1056 (void)strncpy(f->f_prevhost, from,
1057 sizeof(f->f_prevhost));
1058 if (msglen < MAXSVLINE) {
1059 f->f_prevlen = msglen;
1060 (void)strlcpy(f->f_prevline, msg,
1061 sizeof(f->f_prevline));
1062 fprintlog(f, flags, (char *)NULL);
1063 } else {
1064 f->f_prevline[0] = 0;
1065 f->f_prevlen = 0;
1066 fprintlog(f, flags, msg);
1067 }
1068 }
1069 }
1070 (void)sigsetmask(omask);
1071 }
1072
1073 void
1074 fprintlog(struct filed *f, int flags, char *msg)
1075 {
1076 struct iovec iov[10];
1077 struct iovec *v;
1078 struct addrinfo *r;
1079 int j, l, lsent, fail, retry;
1080 char line[MAXLINE + 1], repbuf[80], greetings[200];
1081 #define ADDEV() assert(++v - iov < A_CNT(iov))
1082
1083 v = iov;
1084 if (f->f_type == F_WALL) {
1085 v->iov_base = greetings;
1086 v->iov_len = snprintf(greetings, sizeof greetings,
1087 "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
1088 f->f_prevhost, ctime(&now));
1089 ADDEV();
1090 v->iov_base = "";
1091 v->iov_len = 0;
1092 ADDEV();
1093 } else {
1094 v->iov_base = f->f_lasttime;
1095 v->iov_len = 15;
1096 ADDEV();
1097 v->iov_base = " ";
1098 v->iov_len = 1;
1099 ADDEV();
1100 }
1101
1102 if (LogFacPri) {
1103 static char fp_buf[30];
1104 const char *f_s = NULL, *p_s = NULL;
1105 int fac = f->f_prevpri & LOG_FACMASK;
1106 int pri = LOG_PRI(f->f_prevpri);
1107 char f_n[5], p_n[5];
1108
1109 if (LogFacPri > 1) {
1110 CODE *c;
1111
1112 for (c = facilitynames; c->c_name != NULL; c++) {
1113 if (c->c_val == fac) {
1114 f_s = c->c_name;
1115 break;
1116 }
1117 }
1118 for (c = prioritynames; c->c_name != NULL; c++) {
1119 if (c->c_val == pri) {
1120 p_s = c->c_name;
1121 break;
1122 }
1123 }
1124 }
1125 if (f_s == NULL) {
1126 snprintf(f_n, sizeof(f_n), "%d", LOG_FAC(fac));
1127 f_s = f_n;
1128 }
1129 if (p_s == NULL) {
1130 snprintf(p_n, sizeof(p_n), "%d", pri);
1131 p_s = p_n;
1132 }
1133 snprintf(fp_buf, sizeof(fp_buf), "<%s.%s>", f_s, p_s);
1134 v->iov_base = fp_buf;
1135 v->iov_len = strlen(fp_buf);
1136 } else {
1137 v->iov_base = "";
1138 v->iov_len = 0;
1139 }
1140 ADDEV();
1141
1142 v->iov_base = f->f_prevhost;
1143 v->iov_len = strlen(v->iov_base);
1144 ADDEV();
1145 v->iov_base = " ";
1146 v->iov_len = 1;
1147 ADDEV();
1148
1149 if (msg) {
1150 v->iov_base = msg;
1151 v->iov_len = strlen(msg);
1152 } else if (f->f_prevcount > 1) {
1153 v->iov_base = repbuf;
1154 v->iov_len = snprintf(repbuf, sizeof repbuf,
1155 "last message repeated %d times", f->f_prevcount);
1156 } else {
1157 v->iov_base = f->f_prevline;
1158 v->iov_len = f->f_prevlen;
1159 }
1160 ADDEV();
1161
1162 dprintf("Logging to %s", TypeNames[f->f_type]);
1163 f->f_time = now;
1164
1165 switch (f->f_type) {
1166 case F_UNUSED:
1167 dprintf("\n");
1168 break;
1169
1170 case F_FORW:
1171 dprintf(" %s\n", f->f_un.f_forw.f_hname);
1172 /*
1173 * check for local vs remote messages
1174 * (from FreeBSD PR#bin/7055)
1175 */
1176 if (strcasecmp(f->f_prevhost, LocalHostName)) {
1177 l = snprintf(line, sizeof(line) - 1,
1178 "<%d>%.15s [%s]: %s",
1179 f->f_prevpri, (char *) iov[0].iov_base,
1180 f->f_prevhost, (char *) iov[5].iov_base);
1181 } else {
1182 l = snprintf(line, sizeof(line) - 1, "<%d>%.15s %s",
1183 f->f_prevpri, (char *) iov[0].iov_base,
1184 (char *) iov[5].iov_base);
1185 }
1186 if (l > MAXLINE)
1187 l = MAXLINE;
1188 if (finet) {
1189 lsent = -1;
1190 fail = 0;
1191 for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
1192 retry = 0;
1193 for (j = 0; j < *finet; j++) {
1194 #if 0
1195 /*
1196 * should we check AF first, or just
1197 * trial and error? FWD
1198 */
1199 if (r->ai_family ==
1200 address_family_of(finet[j+1]))
1201 #endif
1202 sendagain:
1203 lsent = sendto(finet[j+1], line, l, 0,
1204 r->ai_addr, r->ai_addrlen);
1205 if (lsent == -1) {
1206 switch (errno) {
1207 case ENOBUFS:
1208 /* wait/retry/drop */
1209 if (++retry < 5) {
1210 usleep(1000);
1211 goto sendagain;
1212 }
1213 break;
1214 case EHOSTDOWN:
1215 case EHOSTUNREACH:
1216 case ENETDOWN:
1217 /* drop */
1218 break;
1219 default:
1220 /* busted */
1221 fail++;
1222 break;
1223 }
1224 } else if (lsent == l)
1225 break;
1226 }
1227 }
1228 if (lsent != l && fail) {
1229 f->f_type = F_UNUSED;
1230 logerror("sendto() failed");
1231 }
1232 }
1233 break;
1234
1235 case F_PIPE:
1236 dprintf(" %s\n", f->f_un.f_pipe.f_pname);
1237 v->iov_base = "\n";
1238 v->iov_len = 1;
1239 ADDEV();
1240 if (f->f_un.f_pipe.f_pid == 0) {
1241 if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
1242 &f->f_un.f_pipe.f_pid)) < 0) {
1243 f->f_type = F_UNUSED;
1244 logerror(f->f_un.f_pipe.f_pname);
1245 break;
1246 }
1247 }
1248 if (writev(f->f_file, iov, v - iov) < 0) {
1249 int e = errno;
1250 if (f->f_un.f_pipe.f_pid > 0) {
1251 (void) close(f->f_file);
1252 deadq_enter(f->f_un.f_pipe.f_pid,
1253 f->f_un.f_pipe.f_pname);
1254 }
1255 f->f_un.f_pipe.f_pid = 0;
1256 /*
1257 * If the error was EPIPE, then what is likely
1258 * has happened is we have a command that is
1259 * designed to take a single message line and
1260 * then exit, but we tried to feed it another
1261 * one before we reaped the child and thus
1262 * reset our state.
1263 *
1264 * Well, now we've reset our state, so try opening
1265 * the pipe and sending the message again if EPIPE
1266 * was the error.
1267 */
1268 if (e == EPIPE) {
1269 if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
1270 &f->f_un.f_pipe.f_pid)) < 0) {
1271 f->f_type = F_UNUSED;
1272 logerror(f->f_un.f_pipe.f_pname);
1273 break;
1274 }
1275 if (writev(f->f_file, iov, v - iov) < 0) {
1276 e = errno;
1277 if (f->f_un.f_pipe.f_pid > 0) {
1278 (void) close(f->f_file);
1279 deadq_enter(f->f_un.f_pipe.f_pid,
1280 f->f_un.f_pipe.f_pname);
1281 }
1282 f->f_un.f_pipe.f_pid = 0;
1283 } else
1284 e = 0;
1285 }
1286 if (e != 0) {
1287 errno = e;
1288 logerror(f->f_un.f_pipe.f_pname);
1289 }
1290 }
1291 break;
1292
1293 case F_CONSOLE:
1294 if (flags & IGN_CONS) {
1295 dprintf(" (ignored)\n");
1296 break;
1297 }
1298 /* FALLTHROUGH */
1299
1300 case F_TTY:
1301 case F_FILE:
1302 dprintf(" %s\n", f->f_un.f_fname);
1303 if (f->f_type != F_FILE) {
1304 v->iov_base = "\r\n";
1305 v->iov_len = 2;
1306 } else {
1307 v->iov_base = "\n";
1308 v->iov_len = 1;
1309 }
1310 ADDEV();
1311 again:
1312 if (writev(f->f_file, iov, v - iov) < 0) {
1313 int e = errno;
1314 if (f->f_type == F_FILE && e == ENOSPC) {
1315 int lasterror = f->f_lasterror;
1316 f->f_lasterror = e;
1317 if (lasterror != e)
1318 logerror(f->f_un.f_fname);
1319 break;
1320 }
1321 (void)close(f->f_file);
1322 /*
1323 * Check for errors on TTY's due to loss of tty
1324 */
1325 if ((e == EIO || e == EBADF) && f->f_type != F_FILE) {
1326 f->f_file = open(f->f_un.f_fname,
1327 O_WRONLY|O_APPEND, 0);
1328 if (f->f_file < 0) {
1329 f->f_type = F_UNUSED;
1330 logerror(f->f_un.f_fname);
1331 } else
1332 goto again;
1333 } else {
1334 f->f_type = F_UNUSED;
1335 errno = e;
1336 f->f_lasterror = e;
1337 logerror(f->f_un.f_fname);
1338 }
1339 } else {
1340 f->f_lasterror = 0;
1341 if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC))
1342 (void)fsync(f->f_file);
1343 }
1344 break;
1345
1346 case F_USERS:
1347 case F_WALL:
1348 dprintf("\n");
1349 v->iov_base = "\r\n";
1350 v->iov_len = 2;
1351 ADDEV();
1352 wallmsg(f, iov, v - iov);
1353 break;
1354 }
1355 f->f_prevcount = 0;
1356 }
1357
1358 /*
1359 * WALLMSG -- Write a message to the world at large
1360 *
1361 * Write the specified message to either the entire
1362 * world, or a list of approved users.
1363 */
1364 void
1365 wallmsg(struct filed *f, struct iovec *iov, size_t iovcnt)
1366 {
1367 static int reenter; /* avoid calling ourselves */
1368 int i;
1369 char *p;
1370 static struct utmpentry *ohead = NULL;
1371 struct utmpentry *ep;
1372
1373 if (reenter++)
1374 return;
1375
1376 (void)getutentries(NULL, &ep);
1377 if (ep != ohead) {
1378 freeutentries(ohead);
1379 ohead = ep;
1380 }
1381 /* NOSTRICT */
1382 for (; ep; ep = ep->next) {
1383 if (f->f_type == F_WALL) {
1384 if ((p = ttymsg(iov, iovcnt, ep->line, TTYMSGTIME))
1385 != NULL) {
1386 errno = 0; /* already in msg */
1387 logerror(p);
1388 }
1389 continue;
1390 }
1391 /* should we send the message to this user? */
1392 for (i = 0; i < MAXUNAMES; i++) {
1393 if (!f->f_un.f_uname[i][0])
1394 break;
1395 if (strcmp(f->f_un.f_uname[i], ep->name) == 0) {
1396 if ((p = ttymsg(iov, iovcnt, ep->line,
1397 TTYMSGTIME)) != NULL) {
1398 errno = 0; /* already in msg */
1399 logerror(p);
1400 }
1401 break;
1402 }
1403 }
1404 }
1405 reenter = 0;
1406 }
1407
1408 void
1409 reapchild(struct kevent *ev)
1410 {
1411 int status;
1412 pid_t pid;
1413 struct filed *f;
1414
1415 while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
1416 if (!Initialized || ShuttingDown) {
1417 /*
1418 * Be silent while we are initializing or
1419 * shutting down.
1420 */
1421 continue;
1422 }
1423
1424 if (deadq_remove(pid))
1425 continue;
1426
1427 /* Now, look in the list of active processes. */
1428 for (f = Files; f != NULL; f = f->f_next) {
1429 if (f->f_type == F_PIPE &&
1430 f->f_un.f_pipe.f_pid == pid) {
1431 (void) close(f->f_file);
1432 f->f_un.f_pipe.f_pid = 0;
1433 log_deadchild(pid, status,
1434 f->f_un.f_pipe.f_pname);
1435 break;
1436 }
1437 }
1438 }
1439 }
1440
1441 /*
1442 * Return a printable representation of a host address.
1443 */
1444 char *
1445 cvthname(struct sockaddr_storage *f)
1446 {
1447 int error;
1448 const int niflag = NI_DGRAM;
1449 static char host[NI_MAXHOST], ip[NI_MAXHOST];
1450
1451 error = getnameinfo((struct sockaddr*)f, ((struct sockaddr*)f)->sa_len,
1452 ip, sizeof ip, NULL, 0, NI_NUMERICHOST|niflag);
1453
1454 dprintf("cvthname(%s)\n", ip);
1455
1456 if (error) {
1457 dprintf("Malformed from address %s\n", gai_strerror(error));
1458 return ("???");
1459 }
1460
1461 if (!UseNameService)
1462 return (ip);
1463
1464 error = getnameinfo((struct sockaddr*)f, ((struct sockaddr*)f)->sa_len,
1465 host, sizeof host, NULL, 0, niflag);
1466 if (error) {
1467 dprintf("Host name for your address (%s) unknown\n", ip);
1468 return (ip);
1469 }
1470
1471 trim_localdomain(host);
1472
1473 return (host);
1474 }
1475
1476 void
1477 trim_localdomain(char *host)
1478 {
1479 size_t hl;
1480
1481 hl = strlen(host);
1482 if (hl > 0 && host[hl - 1] == '.')
1483 host[--hl] = '\0';
1484
1485 if (hl > LocalDomainLen && host[hl - LocalDomainLen - 1] == '.' &&
1486 strcasecmp(&host[hl - LocalDomainLen], LocalDomain) == 0)
1487 host[hl - LocalDomainLen - 1] = '\0';
1488 }
1489
1490 void
1491 domark(struct kevent *ev)
1492 {
1493 struct filed *f;
1494 dq_t q, nextq;
1495
1496 /*
1497 * XXX Should we bother to adjust for the # of times the timer
1498 * has expired (i.e. in case we miss one?). This information is
1499 * returned to us in ev->data.
1500 */
1501
1502 now = time((time_t *)NULL);
1503 MarkSeq += TIMERINTVL;
1504 if (MarkSeq >= MarkInterval) {
1505 logmsg(LOG_INFO, "-- MARK --", LocalHostName, ADDDATE|MARK);
1506 MarkSeq = 0;
1507 }
1508
1509 for (f = Files; f; f = f->f_next) {
1510 if (f->f_prevcount && now >= REPEATTIME(f)) {
1511 dprintf("Flush %s: repeated %d times, %d sec.\n",
1512 TypeNames[f->f_type], f->f_prevcount,
1513 repeatinterval[f->f_repeatcount]);
1514 fprintlog(f, 0, (char *)NULL);
1515 BACKOFF(f);
1516 }
1517 }
1518
1519 /* Walk the dead queue, and see if we should signal somebody. */
1520 for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = nextq) {
1521 nextq = TAILQ_NEXT(q, dq_entries);
1522 switch (q->dq_timeout) {
1523 case 0:
1524 /* Already signalled once, try harder now. */
1525 if (kill(q->dq_pid, SIGKILL) != 0)
1526 (void) deadq_remove(q->dq_pid);
1527 break;
1528
1529 case 1:
1530 /*
1531 * Timed out on the dead queue, send terminate
1532 * signal. Note that we leave the removal from
1533 * the dead queue to reapchild(), which will
1534 * also log the event (unless the process
1535 * didn't even really exist, in case we simply
1536 * drop it from the dead queue).
1537 */
1538 if (kill(q->dq_pid, SIGTERM) != 0) {
1539 (void) deadq_remove(q->dq_pid);
1540 break;
1541 }
1542 /* FALLTHROUGH */
1543
1544 default:
1545 q->dq_timeout--;
1546 }
1547 }
1548 }
1549
1550 /*
1551 * Print syslogd errors some place.
1552 */
1553 void
1554 logerror(const char *fmt, ...)
1555 {
1556 static int logerror_running;
1557 va_list ap;
1558 char tmpbuf[BUFSIZ];
1559 char buf[BUFSIZ];
1560
1561 /* If there's an error while trying to log an error, give up. */
1562 if (logerror_running)
1563 return;
1564 logerror_running = 1;
1565
1566 va_start(ap, fmt);
1567
1568 (void)vsnprintf(tmpbuf, sizeof(tmpbuf), fmt, ap);
1569
1570 va_end(ap);
1571
1572 if (errno)
1573 (void)snprintf(buf, sizeof(buf), "syslogd: %s: %s",
1574 tmpbuf, strerror(errno));
1575 else
1576 (void)snprintf(buf, sizeof(buf), "syslogd: %s", tmpbuf);
1577
1578 if (daemonized)
1579 logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1580 if (!daemonized && Debug)
1581 dprintf("%s\n", buf);
1582 if (!daemonized && !Debug)
1583 printf("%s\n", buf);
1584
1585 logerror_running = 0;
1586 }
1587
1588 void
1589 die(struct kevent *ev)
1590 {
1591 struct filed *f;
1592 char **p;
1593
1594 ShuttingDown = 1; /* Don't log SIGCHLDs. */
1595 for (f = Files; f != NULL; f = f->f_next) {
1596 /* flush any pending output */
1597 if (f->f_prevcount)
1598 fprintlog(f, 0, (char *)NULL);
1599 if (f->f_type == F_PIPE && f->f_un.f_pipe.f_pid > 0) {
1600 (void) close(f->f_file);
1601 f->f_un.f_pipe.f_pid = 0;
1602 }
1603 }
1604 errno = 0;
1605 if (ev != NULL)
1606 logerror("Exiting on signal %d", (int) ev->ident);
1607 else
1608 logerror("Fatal error, exiting");
1609 for (p = LogPaths; p && *p; p++)
1610 unlink(*p);
1611 exit(0);
1612 }
1613
1614 /*
1615 * INIT -- Initialize syslogd from configuration table
1616 */
1617 void
1618 init(struct kevent *ev)
1619 {
1620 size_t i;
1621 FILE *cf;
1622 struct filed *f, *next, **nextp;
1623 char *p;
1624 char cline[LINE_MAX];
1625 char prog[NAME_MAX + 1];
1626 char host[MAXHOSTNAMELEN];
1627 char hostMsg[2*MAXHOSTNAMELEN + 40];
1628
1629 dprintf("init\n");
1630
1631 (void)strlcpy(oldLocalHostName, LocalHostName,
1632 sizeof(oldLocalHostName));
1633 (void)gethostname(LocalHostName, sizeof(LocalHostName));
1634 if ((p = strchr(LocalHostName, '.')) != NULL) {
1635 *p++ = '\0';
1636 LocalDomain = p;
1637 } else
1638 LocalDomain = "";
1639 LocalDomainLen = strlen(LocalDomain);
1640
1641 /*
1642 * Close all open log files.
1643 */
1644 Initialized = 0;
1645 for (f = Files; f != NULL; f = next) {
1646 /* flush any pending output */
1647 if (f->f_prevcount)
1648 fprintlog(f, 0, (char *)NULL);
1649
1650 switch (f->f_type) {
1651 case F_FILE:
1652 case F_TTY:
1653 case F_CONSOLE:
1654 (void)close(f->f_file);
1655 break;
1656 case F_PIPE:
1657 if (f->f_un.f_pipe.f_pid > 0) {
1658 (void)close(f->f_file);
1659 deadq_enter(f->f_un.f_pipe.f_pid,
1660 f->f_un.f_pipe.f_pname);
1661 }
1662 f->f_un.f_pipe.f_pid = 0;
1663 break;
1664 case F_FORW:
1665 if (f->f_un.f_forw.f_addr)
1666 freeaddrinfo(f->f_un.f_forw.f_addr);
1667 break;
1668 }
1669 next = f->f_next;
1670 if (f->f_program != NULL)
1671 free(f->f_program);
1672 if (f->f_host != NULL)
1673 free(f->f_host);
1674 free((char *)f);
1675 }
1676 Files = NULL;
1677 nextp = &Files;
1678
1679 /*
1680 * Close all open sockets
1681 */
1682
1683 if (finet) {
1684 for (i = 0; i < *finet; i++) {
1685 if (close(finet[i+1]) < 0) {
1686 logerror("close() failed");
1687 die(NULL);
1688 }
1689 }
1690 }
1691
1692 /*
1693 * Reset counter of forwarding actions
1694 */
1695
1696 NumForwards=0;
1697
1698 /* open the configuration file */
1699 if ((cf = fopen(ConfFile, "r")) == NULL) {
1700 dprintf("Cannot open `%s'\n", ConfFile);
1701 *nextp = (struct filed *)calloc(1, sizeof(*f));
1702 cfline("*.ERR\t/dev/console", *nextp, "*", "*");
1703 (*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1704 cfline("*.PANIC\t*", (*nextp)->f_next, "*", "*");
1705 Initialized = 1;
1706 return;
1707 }
1708
1709 /*
1710 * Foreach line in the conf table, open that file.
1711 */
1712 f = NULL;
1713 strcpy(prog, "*");
1714 strcpy(host, "*");
1715 while (fgets(cline, sizeof(cline), cf) != NULL) {
1716 /*
1717 * check for end-of-section, comments, strip off trailing
1718 * spaces and newline character. #!prog is treated specially:
1719 * following lines apply only to that program.
1720 */
1721 for (p = cline; isspace((unsigned char)*p); ++p)
1722 continue;
1723 if (*p == '\0')
1724 continue;
1725 if (*p == '#') {
1726 p++;
1727 if (*p != '!' && *p != '+' && *p != '-')
1728 continue;
1729 }
1730 if (*p == '+' || *p == '-') {
1731 host[0] = *p++;
1732 while (isspace((unsigned char)*p))
1733 p++;
1734 if (*p == '\0' || *p == '*') {
1735 strcpy(host, "*");
1736 continue;
1737 }
1738 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
1739 if (*p == '@') {
1740 (void)strncpy(&host[i], LocalHostName,
1741 sizeof(host) - 1 - i);
1742 host[sizeof(host) - 1] = '\0';
1743 i = strlen(host) - 1;
1744 p++;
1745 continue;
1746 }
1747 if (!isalnum((unsigned char)*p) &&
1748 *p != '.' && *p != '-' && *p != ',')
1749 break;
1750 host[i] = *p++;
1751 }
1752 host[i] = '\0';
1753 continue;
1754 }
1755 if (*p == '!') {
1756 p++;
1757 while (isspace((unsigned char)*p))
1758 p++;
1759 if (*p == '\0' || *p == '*') {
1760 strcpy(prog, "*");
1761 continue;
1762 }
1763 for (i = 0; i < NAME_MAX; i++) {
1764 if (!isprint((unsigned char)p[i]))
1765 break;
1766 prog[i] = p[i];
1767 }
1768 prog[i] = '\0';
1769 continue;
1770 }
1771 for (p = strchr(cline, '\0'); isspace((unsigned char)*--p);)
1772 continue;
1773 *++p = '\0';
1774 f = (struct filed *)calloc(1, sizeof(*f));
1775 *nextp = f;
1776 nextp = &f->f_next;
1777 cfline(cline, f, prog, host);
1778 }
1779
1780 /* close the configuration file */
1781 (void)fclose(cf);
1782
1783 Initialized = 1;
1784
1785 if (Debug) {
1786 for (f = Files; f; f = f->f_next) {
1787 for (i = 0; i <= LOG_NFACILITIES; i++)
1788 if (f->f_pmask[i] == INTERNAL_NOPRI)
1789 printf("X ");
1790 else
1791 printf("%d ", f->f_pmask[i]);
1792 printf("%s: ", TypeNames[f->f_type]);
1793 switch (f->f_type) {
1794 case F_FILE:
1795 case F_TTY:
1796 case F_CONSOLE:
1797 printf("%s", f->f_un.f_fname);
1798 break;
1799
1800 case F_FORW:
1801 printf("%s", f->f_un.f_forw.f_hname);
1802 break;
1803
1804 case F_PIPE:
1805 printf("%s", f->f_un.f_pipe.f_pname);
1806 break;
1807
1808 case F_USERS:
1809 for (i = 0;
1810 i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1811 printf("%s, ", f->f_un.f_uname[i]);
1812 break;
1813 }
1814 if (f->f_program != NULL)
1815 printf(" (%s)", f->f_program);
1816 printf("\n");
1817 }
1818 }
1819
1820 finet = socksetup(PF_UNSPEC, bindhostname);
1821 if (finet) {
1822 if (SecureMode) {
1823 for (i = 0; i < *finet; i++) {
1824 if (shutdown(finet[i+1], SHUT_RD) < 0) {
1825 logerror("shutdown() failed");
1826 die(NULL);
1827 }
1828 }
1829 } else
1830 dprintf("Listening on inet and/or inet6 socket\n");
1831 dprintf("Sending on inet and/or inet6 socket\n");
1832 }
1833
1834 logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1835 dprintf("syslogd: restarted\n");
1836 /*
1837 * Log a change in hostname, but only on a restart (we detect this
1838 * by checking to see if we're passed a kevent).
1839 */
1840 if (ev != NULL && strcmp(oldLocalHostName, LocalHostName) != 0) {
1841 (void)snprintf(hostMsg, sizeof(hostMsg),
1842 "syslogd: host name changed, \"%s\" to \"%s\"",
1843 oldLocalHostName, LocalHostName);
1844 logmsg(LOG_SYSLOG|LOG_INFO, hostMsg, LocalHostName, ADDDATE);
1845 dprintf("%s\n", hostMsg);
1846 }
1847 }
1848
1849 /*
1850 * Crack a configuration file line
1851 */
1852 void
1853 cfline(char *line, struct filed *f, char *prog, char *host)
1854 {
1855 struct addrinfo hints, *res;
1856 int error, i, pri, syncfile;
1857 char *bp, *p, *q;
1858 char buf[MAXLINE];
1859
1860 dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
1861
1862 errno = 0; /* keep strerror() stuff out of logerror messages */
1863
1864 /* clear out file entry */
1865 memset(f, 0, sizeof(*f));
1866 for (i = 0; i <= LOG_NFACILITIES; i++)
1867 f->f_pmask[i] = INTERNAL_NOPRI;
1868
1869 /*
1870 * There should not be any space before the log facility.
1871 * Check this is okay, complain and fix if it is not.
1872 */
1873 q = line;
1874 if (isblank((unsigned char)*line)) {
1875 errno = 0;
1876 logerror(
1877 "Warning: `%s' space or tab before the log facility",
1878 line);
1879 /* Fix: strip all spaces/tabs before the log facility */
1880 while (*q++ && isblank((unsigned char)*q))
1881 /* skip blanks */;
1882 line = q;
1883 }
1884
1885 /*
1886 * q is now at the first char of the log facility
1887 * There should be at least one tab after the log facility
1888 * Check this is okay, and complain and fix if it is not.
1889 */
1890 q = line + strlen(line);
1891 while (!isblank((unsigned char)*q) && (q != line))
1892 q--;
1893 if ((q == line) && strlen(line)) {
1894 /* No tabs or space in a non empty line: complain */
1895 errno = 0;
1896 logerror(
1897 "Error: `%s' log facility or log target missing",
1898 line);
1899 return;
1900 }
1901
1902 /* save host name, if any */
1903 if (*host == '*')
1904 f->f_host = NULL;
1905 else {
1906 f->f_host = strdup(host);
1907 trim_localdomain(f->f_host);
1908 }
1909
1910 /* save program name, if any */
1911 if (*prog == '*')
1912 f->f_program = NULL;
1913 else
1914 f->f_program = strdup(prog);
1915
1916 /* scan through the list of selectors */
1917 for (p = line; *p && !isblank((unsigned char)*p);) {
1918 int pri_done, pri_cmp, pri_invert;
1919
1920 /* find the end of this facility name list */
1921 for (q = p; *q && !isblank((unsigned char)*q) && *q++ != '.'; )
1922 continue;
1923
1924 /* get the priority comparison */
1925 pri_cmp = 0;
1926 pri_done = 0;
1927 pri_invert = 0;
1928 if (*q == '!') {
1929 pri_invert = 1;
1930 q++;
1931 }
1932 while (! pri_done) {
1933 switch (*q) {
1934 case '<':
1935 pri_cmp = PRI_LT;
1936 q++;
1937 break;
1938 case '=':
1939 pri_cmp = PRI_EQ;
1940 q++;
1941 break;
1942 case '>':
1943 pri_cmp = PRI_GT;
1944 q++;
1945 break;
1946 default:
1947 pri_done = 1;
1948 break;
1949 }
1950 }
1951
1952 /* collect priority name */
1953 for (bp = buf; *q && !strchr("\t ,;", *q); )
1954 *bp++ = *q++;
1955 *bp = '\0';
1956
1957 /* skip cruft */
1958 while (strchr(",;", *q))
1959 q++;
1960
1961 /* decode priority name */
1962 if (*buf == '*') {
1963 pri = LOG_PRIMASK + 1;
1964 pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
1965 } else {
1966 pri = decode(buf, prioritynames);
1967 if (pri < 0) {
1968 errno = 0;
1969 logerror("Unknown priority name `%s'", buf);
1970 return;
1971 }
1972 }
1973 if (pri_cmp == 0)
1974 pri_cmp = UniquePriority ? PRI_EQ
1975 : PRI_EQ | PRI_GT;
1976 if (pri_invert)
1977 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
1978
1979 /* scan facilities */
1980 while (*p && !strchr("\t .;", *p)) {
1981 for (bp = buf; *p && !strchr("\t ,;.", *p); )
1982 *bp++ = *p++;
1983 *bp = '\0';
1984 if (*buf == '*')
1985 for (i = 0; i < LOG_NFACILITIES; i++) {
1986 f->f_pmask[i] = pri;
1987 f->f_pcmp[i] = pri_cmp;
1988 }
1989 else {
1990 i = decode(buf, facilitynames);
1991 if (i < 0) {
1992 errno = 0;
1993 logerror("Unknown facility name `%s'",
1994 buf);
1995 return;
1996 }
1997 f->f_pmask[i >> 3] = pri;
1998 f->f_pcmp[i >> 3] = pri_cmp;
1999 }
2000 while (*p == ',' || *p == ' ')
2001 p++;
2002 }
2003
2004 p = q;
2005 }
2006
2007 /* skip to action part */
2008 while (isblank((unsigned char)*p))
2009 p++;
2010
2011 if (*p == '-') {
2012 syncfile = 0;
2013 p++;
2014 } else
2015 syncfile = 1;
2016
2017 switch (*p) {
2018 case '@':
2019 (void)strlcpy(f->f_un.f_forw.f_hname, ++p,
2020 sizeof(f->f_un.f_forw.f_hname));
2021 memset(&hints, 0, sizeof(hints));
2022 hints.ai_family = AF_UNSPEC;
2023 hints.ai_socktype = SOCK_DGRAM;
2024 hints.ai_protocol = 0;
2025 error = getaddrinfo(f->f_un.f_forw.f_hname, "syslog", &hints,
2026 &res);
2027 if (error) {
2028 logerror(gai_strerror(error));
2029 break;
2030 }
2031 f->f_un.f_forw.f_addr = res;
2032 f->f_type = F_FORW;
2033 NumForwards++;
2034 break;
2035
2036 case '/':
2037 (void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
2038 if ((f->f_file = open(p, O_WRONLY|O_APPEND, 0)) < 0) {
2039 f->f_type = F_UNUSED;
2040 logerror(p);
2041 break;
2042 }
2043 if (syncfile)
2044 f->f_flags |= FFLAG_SYNC;
2045 if (isatty(f->f_file))
2046 f->f_type = F_TTY;
2047 else
2048 f->f_type = F_FILE;
2049 if (strcmp(p, ctty) == 0)
2050 f->f_type = F_CONSOLE;
2051 break;
2052
2053 case '|':
2054 f->f_un.f_pipe.f_pid = 0;
2055 (void) strlcpy(f->f_un.f_pipe.f_pname, p + 1,
2056 sizeof(f->f_un.f_pipe.f_pname));
2057 f->f_type = F_PIPE;
2058 break;
2059
2060 case '*':
2061 f->f_type = F_WALL;
2062 break;
2063
2064 default:
2065 for (i = 0; i < MAXUNAMES && *p; i++) {
2066 for (q = p; *q && *q != ','; )
2067 q++;
2068 (void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
2069 if ((q - p) > UT_NAMESIZE)
2070 f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
2071 else
2072 f->f_un.f_uname[i][q - p] = '\0';
2073 while (*q == ',' || *q == ' ')
2074 q++;
2075 p = q;
2076 }
2077 f->f_type = F_USERS;
2078 break;
2079 }
2080 }
2081
2082
2083 /*
2084 * Decode a symbolic name to a numeric value
2085 */
2086 int
2087 decode(const char *name, CODE *codetab)
2088 {
2089 CODE *c;
2090 char *p, buf[40];
2091
2092 if (isdigit((unsigned char)*name))
2093 return (atoi(name));
2094
2095 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
2096 if (isupper((unsigned char)*name))
2097 *p = tolower((unsigned char)*name);
2098 else
2099 *p = *name;
2100 }
2101 *p = '\0';
2102 for (c = codetab; c->c_name; c++)
2103 if (!strcmp(buf, c->c_name))
2104 return (c->c_val);
2105
2106 return (-1);
2107 }
2108
2109 /*
2110 * Retrieve the size of the kernel message buffer, via sysctl.
2111 */
2112 int
2113 getmsgbufsize(void)
2114 {
2115 int msgbufsize, mib[2];
2116 size_t size;
2117
2118 mib[0] = CTL_KERN;
2119 mib[1] = KERN_MSGBUFSIZE;
2120 size = sizeof msgbufsize;
2121 if (sysctl(mib, 2, &msgbufsize, &size, NULL, 0) == -1) {
2122 dprintf("Couldn't get kern.msgbufsize\n");
2123 return (0);
2124 }
2125 return (msgbufsize);
2126 }
2127
2128 int *
2129 socksetup(int af, const char *hostname)
2130 {
2131 struct addrinfo hints, *res, *r;
2132 struct kevent *ev;
2133 int error, maxs, *s, *socks;
2134 const int on = 1;
2135
2136 if(SecureMode && !NumForwards)
2137 return(NULL);
2138
2139 memset(&hints, 0, sizeof(hints));
2140 hints.ai_flags = AI_PASSIVE;
2141 hints.ai_family = af;
2142 hints.ai_socktype = SOCK_DGRAM;
2143 error = getaddrinfo(hostname, "syslog", &hints, &res);
2144 if (error) {
2145 logerror(gai_strerror(error));
2146 errno = 0;
2147 die(NULL);
2148 }
2149
2150 /* Count max number of sockets we may open */
2151 for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
2152 continue;
2153 socks = malloc((maxs+1) * sizeof(int));
2154 if (!socks) {
2155 logerror("Couldn't allocate memory for sockets");
2156 die(NULL);
2157 }
2158
2159 *socks = 0; /* num of sockets counter at start of array */
2160 s = socks + 1;
2161 for (r = res; r; r = r->ai_next) {
2162 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
2163 if (*s < 0) {
2164 logerror("socket() failed");
2165 continue;
2166 }
2167 if (r->ai_family == AF_INET6 && setsockopt(*s, IPPROTO_IPV6,
2168 IPV6_V6ONLY, &on, sizeof(on)) < 0) {
2169 logerror("setsockopt(IPV6_V6ONLY) failed");
2170 close(*s);
2171 continue;
2172 }
2173
2174 if (!SecureMode) {
2175 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
2176 logerror("bind() failed");
2177 close(*s);
2178 continue;
2179 }
2180 ev = allocevchange();
2181 EV_SET(ev, *s, EVFILT_READ, EV_ADD | EV_ENABLE,
2182 0, 0, (intptr_t) dispatch_read_finet);
2183 }
2184
2185 *socks = *socks + 1;
2186 s++;
2187 }
2188
2189 if (*socks == 0) {
2190 free (socks);
2191 if(Debug)
2192 return(NULL);
2193 else
2194 die(NULL);
2195 }
2196 if (res)
2197 freeaddrinfo(res);
2198
2199 return(socks);
2200 }
2201
2202 /*
2203 * Fairly similar to popen(3), but returns an open descriptor, as opposed
2204 * to a FILE *.
2205 */
2206 int
2207 p_open(char *prog, pid_t *rpid)
2208 {
2209 int pfd[2], nulldesc, i;
2210 pid_t pid;
2211 char *argv[4]; /* sh -c cmd NULL */
2212 char errmsg[200];
2213
2214 if (pipe(pfd) == -1)
2215 return (-1);
2216 if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1) {
2217 /* We are royally screwed anyway. */
2218 return (-1);
2219 }
2220
2221 switch ((pid = fork())) {
2222 case -1:
2223 (void) close(nulldesc);
2224 return (-1);
2225
2226 case 0:
2227 argv[0] = "sh";
2228 argv[1] = "-c";
2229 argv[2] = prog;
2230 argv[3] = NULL;
2231
2232 (void) setsid(); /* avoid catching SIGHUPs. */
2233
2234 /*
2235 * Reset ignored signals to their default behavior.
2236 */
2237 (void)signal(SIGTERM, SIG_DFL);
2238 (void)signal(SIGINT, SIG_DFL);
2239 (void)signal(SIGQUIT, SIG_DFL);
2240 (void)signal(SIGPIPE, SIG_DFL);
2241 (void)signal(SIGHUP, SIG_DFL);
2242
2243 dup2(pfd[0], STDIN_FILENO);
2244 dup2(nulldesc, STDOUT_FILENO);
2245 dup2(nulldesc, STDERR_FILENO);
2246 for (i = getdtablesize(); i > 2; i--)
2247 (void) close(i);
2248
2249 (void) execvp(_PATH_BSHELL, argv);
2250 _exit(255);
2251 }
2252
2253 (void) close(nulldesc);
2254 (void) close(pfd[0]);
2255
2256 /*
2257 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
2258 * supposed to get an EWOULDBLOCK on writev(2), which is
2259 * caught by the logic above anyway, which will in turn
2260 * close the pipe, and fork a new logging subprocess if
2261 * necessary. The stale subprocess will be killed some
2262 * time later unless it terminated itself due to closing
2263 * its input pipe.
2264 */
2265 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
2266 /* This is bad. */
2267 (void) snprintf(errmsg, sizeof(errmsg),
2268 "Warning: cannot change pipe to pid %d to "
2269 "non-blocking.", (int) pid);
2270 logerror(errmsg);
2271 }
2272 *rpid = pid;
2273 return (pfd[1]);
2274 }
2275
2276 void
2277 deadq_enter(pid_t pid, const char *name)
2278 {
2279 dq_t p;
2280 int status;
2281
2282 /*
2283 * Be paranoid: if we can't signal the process, don't enter it
2284 * into the dead queue (perhaps it's already dead). If possible,
2285 * we try to fetch and log the child's status.
2286 */
2287 if (kill(pid, 0) != 0) {
2288 if (waitpid(pid, &status, WNOHANG) > 0)
2289 log_deadchild(pid, status, name);
2290 return;
2291 }
2292
2293 p = malloc(sizeof(*p));
2294 if (p == NULL) {
2295 errno = 0;
2296 logerror("panic: out of memory!");
2297 exit(1);
2298 }
2299
2300 p->dq_pid = pid;
2301 p->dq_timeout = DQ_TIMO_INIT;
2302 TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
2303 }
2304
2305 int
2306 deadq_remove(pid_t pid)
2307 {
2308 dq_t q;
2309
2310 for (q = TAILQ_FIRST(&deadq_head); q != NULL;
2311 q = TAILQ_NEXT(q, dq_entries)) {
2312 if (q->dq_pid == pid) {
2313 TAILQ_REMOVE(&deadq_head, q, dq_entries);
2314 free(q);
2315 return (1);
2316 }
2317 }
2318 return (0);
2319 }
2320
2321 void
2322 log_deadchild(pid_t pid, int status, const char *name)
2323 {
2324 int code;
2325 char buf[256];
2326 const char *reason;
2327
2328 /* Keep strerror() struff out of logerror messages. */
2329 errno = 0;
2330 if (WIFSIGNALED(status)) {
2331 reason = "due to signal";
2332 code = WTERMSIG(status);
2333 } else {
2334 reason = "with status";
2335 code = WEXITSTATUS(status);
2336 if (code == 0)
2337 return;
2338 }
2339 (void) snprintf(buf, sizeof(buf),
2340 "Logging subprocess %d (%s) exited %s %d.",
2341 pid, name, reason, code);
2342 logerror(buf);
2343 }
2344
2345 static struct kevent changebuf[8];
2346 static int nchanges;
2347
2348 static struct kevent *
2349 allocevchange(void)
2350 {
2351
2352 if (nchanges == A_CNT(changebuf)) {
2353 /* XXX Error handling could be improved. */
2354 (void) wait_for_events(NULL, 0);
2355 }
2356
2357 return (&changebuf[nchanges++]);
2358 }
2359
2360 static int
2361 wait_for_events(struct kevent *events, size_t nevents)
2362 {
2363 int rv;
2364
2365 rv = kevent(fkq, nchanges ? changebuf : NULL, nchanges,
2366 events, nevents, NULL);
2367 nchanges = 0;
2368 return (rv);
2369 }
2370