syslogd.c revision 1.79 1 /* $NetBSD: syslogd.c,v 1.79 2006/09/15 20:32:59 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.79 2006/09/15 20:32:59 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] [-f config_file] [-g group] [-m mark_interval]\n"
613 "\t[-P file_list] [-p log_socket [-p log_socket2 ...]]\n"
614 "\t[-t chroot_dir] [-u user]\n", getprogname());
615 exit(1);
616 }
617
618 /*
619 * Dispatch routine for reading /dev/klog
620 */
621 static void
622 dispatch_read_klog(struct kevent *ev)
623 {
624 ssize_t rv;
625 int fd = ev->ident;
626
627 dprintf("Kernel log active\n");
628
629 rv = read(fd, linebuf, linebufsize - 1);
630 if (rv > 0) {
631 linebuf[rv] = '\0';
632 printsys(linebuf);
633 } else if (rv < 0 && errno != EINTR) {
634 /*
635 * /dev/klog has croaked. Disable the event
636 * so it won't bother us again.
637 */
638 struct kevent *cev = allocevchange();
639 logerror("klog failed");
640 EV_SET(cev, fd, EVFILT_READ, EV_DISABLE,
641 0, 0, (intptr_t) dispatch_read_klog);
642 }
643 }
644
645 /*
646 * Dispatch routine for reading Unix domain sockets.
647 */
648 static void
649 dispatch_read_funix(struct kevent *ev)
650 {
651 struct sockaddr_un myname, fromunix;
652 ssize_t rv;
653 socklen_t sunlen;
654 int fd = ev->ident;
655
656 sunlen = sizeof(myname);
657 if (getsockname(fd, (struct sockaddr *)&myname, &sunlen) != 0) {
658 /*
659 * This should never happen, so ensure that it doesn't
660 * happen again.
661 */
662 struct kevent *cev = allocevchange();
663 logerror("getsockname() unix failed");
664 EV_SET(cev, fd, EVFILT_READ, EV_DISABLE,
665 0, 0, (intptr_t) dispatch_read_funix);
666 return;
667 }
668
669 dprintf("Unix socket (%s) active\n", myname.sun_path);
670
671 sunlen = sizeof(fromunix);
672 rv = recvfrom(fd, linebuf, MAXLINE, 0,
673 (struct sockaddr *)&fromunix, &sunlen);
674 if (rv > 0) {
675 linebuf[rv] = '\0';
676 printline(LocalHostName, linebuf, 0);
677 } else if (rv < 0 && errno != EINTR) {
678 logerror("recvfrom() unix `%s'", myname.sun_path);
679 }
680 }
681
682 /*
683 * Dispatch routine for reading Internet sockets.
684 */
685 static void
686 dispatch_read_finet(struct kevent *ev)
687 {
688 #ifdef LIBWRAP
689 struct request_info req;
690 #endif
691 struct sockaddr_storage frominet;
692 ssize_t rv;
693 socklen_t len;
694 int fd = ev->ident;
695 int reject = 0;
696
697 dprintf("inet socket active\n");
698
699 #ifdef LIBWRAP
700 request_init(&req, RQ_DAEMON, "syslogd", RQ_FILE, fd, NULL);
701 fromhost(&req);
702 reject = !hosts_access(&req);
703 if (reject)
704 dprintf("access denied\n");
705 #endif
706
707 len = sizeof(frominet);
708 rv = recvfrom(fd, linebuf, MAXLINE, 0,
709 (struct sockaddr *)&frominet, &len);
710 if (rv == 0 || (rv < 0 && errno == EINTR))
711 return;
712 else if (rv < 0) {
713 logerror("recvfrom inet");
714 return;
715 }
716
717 linebuf[rv] = '\0';
718 if (!reject)
719 printline(cvthname(&frominet), linebuf,
720 RemoteAddDate ? ADDDATE : 0);
721 }
722
723 /*
724 * given a pointer to an array of char *'s, a pointer to its current
725 * size and current allocated max size, and a new char * to add, add
726 * it, update everything as necessary, possibly allocating a new array
727 */
728 void
729 logpath_add(char ***lp, int *szp, int *maxszp, char *new)
730 {
731 char **nlp;
732 int newmaxsz;
733
734 dprintf("Adding `%s' to the %p logpath list\n", new, *lp);
735 if (*szp == *maxszp) {
736 if (*maxszp == 0) {
737 newmaxsz = 4; /* start of with enough for now */
738 *lp = NULL;
739 } else
740 newmaxsz = *maxszp * 2;
741 nlp = realloc(*lp, sizeof(char *) * (newmaxsz + 1));
742 if (nlp == NULL) {
743 logerror("Couldn't allocate line buffer");
744 die(NULL);
745 }
746 *lp = nlp;
747 *maxszp = newmaxsz;
748 }
749 if (((*lp)[(*szp)++] = strdup(new)) == NULL) {
750 logerror("Couldn't allocate logpath");
751 die(NULL);
752 }
753 (*lp)[(*szp)] = NULL; /* always keep it NULL terminated */
754 }
755
756 /* do a file of log sockets */
757 void
758 logpath_fileadd(char ***lp, int *szp, int *maxszp, char *file)
759 {
760 FILE *fp;
761 char *line;
762 size_t len;
763
764 fp = fopen(file, "r");
765 if (fp == NULL) {
766 logerror("Could not open socket file list `%s'", file);
767 die(NULL);
768 }
769
770 while ((line = fgetln(fp, &len))) {
771 line[len - 1] = 0;
772 logpath_add(lp, szp, maxszp, line);
773 }
774 fclose(fp);
775 }
776
777 /*
778 * Take a raw input line, decode the message, and print the message
779 * on the appropriate log files.
780 */
781 void
782 printline(char *hname, char *msg, int flags)
783 {
784 int c, pri;
785 char *p, *q, line[MAXLINE + 1];
786 long n;
787
788 /* test for special codes */
789 pri = DEFUPRI;
790 p = msg;
791 if (*p == '<') {
792 errno = 0;
793 n = strtol(p + 1, &q, 10);
794 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
795 p = q + 1;
796 pri = (int)n;
797 }
798 }
799 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
800 pri = DEFUPRI;
801
802 /*
803 * Don't allow users to log kernel messages.
804 * NOTE: Since LOG_KERN == 0, this will also match
805 * messages with no facility specified.
806 */
807 if ((pri & LOG_FACMASK) == LOG_KERN)
808 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
809
810 q = line;
811
812 while ((c = *p++) != '\0' &&
813 q < &line[sizeof(line) - 2]) {
814 c &= 0177;
815 if (iscntrl(c))
816 if (c == '\n')
817 *q++ = ' ';
818 else if (c == '\t')
819 *q++ = '\t';
820 else {
821 *q++ = '^';
822 *q++ = c ^ 0100;
823 }
824 else
825 *q++ = c;
826 }
827 *q = '\0';
828
829 logmsg(pri, line, hname, flags);
830 }
831
832 /*
833 * Take a raw input line from /dev/klog, split and format similar to syslog().
834 */
835 void
836 printsys(char *msg)
837 {
838 int n, pri, flags, is_printf;
839 char *p, *q;
840
841 for (p = msg; *p != '\0'; ) {
842 flags = ISKERNEL | ADDDATE;
843 if (SyncKernel)
844 flags |= SYNC_FILE;
845 pri = DEFSPRI;
846 is_printf = 1;
847 if (*p == '<') {
848 errno = 0;
849 n = (int)strtol(p + 1, &q, 10);
850 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
851 p = q + 1;
852 pri = n;
853 is_printf = 0;
854 }
855 }
856 if (is_printf) {
857 /* kernel printf's come out on console */
858 flags |= IGN_CONS;
859 }
860 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
861 pri = DEFSPRI;
862 for (q = p; *q != '\0' && *q != '\n'; q++)
863 /* look for end of line */;
864 if (*q != '\0')
865 *q++ = '\0';
866 logmsg(pri, p, LocalHostName, flags);
867 p = q;
868 }
869 }
870
871 time_t now;
872
873 /*
874 * Check to see if `name' matches the provided specification, using the
875 * specified strstr function.
876 */
877 int
878 matches_spec(const char *name, const char *spec,
879 char *(*check)(const char *, const char *))
880 {
881 const char *s;
882 char prev, next;
883
884 if ((s = (*check)(spec, name)) != NULL) {
885 prev = s == spec ? ',' : *(s - 1);
886 next = *(s + strlen(name));
887
888 if (prev == ',' && (next == '\0' || next == ','))
889 return (1);
890 }
891
892 return (0);
893 }
894
895 /*
896 * Log a message to the appropriate log files, users, etc. based on
897 * the priority.
898 */
899 void
900 logmsg(int pri, char *msg, char *from, int flags)
901 {
902 struct filed *f;
903 int fac, msglen, omask, prilev, i;
904 char *timestamp;
905 char prog[NAME_MAX + 1];
906 char buf[MAXLINE + 1];
907
908 dprintf("logmsg: pri 0%o, flags 0x%x, from %s, msg %s\n",
909 pri, flags, from, msg);
910
911 omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
912
913 /*
914 * Check to see if msg looks non-standard.
915 */
916 msglen = strlen(msg);
917 if (msglen < 16 || msg[3] != ' ' || msg[6] != ' ' ||
918 msg[9] != ':' || msg[12] != ':' || msg[15] != ' ')
919 flags |= ADDDATE;
920
921 (void)time(&now);
922 if (flags & ADDDATE)
923 timestamp = ctime(&now) + 4;
924 else {
925 timestamp = msg;
926 msg += 16;
927 msglen -= 16;
928 }
929
930 /* skip leading whitespace */
931 while (isspace((unsigned char)*msg)) {
932 msg++;
933 msglen--;
934 }
935
936 /* extract facility and priority level */
937 if (flags & MARK)
938 fac = LOG_NFACILITIES;
939 else
940 fac = LOG_FAC(pri);
941 prilev = LOG_PRI(pri);
942
943 /* extract program name */
944 for (i = 0; i < NAME_MAX; i++) {
945 if (!isprint((unsigned char)msg[i]) ||
946 msg[i] == ':' || msg[i] == '[')
947 break;
948 prog[i] = msg[i];
949 }
950 prog[i] = '\0';
951
952 /* add kernel prefix for kernel messages */
953 if (flags & ISKERNEL) {
954 snprintf(buf, sizeof(buf), "%s: %s",
955 _PATH_UNIX, msg);
956 msg = buf;
957 msglen = strlen(buf);
958 }
959
960 /* log the message to the particular outputs */
961 if (!Initialized) {
962 f = &consfile;
963 f->f_file = open(ctty, O_WRONLY, 0);
964
965 if (f->f_file >= 0) {
966 (void)strncpy(f->f_lasttime, timestamp, 15);
967 fprintlog(f, flags, msg);
968 (void)close(f->f_file);
969 }
970 (void)sigsetmask(omask);
971 return;
972 }
973 for (f = Files; f; f = f->f_next) {
974 /* skip messages that are incorrect priority */
975 if (!(((f->f_pcmp[fac] & PRI_EQ) && (f->f_pmask[fac] == prilev))
976 ||((f->f_pcmp[fac] & PRI_LT) && (f->f_pmask[fac] < prilev))
977 ||((f->f_pcmp[fac] & PRI_GT) && (f->f_pmask[fac] > prilev))
978 )
979 || f->f_pmask[fac] == INTERNAL_NOPRI)
980 continue;
981
982 /* skip messages with the incorrect host name */
983 if (f->f_host != NULL) {
984 switch (f->f_host[0]) {
985 case '+':
986 if (! matches_spec(from, f->f_host + 1,
987 strcasestr))
988 continue;
989 break;
990 case '-':
991 if (matches_spec(from, f->f_host + 1,
992 strcasestr))
993 continue;
994 break;
995 }
996 }
997
998 /* skip messages with the incorrect program name */
999 if (f->f_program != NULL) {
1000 switch (f->f_program[0]) {
1001 case '+':
1002 if (! matches_spec(prog, f->f_program + 1,
1003 strstr))
1004 continue;
1005 break;
1006 case '-':
1007 if (matches_spec(prog, f->f_program + 1,
1008 strstr))
1009 continue;
1010 break;
1011 default:
1012 if (! matches_spec(prog, f->f_program,
1013 strstr))
1014 continue;
1015 break;
1016 }
1017 }
1018
1019 if (f->f_type == F_CONSOLE && (flags & IGN_CONS))
1020 continue;
1021
1022 /* don't output marks to recently written files */
1023 if ((flags & MARK) && (now - f->f_time) < MarkInterval / 2)
1024 continue;
1025
1026 /*
1027 * suppress duplicate lines to this file unless NoRepeat
1028 */
1029 if ((flags & MARK) == 0 && msglen == f->f_prevlen &&
1030 !NoRepeat &&
1031 !strcmp(msg, f->f_prevline) &&
1032 !strcasecmp(from, f->f_prevhost)) {
1033 (void)strncpy(f->f_lasttime, timestamp, 15);
1034 f->f_prevcount++;
1035 dprintf("Msg repeated %d times, %ld sec of %d\n",
1036 f->f_prevcount, (long)(now - f->f_time),
1037 repeatinterval[f->f_repeatcount]);
1038 /*
1039 * If domark would have logged this by now,
1040 * flush it now (so we don't hold isolated messages),
1041 * but back off so we'll flush less often
1042 * in the future.
1043 */
1044 if (now > REPEATTIME(f)) {
1045 fprintlog(f, flags, (char *)NULL);
1046 BACKOFF(f);
1047 }
1048 } else {
1049 /* new line, save it */
1050 if (f->f_prevcount)
1051 fprintlog(f, 0, (char *)NULL);
1052 f->f_repeatcount = 0;
1053 f->f_prevpri = pri;
1054 (void)strncpy(f->f_lasttime, timestamp, 15);
1055 (void)strncpy(f->f_prevhost, from,
1056 sizeof(f->f_prevhost));
1057 if (msglen < MAXSVLINE) {
1058 f->f_prevlen = msglen;
1059 (void)strlcpy(f->f_prevline, msg,
1060 sizeof(f->f_prevline));
1061 fprintlog(f, flags, (char *)NULL);
1062 } else {
1063 f->f_prevline[0] = 0;
1064 f->f_prevlen = 0;
1065 fprintlog(f, flags, msg);
1066 }
1067 }
1068 }
1069 (void)sigsetmask(omask);
1070 }
1071
1072 void
1073 fprintlog(struct filed *f, int flags, char *msg)
1074 {
1075 struct iovec iov[10];
1076 struct iovec *v;
1077 struct addrinfo *r;
1078 int j, l, lsent;
1079 char line[MAXLINE + 1], repbuf[80], greetings[200];
1080 #define ADDEV() assert(++v - iov < A_CNT(iov))
1081
1082 v = iov;
1083 if (f->f_type == F_WALL) {
1084 v->iov_base = greetings;
1085 v->iov_len = snprintf(greetings, sizeof greetings,
1086 "\r\n\7Message from syslogd@%s at %.24s ...\r\n",
1087 f->f_prevhost, ctime(&now));
1088 ADDEV();
1089 v->iov_base = "";
1090 v->iov_len = 0;
1091 ADDEV();
1092 } else {
1093 v->iov_base = f->f_lasttime;
1094 v->iov_len = 15;
1095 ADDEV();
1096 v->iov_base = " ";
1097 v->iov_len = 1;
1098 ADDEV();
1099 }
1100
1101 if (LogFacPri) {
1102 static char fp_buf[30];
1103 const char *f_s = NULL, *p_s = NULL;
1104 int fac = f->f_prevpri & LOG_FACMASK;
1105 int pri = LOG_PRI(f->f_prevpri);
1106 char f_n[5], p_n[5];
1107
1108 if (LogFacPri > 1) {
1109 CODE *c;
1110
1111 for (c = facilitynames; c->c_name != NULL; c++) {
1112 if (c->c_val == fac) {
1113 f_s = c->c_name;
1114 break;
1115 }
1116 }
1117 for (c = prioritynames; c->c_name != NULL; c++) {
1118 if (c->c_val == pri) {
1119 p_s = c->c_name;
1120 break;
1121 }
1122 }
1123 }
1124 if (f_s == NULL) {
1125 snprintf(f_n, sizeof(f_n), "%d", LOG_FAC(fac));
1126 f_s = f_n;
1127 }
1128 if (p_s == NULL) {
1129 snprintf(p_n, sizeof(p_n), "%d", pri);
1130 p_s = p_n;
1131 }
1132 snprintf(fp_buf, sizeof(fp_buf), "<%s.%s>", f_s, p_s);
1133 v->iov_base = fp_buf;
1134 v->iov_len = strlen(fp_buf);
1135 } else {
1136 v->iov_base = "";
1137 v->iov_len = 0;
1138 }
1139 ADDEV();
1140
1141 v->iov_base = f->f_prevhost;
1142 v->iov_len = strlen(v->iov_base);
1143 ADDEV();
1144 v->iov_base = " ";
1145 v->iov_len = 1;
1146 ADDEV();
1147
1148 if (msg) {
1149 v->iov_base = msg;
1150 v->iov_len = strlen(msg);
1151 } else if (f->f_prevcount > 1) {
1152 v->iov_base = repbuf;
1153 v->iov_len = snprintf(repbuf, sizeof repbuf,
1154 "last message repeated %d times", f->f_prevcount);
1155 } else {
1156 v->iov_base = f->f_prevline;
1157 v->iov_len = f->f_prevlen;
1158 }
1159 ADDEV();
1160
1161 dprintf("Logging to %s", TypeNames[f->f_type]);
1162 f->f_time = now;
1163
1164 switch (f->f_type) {
1165 case F_UNUSED:
1166 dprintf("\n");
1167 break;
1168
1169 case F_FORW:
1170 dprintf(" %s\n", f->f_un.f_forw.f_hname);
1171 /*
1172 * check for local vs remote messages
1173 * (from FreeBSD PR#bin/7055)
1174 */
1175 if (strcasecmp(f->f_prevhost, LocalHostName)) {
1176 l = snprintf(line, sizeof(line) - 1,
1177 "<%d>%.15s [%s]: %s",
1178 f->f_prevpri, (char *) iov[0].iov_base,
1179 f->f_prevhost, (char *) iov[5].iov_base);
1180 } else {
1181 l = snprintf(line, sizeof(line) - 1, "<%d>%.15s %s",
1182 f->f_prevpri, (char *) iov[0].iov_base,
1183 (char *) iov[5].iov_base);
1184 }
1185 if (l > MAXLINE)
1186 l = MAXLINE;
1187 if (finet) {
1188 lsent = -1;
1189 for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
1190 for (j = 0; j < *finet; j++) {
1191 #if 0
1192 /*
1193 * should we check AF first, or just
1194 * trial and error? FWD
1195 */
1196 if (r->ai_family ==
1197 address_family_of(finet[j+1]))
1198 #endif
1199 lsent = sendto(finet[j+1], line, l, 0,
1200 r->ai_addr, r->ai_addrlen);
1201 if (lsent == l)
1202 break;
1203 }
1204 }
1205 if (lsent != l) {
1206 f->f_type = F_UNUSED;
1207 logerror("sendto() failed");
1208 }
1209 }
1210 break;
1211
1212 case F_PIPE:
1213 dprintf(" %s\n", f->f_un.f_pipe.f_pname);
1214 v->iov_base = "\n";
1215 v->iov_len = 1;
1216 ADDEV();
1217 if (f->f_un.f_pipe.f_pid == 0) {
1218 if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
1219 &f->f_un.f_pipe.f_pid)) < 0) {
1220 f->f_type = F_UNUSED;
1221 logerror(f->f_un.f_pipe.f_pname);
1222 break;
1223 }
1224 }
1225 if (writev(f->f_file, iov, v - iov) < 0) {
1226 int e = errno;
1227 if (f->f_un.f_pipe.f_pid > 0) {
1228 (void) close(f->f_file);
1229 deadq_enter(f->f_un.f_pipe.f_pid,
1230 f->f_un.f_pipe.f_pname);
1231 }
1232 f->f_un.f_pipe.f_pid = 0;
1233 /*
1234 * If the error was EPIPE, then what is likely
1235 * has happened is we have a command that is
1236 * designed to take a single message line and
1237 * then exit, but we tried to feed it another
1238 * one before we reaped the child and thus
1239 * reset our state.
1240 *
1241 * Well, now we've reset our state, so try opening
1242 * the pipe and sending the message again if EPIPE
1243 * was the error.
1244 */
1245 if (e == EPIPE) {
1246 if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
1247 &f->f_un.f_pipe.f_pid)) < 0) {
1248 f->f_type = F_UNUSED;
1249 logerror(f->f_un.f_pipe.f_pname);
1250 break;
1251 }
1252 if (writev(f->f_file, iov, v - iov) < 0) {
1253 e = errno;
1254 if (f->f_un.f_pipe.f_pid > 0) {
1255 (void) close(f->f_file);
1256 deadq_enter(f->f_un.f_pipe.f_pid,
1257 f->f_un.f_pipe.f_pname);
1258 }
1259 f->f_un.f_pipe.f_pid = 0;
1260 } else
1261 e = 0;
1262 }
1263 if (e != 0) {
1264 errno = e;
1265 logerror(f->f_un.f_pipe.f_pname);
1266 }
1267 }
1268 break;
1269
1270 case F_CONSOLE:
1271 if (flags & IGN_CONS) {
1272 dprintf(" (ignored)\n");
1273 break;
1274 }
1275 /* FALLTHROUGH */
1276
1277 case F_TTY:
1278 case F_FILE:
1279 dprintf(" %s\n", f->f_un.f_fname);
1280 if (f->f_type != F_FILE) {
1281 v->iov_base = "\r\n";
1282 v->iov_len = 2;
1283 } else {
1284 v->iov_base = "\n";
1285 v->iov_len = 1;
1286 }
1287 ADDEV();
1288 again:
1289 if (writev(f->f_file, iov, v - iov) < 0) {
1290 int e = errno;
1291 if (f->f_type == F_FILE && e == ENOSPC) {
1292 int lasterror = f->f_lasterror;
1293 f->f_lasterror = e;
1294 if (lasterror != e)
1295 logerror(f->f_un.f_fname);
1296 break;
1297 }
1298 (void)close(f->f_file);
1299 /*
1300 * Check for errors on TTY's due to loss of tty
1301 */
1302 if ((e == EIO || e == EBADF) && f->f_type != F_FILE) {
1303 f->f_file = open(f->f_un.f_fname,
1304 O_WRONLY|O_APPEND, 0);
1305 if (f->f_file < 0) {
1306 f->f_type = F_UNUSED;
1307 logerror(f->f_un.f_fname);
1308 } else
1309 goto again;
1310 } else {
1311 f->f_type = F_UNUSED;
1312 errno = e;
1313 f->f_lasterror = e;
1314 logerror(f->f_un.f_fname);
1315 }
1316 } else {
1317 f->f_lasterror = 0;
1318 if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC))
1319 (void)fsync(f->f_file);
1320 }
1321 break;
1322
1323 case F_USERS:
1324 case F_WALL:
1325 dprintf("\n");
1326 v->iov_base = "\r\n";
1327 v->iov_len = 2;
1328 ADDEV();
1329 wallmsg(f, iov, v - iov);
1330 break;
1331 }
1332 f->f_prevcount = 0;
1333 }
1334
1335 /*
1336 * WALLMSG -- Write a message to the world at large
1337 *
1338 * Write the specified message to either the entire
1339 * world, or a list of approved users.
1340 */
1341 void
1342 wallmsg(struct filed *f, struct iovec *iov, size_t iovcnt)
1343 {
1344 static int reenter; /* avoid calling ourselves */
1345 int i;
1346 char *p;
1347 static struct utmpentry *ohead = NULL;
1348 struct utmpentry *ep;
1349
1350 if (reenter++)
1351 return;
1352
1353 (void)getutentries(NULL, &ep);
1354 if (ep != ohead) {
1355 freeutentries(ohead);
1356 ohead = ep;
1357 }
1358 /* NOSTRICT */
1359 for (; ep; ep = ep->next) {
1360 if (f->f_type == F_WALL) {
1361 if ((p = ttymsg(iov, iovcnt, ep->line, TTYMSGTIME))
1362 != NULL) {
1363 errno = 0; /* already in msg */
1364 logerror(p);
1365 }
1366 continue;
1367 }
1368 /* should we send the message to this user? */
1369 for (i = 0; i < MAXUNAMES; i++) {
1370 if (!f->f_un.f_uname[i][0])
1371 break;
1372 if (strcmp(f->f_un.f_uname[i], ep->name) == 0) {
1373 if ((p = ttymsg(iov, iovcnt, ep->line,
1374 TTYMSGTIME)) != NULL) {
1375 errno = 0; /* already in msg */
1376 logerror(p);
1377 }
1378 break;
1379 }
1380 }
1381 }
1382 reenter = 0;
1383 }
1384
1385 void
1386 reapchild(struct kevent *ev)
1387 {
1388 int status;
1389 pid_t pid;
1390 struct filed *f;
1391
1392 while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
1393 if (!Initialized || ShuttingDown) {
1394 /*
1395 * Be silent while we are initializing or
1396 * shutting down.
1397 */
1398 continue;
1399 }
1400
1401 if (deadq_remove(pid))
1402 continue;
1403
1404 /* Now, look in the list of active processes. */
1405 for (f = Files; f != NULL; f = f->f_next) {
1406 if (f->f_type == F_PIPE &&
1407 f->f_un.f_pipe.f_pid == pid) {
1408 (void) close(f->f_file);
1409 f->f_un.f_pipe.f_pid = 0;
1410 log_deadchild(pid, status,
1411 f->f_un.f_pipe.f_pname);
1412 break;
1413 }
1414 }
1415 }
1416 }
1417
1418 /*
1419 * Return a printable representation of a host address.
1420 */
1421 char *
1422 cvthname(struct sockaddr_storage *f)
1423 {
1424 int error;
1425 const int niflag = NI_DGRAM;
1426 static char host[NI_MAXHOST], ip[NI_MAXHOST];
1427
1428 error = getnameinfo((struct sockaddr*)f, ((struct sockaddr*)f)->sa_len,
1429 ip, sizeof ip, NULL, 0, NI_NUMERICHOST|niflag);
1430
1431 dprintf("cvthname(%s)\n", ip);
1432
1433 if (error) {
1434 dprintf("Malformed from address %s\n", gai_strerror(error));
1435 return ("???");
1436 }
1437
1438 if (!UseNameService)
1439 return (ip);
1440
1441 error = getnameinfo((struct sockaddr*)f, ((struct sockaddr*)f)->sa_len,
1442 host, sizeof host, NULL, 0, niflag);
1443 if (error) {
1444 dprintf("Host name for your address (%s) unknown\n", ip);
1445 return (ip);
1446 }
1447
1448 trim_localdomain(host);
1449
1450 return (host);
1451 }
1452
1453 void
1454 trim_localdomain(char *host)
1455 {
1456 size_t hl;
1457
1458 hl = strlen(host);
1459 if (hl > 0 && host[hl - 1] == '.')
1460 host[--hl] = '\0';
1461
1462 if (hl > LocalDomainLen && host[hl - LocalDomainLen - 1] == '.' &&
1463 strcasecmp(&host[hl - LocalDomainLen], LocalDomain) == 0)
1464 host[hl - LocalDomainLen - 1] = '\0';
1465 }
1466
1467 void
1468 domark(struct kevent *ev)
1469 {
1470 struct filed *f;
1471 dq_t q, nextq;
1472
1473 /*
1474 * XXX Should we bother to adjust for the # of times the timer
1475 * has expired (i.e. in case we miss one?). This information is
1476 * returned to us in ev->data.
1477 */
1478
1479 now = time((time_t *)NULL);
1480 MarkSeq += TIMERINTVL;
1481 if (MarkSeq >= MarkInterval) {
1482 logmsg(LOG_INFO, "-- MARK --", LocalHostName, ADDDATE|MARK);
1483 MarkSeq = 0;
1484 }
1485
1486 for (f = Files; f; f = f->f_next) {
1487 if (f->f_prevcount && now >= REPEATTIME(f)) {
1488 dprintf("Flush %s: repeated %d times, %d sec.\n",
1489 TypeNames[f->f_type], f->f_prevcount,
1490 repeatinterval[f->f_repeatcount]);
1491 fprintlog(f, 0, (char *)NULL);
1492 BACKOFF(f);
1493 }
1494 }
1495
1496 /* Walk the dead queue, and see if we should signal somebody. */
1497 for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = nextq) {
1498 nextq = TAILQ_NEXT(q, dq_entries);
1499 switch (q->dq_timeout) {
1500 case 0:
1501 /* Already signalled once, try harder now. */
1502 if (kill(q->dq_pid, SIGKILL) != 0)
1503 (void) deadq_remove(q->dq_pid);
1504 break;
1505
1506 case 1:
1507 /*
1508 * Timed out on the dead queue, send terminate
1509 * signal. Note that we leave the removal from
1510 * the dead queue to reapchild(), which will
1511 * also log the event (unless the process
1512 * didn't even really exist, in case we simply
1513 * drop it from the dead queue).
1514 */
1515 if (kill(q->dq_pid, SIGTERM) != 0) {
1516 (void) deadq_remove(q->dq_pid);
1517 break;
1518 }
1519 /* FALLTHROUGH */
1520
1521 default:
1522 q->dq_timeout--;
1523 }
1524 }
1525 }
1526
1527 /*
1528 * Print syslogd errors some place.
1529 */
1530 void
1531 logerror(const char *fmt, ...)
1532 {
1533 static int logerror_running;
1534 va_list ap;
1535 char tmpbuf[BUFSIZ];
1536 char buf[BUFSIZ];
1537
1538 /* If there's an error while trying to log an error, give up. */
1539 if (logerror_running)
1540 return;
1541 logerror_running = 1;
1542
1543 va_start(ap, fmt);
1544
1545 (void)vsnprintf(tmpbuf, sizeof(tmpbuf), fmt, ap);
1546
1547 va_end(ap);
1548
1549 if (errno)
1550 (void)snprintf(buf, sizeof(buf), "syslogd: %s: %s",
1551 tmpbuf, strerror(errno));
1552 else
1553 (void)snprintf(buf, sizeof(buf), "syslogd: %s", tmpbuf);
1554
1555 if (daemonized)
1556 logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1557 if (!daemonized && Debug)
1558 dprintf("%s\n", buf);
1559 if (!daemonized && !Debug)
1560 printf("%s\n", buf);
1561
1562 logerror_running = 0;
1563 }
1564
1565 void
1566 die(struct kevent *ev)
1567 {
1568 struct filed *f;
1569 char **p;
1570
1571 ShuttingDown = 1; /* Don't log SIGCHLDs. */
1572 for (f = Files; f != NULL; f = f->f_next) {
1573 /* flush any pending output */
1574 if (f->f_prevcount)
1575 fprintlog(f, 0, (char *)NULL);
1576 if (f->f_type == F_PIPE && f->f_un.f_pipe.f_pid > 0) {
1577 (void) close(f->f_file);
1578 f->f_un.f_pipe.f_pid = 0;
1579 }
1580 }
1581 errno = 0;
1582 if (ev != NULL)
1583 logerror("Exiting on signal %d", (int) ev->ident);
1584 else
1585 logerror("Fatal error, exiting");
1586 for (p = LogPaths; p && *p; p++)
1587 unlink(*p);
1588 exit(0);
1589 }
1590
1591 /*
1592 * INIT -- Initialize syslogd from configuration table
1593 */
1594 void
1595 init(struct kevent *ev)
1596 {
1597 int i;
1598 FILE *cf;
1599 struct filed *f, *next, **nextp;
1600 char *p;
1601 char cline[LINE_MAX];
1602 char prog[NAME_MAX + 1];
1603 char host[MAXHOSTNAMELEN];
1604 char hostMsg[2*MAXHOSTNAMELEN + 40];
1605
1606 dprintf("init\n");
1607
1608 (void)strlcpy(oldLocalHostName, LocalHostName,
1609 sizeof(oldLocalHostName));
1610 (void)gethostname(LocalHostName, sizeof(LocalHostName));
1611 if ((p = strchr(LocalHostName, '.')) != NULL) {
1612 *p++ = '\0';
1613 LocalDomain = p;
1614 } else
1615 LocalDomain = "";
1616 LocalDomainLen = strlen(LocalDomain);
1617
1618 /*
1619 * Close all open log files.
1620 */
1621 Initialized = 0;
1622 for (f = Files; f != NULL; f = next) {
1623 /* flush any pending output */
1624 if (f->f_prevcount)
1625 fprintlog(f, 0, (char *)NULL);
1626
1627 switch (f->f_type) {
1628 case F_FILE:
1629 case F_TTY:
1630 case F_CONSOLE:
1631 (void)close(f->f_file);
1632 break;
1633 case F_PIPE:
1634 if (f->f_un.f_pipe.f_pid > 0) {
1635 (void)close(f->f_file);
1636 deadq_enter(f->f_un.f_pipe.f_pid,
1637 f->f_un.f_pipe.f_pname);
1638 }
1639 f->f_un.f_pipe.f_pid = 0;
1640 break;
1641 case F_FORW:
1642 if (f->f_un.f_forw.f_addr)
1643 freeaddrinfo(f->f_un.f_forw.f_addr);
1644 break;
1645 }
1646 next = f->f_next;
1647 if (f->f_program != NULL)
1648 free(f->f_program);
1649 if (f->f_host != NULL)
1650 free(f->f_host);
1651 free((char *)f);
1652 }
1653 Files = NULL;
1654 nextp = &Files;
1655
1656 /*
1657 * Close all open sockets
1658 */
1659
1660 if (finet) {
1661 for (i = 0; i < *finet; i++) {
1662 if (close(finet[i+1]) < 0) {
1663 logerror("close() failed");
1664 die(NULL);
1665 }
1666 }
1667 }
1668
1669 /*
1670 * Reset counter of forwarding actions
1671 */
1672
1673 NumForwards=0;
1674
1675 /* open the configuration file */
1676 if ((cf = fopen(ConfFile, "r")) == NULL) {
1677 dprintf("Cannot open `%s'\n", ConfFile);
1678 *nextp = (struct filed *)calloc(1, sizeof(*f));
1679 cfline("*.ERR\t/dev/console", *nextp, "*", "*");
1680 (*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1681 cfline("*.PANIC\t*", (*nextp)->f_next, "*", "*");
1682 Initialized = 1;
1683 return;
1684 }
1685
1686 /*
1687 * Foreach line in the conf table, open that file.
1688 */
1689 f = NULL;
1690 strcpy(prog, "*");
1691 strcpy(host, "*");
1692 while (fgets(cline, sizeof(cline), cf) != NULL) {
1693 /*
1694 * check for end-of-section, comments, strip off trailing
1695 * spaces and newline character. #!prog is treated specially:
1696 * following lines apply only to that program.
1697 */
1698 for (p = cline; isspace((unsigned char)*p); ++p)
1699 continue;
1700 if (*p == '\0')
1701 continue;
1702 if (*p == '#') {
1703 p++;
1704 if (*p != '!' && *p != '+' && *p != '-')
1705 continue;
1706 }
1707 if (*p == '+' || *p == '-') {
1708 host[0] = *p++;
1709 while (isspace((unsigned char)*p))
1710 p++;
1711 if (*p == '\0' || *p == '*') {
1712 strcpy(host, "*");
1713 continue;
1714 }
1715 if (*p == '@')
1716 p = LocalHostName;
1717 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
1718 if (!isalnum((unsigned char)*p) &&
1719 *p != '.' && *p != '-' && *p != ',')
1720 break;
1721 host[i] = *p++;
1722 }
1723 host[i] = '\0';
1724 continue;
1725 }
1726 if (*p == '!') {
1727 p++;
1728 while (isspace((unsigned char)*p))
1729 p++;
1730 if (*p == '\0' || *p == '*') {
1731 strcpy(prog, "*");
1732 continue;
1733 }
1734 for (i = 0; i < NAME_MAX; i++) {
1735 if (!isprint((unsigned char)p[i]))
1736 break;
1737 prog[i] = p[i];
1738 }
1739 prog[i] = '\0';
1740 continue;
1741 }
1742 for (p = strchr(cline, '\0'); isspace((unsigned char)*--p);)
1743 continue;
1744 *++p = '\0';
1745 f = (struct filed *)calloc(1, sizeof(*f));
1746 *nextp = f;
1747 nextp = &f->f_next;
1748 cfline(cline, f, prog, host);
1749 }
1750
1751 /* close the configuration file */
1752 (void)fclose(cf);
1753
1754 Initialized = 1;
1755
1756 if (Debug) {
1757 for (f = Files; f; f = f->f_next) {
1758 for (i = 0; i <= LOG_NFACILITIES; i++)
1759 if (f->f_pmask[i] == INTERNAL_NOPRI)
1760 printf("X ");
1761 else
1762 printf("%d ", f->f_pmask[i]);
1763 printf("%s: ", TypeNames[f->f_type]);
1764 switch (f->f_type) {
1765 case F_FILE:
1766 case F_TTY:
1767 case F_CONSOLE:
1768 printf("%s", f->f_un.f_fname);
1769 break;
1770
1771 case F_FORW:
1772 printf("%s", f->f_un.f_forw.f_hname);
1773 break;
1774
1775 case F_PIPE:
1776 printf("%s", f->f_un.f_pipe.f_pname);
1777 break;
1778
1779 case F_USERS:
1780 for (i = 0;
1781 i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1782 printf("%s, ", f->f_un.f_uname[i]);
1783 break;
1784 }
1785 if (f->f_program != NULL)
1786 printf(" (%s)", f->f_program);
1787 printf("\n");
1788 }
1789 }
1790
1791 finet = socksetup(PF_UNSPEC, bindhostname);
1792 if (finet) {
1793 if (SecureMode) {
1794 for (i = 0; i < *finet; i++) {
1795 if (shutdown(finet[i+1], SHUT_RD) < 0) {
1796 logerror("shutdown() failed");
1797 die(NULL);
1798 }
1799 }
1800 } else
1801 dprintf("Listening on inet and/or inet6 socket\n");
1802 dprintf("Sending on inet and/or inet6 socket\n");
1803 }
1804
1805 logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1806 dprintf("syslogd: restarted\n");
1807 /*
1808 * Log a change in hostname, but only on a restart (we detect this
1809 * by checking to see if we're passed a kevent).
1810 */
1811 if (ev != NULL && strcmp(oldLocalHostName, LocalHostName) != 0) {
1812 (void)snprintf(hostMsg, sizeof(hostMsg),
1813 "syslogd: host name changed, \"%s\" to \"%s\"",
1814 oldLocalHostName, LocalHostName);
1815 logmsg(LOG_SYSLOG|LOG_INFO, hostMsg, LocalHostName, ADDDATE);
1816 dprintf("%s\n", hostMsg);
1817 }
1818 }
1819
1820 /*
1821 * Crack a configuration file line
1822 */
1823 void
1824 cfline(char *line, struct filed *f, char *prog, char *host)
1825 {
1826 struct addrinfo hints, *res;
1827 int error, i, pri, syncfile;
1828 char *bp, *p, *q;
1829 char buf[MAXLINE];
1830
1831 dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
1832
1833 errno = 0; /* keep strerror() stuff out of logerror messages */
1834
1835 /* clear out file entry */
1836 memset(f, 0, sizeof(*f));
1837 for (i = 0; i <= LOG_NFACILITIES; i++)
1838 f->f_pmask[i] = INTERNAL_NOPRI;
1839
1840 /*
1841 * There should not be any space before the log facility.
1842 * Check this is okay, complain and fix if it is not.
1843 */
1844 q = line;
1845 if (isblank((unsigned char)*line)) {
1846 errno = 0;
1847 logerror(
1848 "Warning: `%s' space or tab before the log facility",
1849 line);
1850 /* Fix: strip all spaces/tabs before the log facility */
1851 while (*q++ && isblank((unsigned char)*q))
1852 /* skip blanks */;
1853 line = q;
1854 }
1855
1856 /*
1857 * q is now at the first char of the log facility
1858 * There should be at least one tab after the log facility
1859 * Check this is okay, and complain and fix if it is not.
1860 */
1861 q = line + strlen(line);
1862 while (!isblank((unsigned char)*q) && (q != line))
1863 q--;
1864 if ((q == line) && strlen(line)) {
1865 /* No tabs or space in a non empty line: complain */
1866 errno = 0;
1867 logerror(
1868 "Error: `%s' log facility or log target missing",
1869 line);
1870 return;
1871 }
1872
1873 /* save host name, if any */
1874 if (*host == '*')
1875 f->f_host = NULL;
1876 else {
1877 f->f_host = strdup(host);
1878 trim_localdomain(f->f_host);
1879 }
1880
1881 /* save program name, if any */
1882 if (*prog == '*')
1883 f->f_program = NULL;
1884 else
1885 f->f_program = strdup(prog);
1886
1887 /* scan through the list of selectors */
1888 for (p = line; *p && !isblank((unsigned char)*p);) {
1889 int pri_done, pri_cmp, pri_invert;
1890
1891 /* find the end of this facility name list */
1892 for (q = p; *q && !isblank((unsigned char)*q) && *q++ != '.'; )
1893 continue;
1894
1895 /* get the priority comparison */
1896 pri_cmp = 0;
1897 pri_done = 0;
1898 pri_invert = 0;
1899 if (*q == '!') {
1900 pri_invert = 1;
1901 q++;
1902 }
1903 while (! pri_done) {
1904 switch (*q) {
1905 case '<':
1906 pri_cmp = PRI_LT;
1907 q++;
1908 break;
1909 case '=':
1910 pri_cmp = PRI_EQ;
1911 q++;
1912 break;
1913 case '>':
1914 pri_cmp = PRI_GT;
1915 q++;
1916 break;
1917 default:
1918 pri_done = 1;
1919 break;
1920 }
1921 }
1922
1923 /* collect priority name */
1924 for (bp = buf; *q && !strchr("\t ,;", *q); )
1925 *bp++ = *q++;
1926 *bp = '\0';
1927
1928 /* skip cruft */
1929 while (strchr(",;", *q))
1930 q++;
1931
1932 /* decode priority name */
1933 if (*buf == '*') {
1934 pri = LOG_PRIMASK + 1;
1935 pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
1936 } else {
1937 pri = decode(buf, prioritynames);
1938 if (pri < 0) {
1939 errno = 0;
1940 logerror("Unknown priority name `%s'", buf);
1941 return;
1942 }
1943 }
1944 if (pri_cmp == 0)
1945 pri_cmp = UniquePriority ? PRI_EQ
1946 : PRI_EQ | PRI_GT;
1947 if (pri_invert)
1948 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
1949
1950 /* scan facilities */
1951 while (*p && !strchr("\t .;", *p)) {
1952 for (bp = buf; *p && !strchr("\t ,;.", *p); )
1953 *bp++ = *p++;
1954 *bp = '\0';
1955 if (*buf == '*')
1956 for (i = 0; i < LOG_NFACILITIES; i++) {
1957 f->f_pmask[i] = pri;
1958 f->f_pcmp[i] = pri_cmp;
1959 }
1960 else {
1961 i = decode(buf, facilitynames);
1962 if (i < 0) {
1963 errno = 0;
1964 logerror("Unknown facility name `%s'",
1965 buf);
1966 return;
1967 }
1968 f->f_pmask[i >> 3] = pri;
1969 f->f_pcmp[i >> 3] = pri_cmp;
1970 }
1971 while (*p == ',' || *p == ' ')
1972 p++;
1973 }
1974
1975 p = q;
1976 }
1977
1978 /* skip to action part */
1979 while (isblank((unsigned char)*p))
1980 p++;
1981
1982 if (*p == '-') {
1983 syncfile = 0;
1984 p++;
1985 } else
1986 syncfile = 1;
1987
1988 switch (*p) {
1989 case '@':
1990 (void)strlcpy(f->f_un.f_forw.f_hname, ++p,
1991 sizeof(f->f_un.f_forw.f_hname));
1992 memset(&hints, 0, sizeof(hints));
1993 hints.ai_family = AF_UNSPEC;
1994 hints.ai_socktype = SOCK_DGRAM;
1995 hints.ai_protocol = 0;
1996 error = getaddrinfo(f->f_un.f_forw.f_hname, "syslog", &hints,
1997 &res);
1998 if (error) {
1999 logerror(gai_strerror(error));
2000 break;
2001 }
2002 f->f_un.f_forw.f_addr = res;
2003 f->f_type = F_FORW;
2004 NumForwards++;
2005 break;
2006
2007 case '/':
2008 (void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
2009 if ((f->f_file = open(p, O_WRONLY|O_APPEND, 0)) < 0) {
2010 f->f_type = F_UNUSED;
2011 logerror(p);
2012 break;
2013 }
2014 if (syncfile)
2015 f->f_flags |= FFLAG_SYNC;
2016 if (isatty(f->f_file))
2017 f->f_type = F_TTY;
2018 else
2019 f->f_type = F_FILE;
2020 if (strcmp(p, ctty) == 0)
2021 f->f_type = F_CONSOLE;
2022 break;
2023
2024 case '|':
2025 f->f_un.f_pipe.f_pid = 0;
2026 (void) strlcpy(f->f_un.f_pipe.f_pname, p + 1,
2027 sizeof(f->f_un.f_pipe.f_pname));
2028 f->f_type = F_PIPE;
2029 break;
2030
2031 case '*':
2032 f->f_type = F_WALL;
2033 break;
2034
2035 default:
2036 for (i = 0; i < MAXUNAMES && *p; i++) {
2037 for (q = p; *q && *q != ','; )
2038 q++;
2039 (void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
2040 if ((q - p) > UT_NAMESIZE)
2041 f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
2042 else
2043 f->f_un.f_uname[i][q - p] = '\0';
2044 while (*q == ',' || *q == ' ')
2045 q++;
2046 p = q;
2047 }
2048 f->f_type = F_USERS;
2049 break;
2050 }
2051 }
2052
2053
2054 /*
2055 * Decode a symbolic name to a numeric value
2056 */
2057 int
2058 decode(const char *name, CODE *codetab)
2059 {
2060 CODE *c;
2061 char *p, buf[40];
2062
2063 if (isdigit((unsigned char)*name))
2064 return (atoi(name));
2065
2066 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
2067 if (isupper((unsigned char)*name))
2068 *p = tolower((unsigned char)*name);
2069 else
2070 *p = *name;
2071 }
2072 *p = '\0';
2073 for (c = codetab; c->c_name; c++)
2074 if (!strcmp(buf, c->c_name))
2075 return (c->c_val);
2076
2077 return (-1);
2078 }
2079
2080 /*
2081 * Retrieve the size of the kernel message buffer, via sysctl.
2082 */
2083 int
2084 getmsgbufsize(void)
2085 {
2086 int msgbufsize, mib[2];
2087 size_t size;
2088
2089 mib[0] = CTL_KERN;
2090 mib[1] = KERN_MSGBUFSIZE;
2091 size = sizeof msgbufsize;
2092 if (sysctl(mib, 2, &msgbufsize, &size, NULL, 0) == -1) {
2093 dprintf("Couldn't get kern.msgbufsize\n");
2094 return (0);
2095 }
2096 return (msgbufsize);
2097 }
2098
2099 int *
2100 socksetup(int af, const char *hostname)
2101 {
2102 struct addrinfo hints, *res, *r;
2103 struct kevent *ev;
2104 int error, maxs, *s, *socks;
2105 const int on = 1;
2106
2107 if(SecureMode && !NumForwards)
2108 return(NULL);
2109
2110 memset(&hints, 0, sizeof(hints));
2111 hints.ai_flags = AI_PASSIVE;
2112 hints.ai_family = af;
2113 hints.ai_socktype = SOCK_DGRAM;
2114 error = getaddrinfo(hostname, "syslog", &hints, &res);
2115 if (error) {
2116 logerror(gai_strerror(error));
2117 errno = 0;
2118 die(NULL);
2119 }
2120
2121 /* Count max number of sockets we may open */
2122 for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
2123 continue;
2124 socks = malloc((maxs+1) * sizeof(int));
2125 if (!socks) {
2126 logerror("Couldn't allocate memory for sockets");
2127 die(NULL);
2128 }
2129
2130 *socks = 0; /* num of sockets counter at start of array */
2131 s = socks + 1;
2132 for (r = res; r; r = r->ai_next) {
2133 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
2134 if (*s < 0) {
2135 logerror("socket() failed");
2136 continue;
2137 }
2138 if (r->ai_family == AF_INET6 && setsockopt(*s, IPPROTO_IPV6,
2139 IPV6_V6ONLY, &on, sizeof(on)) < 0) {
2140 logerror("setsockopt(IPV6_V6ONLY) failed");
2141 close(*s);
2142 continue;
2143 }
2144
2145 if (!SecureMode) {
2146 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
2147 logerror("bind() failed");
2148 close(*s);
2149 continue;
2150 }
2151 ev = allocevchange();
2152 EV_SET(ev, *s, EVFILT_READ, EV_ADD | EV_ENABLE,
2153 0, 0, (intptr_t) dispatch_read_finet);
2154 }
2155
2156 *socks = *socks + 1;
2157 s++;
2158 }
2159
2160 if (*socks == 0) {
2161 free (socks);
2162 if(Debug)
2163 return(NULL);
2164 else
2165 die(NULL);
2166 }
2167 if (res)
2168 freeaddrinfo(res);
2169
2170 return(socks);
2171 }
2172
2173 /*
2174 * Fairly similar to popen(3), but returns an open descriptor, as opposed
2175 * to a FILE *.
2176 */
2177 int
2178 p_open(char *prog, pid_t *rpid)
2179 {
2180 int pfd[2], nulldesc, i;
2181 pid_t pid;
2182 char *argv[4]; /* sh -c cmd NULL */
2183 char errmsg[200];
2184
2185 if (pipe(pfd) == -1)
2186 return (-1);
2187 if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1) {
2188 /* We are royally screwed anyway. */
2189 return (-1);
2190 }
2191
2192 switch ((pid = fork())) {
2193 case -1:
2194 (void) close(nulldesc);
2195 return (-1);
2196
2197 case 0:
2198 argv[0] = "sh";
2199 argv[1] = "-c";
2200 argv[2] = prog;
2201 argv[3] = NULL;
2202
2203 (void) setsid(); /* avoid catching SIGHUPs. */
2204
2205 /*
2206 * Reset ignored signals to their default behavior.
2207 */
2208 (void)signal(SIGTERM, SIG_DFL);
2209 (void)signal(SIGINT, SIG_DFL);
2210 (void)signal(SIGQUIT, SIG_DFL);
2211 (void)signal(SIGPIPE, SIG_DFL);
2212 (void)signal(SIGHUP, SIG_DFL);
2213
2214 dup2(pfd[0], STDIN_FILENO);
2215 dup2(nulldesc, STDOUT_FILENO);
2216 dup2(nulldesc, STDERR_FILENO);
2217 for (i = getdtablesize(); i > 2; i--)
2218 (void) close(i);
2219
2220 (void) execvp(_PATH_BSHELL, argv);
2221 _exit(255);
2222 }
2223
2224 (void) close(nulldesc);
2225 (void) close(pfd[0]);
2226
2227 /*
2228 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
2229 * supposed to get an EWOULDBLOCK on writev(2), which is
2230 * caught by the logic above anyway, which will in turn
2231 * close the pipe, and fork a new logging subprocess if
2232 * necessary. The stale subprocess will be killed some
2233 * time later unless it terminated itself due to closing
2234 * its input pipe.
2235 */
2236 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
2237 /* This is bad. */
2238 (void) snprintf(errmsg, sizeof(errmsg),
2239 "Warning: cannot change pipe to pid %d to "
2240 "non-blocking.", (int) pid);
2241 logerror(errmsg);
2242 }
2243 *rpid = pid;
2244 return (pfd[1]);
2245 }
2246
2247 void
2248 deadq_enter(pid_t pid, const char *name)
2249 {
2250 dq_t p;
2251 int status;
2252
2253 /*
2254 * Be paranoid: if we can't signal the process, don't enter it
2255 * into the dead queue (perhaps it's already dead). If possible,
2256 * we try to fetch and log the child's status.
2257 */
2258 if (kill(pid, 0) != 0) {
2259 if (waitpid(pid, &status, WNOHANG) > 0)
2260 log_deadchild(pid, status, name);
2261 return;
2262 }
2263
2264 p = malloc(sizeof(*p));
2265 if (p == NULL) {
2266 errno = 0;
2267 logerror("panic: out of memory!");
2268 exit(1);
2269 }
2270
2271 p->dq_pid = pid;
2272 p->dq_timeout = DQ_TIMO_INIT;
2273 TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
2274 }
2275
2276 int
2277 deadq_remove(pid_t pid)
2278 {
2279 dq_t q;
2280
2281 for (q = TAILQ_FIRST(&deadq_head); q != NULL;
2282 q = TAILQ_NEXT(q, dq_entries)) {
2283 if (q->dq_pid == pid) {
2284 TAILQ_REMOVE(&deadq_head, q, dq_entries);
2285 free(q);
2286 return (1);
2287 }
2288 }
2289 return (0);
2290 }
2291
2292 void
2293 log_deadchild(pid_t pid, int status, const char *name)
2294 {
2295 int code;
2296 char buf[256];
2297 const char *reason;
2298
2299 /* Keep strerror() struff out of logerror messages. */
2300 errno = 0;
2301 if (WIFSIGNALED(status)) {
2302 reason = "due to signal";
2303 code = WTERMSIG(status);
2304 } else {
2305 reason = "with status";
2306 code = WEXITSTATUS(status);
2307 if (code == 0)
2308 return;
2309 }
2310 (void) snprintf(buf, sizeof(buf),
2311 "Logging subprocess %d (%s) exited %s %d.",
2312 pid, name, reason, code);
2313 logerror(buf);
2314 }
2315
2316 static struct kevent changebuf[8];
2317 static int nchanges;
2318
2319 static struct kevent *
2320 allocevchange(void)
2321 {
2322
2323 if (nchanges == A_CNT(changebuf)) {
2324 /* XXX Error handling could be improved. */
2325 (void) wait_for_events(NULL, 0);
2326 }
2327
2328 return (&changebuf[nchanges++]);
2329 }
2330
2331 static int
2332 wait_for_events(struct kevent *events, size_t nevents)
2333 {
2334 int rv;
2335
2336 rv = kevent(fkq, nchanges ? changebuf : NULL, nchanges,
2337 events, nevents, NULL);
2338 nchanges = 0;
2339 return (rv);
2340 }
2341