syslogd.c revision 1.80 1 /* $NetBSD: syslogd.c,v 1.80 2006/09/16 06:34:55 wiz 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.80 2006/09/16 06:34:55 wiz 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;
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 for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
1191 for (j = 0; j < *finet; j++) {
1192 #if 0
1193 /*
1194 * should we check AF first, or just
1195 * trial and error? FWD
1196 */
1197 if (r->ai_family ==
1198 address_family_of(finet[j+1]))
1199 #endif
1200 lsent = sendto(finet[j+1], line, l, 0,
1201 r->ai_addr, r->ai_addrlen);
1202 if (lsent == l)
1203 break;
1204 }
1205 }
1206 if (lsent != l) {
1207 f->f_type = F_UNUSED;
1208 logerror("sendto() failed");
1209 }
1210 }
1211 break;
1212
1213 case F_PIPE:
1214 dprintf(" %s\n", f->f_un.f_pipe.f_pname);
1215 v->iov_base = "\n";
1216 v->iov_len = 1;
1217 ADDEV();
1218 if (f->f_un.f_pipe.f_pid == 0) {
1219 if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
1220 &f->f_un.f_pipe.f_pid)) < 0) {
1221 f->f_type = F_UNUSED;
1222 logerror(f->f_un.f_pipe.f_pname);
1223 break;
1224 }
1225 }
1226 if (writev(f->f_file, iov, v - iov) < 0) {
1227 int e = errno;
1228 if (f->f_un.f_pipe.f_pid > 0) {
1229 (void) close(f->f_file);
1230 deadq_enter(f->f_un.f_pipe.f_pid,
1231 f->f_un.f_pipe.f_pname);
1232 }
1233 f->f_un.f_pipe.f_pid = 0;
1234 /*
1235 * If the error was EPIPE, then what is likely
1236 * has happened is we have a command that is
1237 * designed to take a single message line and
1238 * then exit, but we tried to feed it another
1239 * one before we reaped the child and thus
1240 * reset our state.
1241 *
1242 * Well, now we've reset our state, so try opening
1243 * the pipe and sending the message again if EPIPE
1244 * was the error.
1245 */
1246 if (e == EPIPE) {
1247 if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
1248 &f->f_un.f_pipe.f_pid)) < 0) {
1249 f->f_type = F_UNUSED;
1250 logerror(f->f_un.f_pipe.f_pname);
1251 break;
1252 }
1253 if (writev(f->f_file, iov, v - iov) < 0) {
1254 e = errno;
1255 if (f->f_un.f_pipe.f_pid > 0) {
1256 (void) close(f->f_file);
1257 deadq_enter(f->f_un.f_pipe.f_pid,
1258 f->f_un.f_pipe.f_pname);
1259 }
1260 f->f_un.f_pipe.f_pid = 0;
1261 } else
1262 e = 0;
1263 }
1264 if (e != 0) {
1265 errno = e;
1266 logerror(f->f_un.f_pipe.f_pname);
1267 }
1268 }
1269 break;
1270
1271 case F_CONSOLE:
1272 if (flags & IGN_CONS) {
1273 dprintf(" (ignored)\n");
1274 break;
1275 }
1276 /* FALLTHROUGH */
1277
1278 case F_TTY:
1279 case F_FILE:
1280 dprintf(" %s\n", f->f_un.f_fname);
1281 if (f->f_type != F_FILE) {
1282 v->iov_base = "\r\n";
1283 v->iov_len = 2;
1284 } else {
1285 v->iov_base = "\n";
1286 v->iov_len = 1;
1287 }
1288 ADDEV();
1289 again:
1290 if (writev(f->f_file, iov, v - iov) < 0) {
1291 int e = errno;
1292 if (f->f_type == F_FILE && e == ENOSPC) {
1293 int lasterror = f->f_lasterror;
1294 f->f_lasterror = e;
1295 if (lasterror != e)
1296 logerror(f->f_un.f_fname);
1297 break;
1298 }
1299 (void)close(f->f_file);
1300 /*
1301 * Check for errors on TTY's due to loss of tty
1302 */
1303 if ((e == EIO || e == EBADF) && f->f_type != F_FILE) {
1304 f->f_file = open(f->f_un.f_fname,
1305 O_WRONLY|O_APPEND, 0);
1306 if (f->f_file < 0) {
1307 f->f_type = F_UNUSED;
1308 logerror(f->f_un.f_fname);
1309 } else
1310 goto again;
1311 } else {
1312 f->f_type = F_UNUSED;
1313 errno = e;
1314 f->f_lasterror = e;
1315 logerror(f->f_un.f_fname);
1316 }
1317 } else {
1318 f->f_lasterror = 0;
1319 if ((flags & SYNC_FILE) && (f->f_flags & FFLAG_SYNC))
1320 (void)fsync(f->f_file);
1321 }
1322 break;
1323
1324 case F_USERS:
1325 case F_WALL:
1326 dprintf("\n");
1327 v->iov_base = "\r\n";
1328 v->iov_len = 2;
1329 ADDEV();
1330 wallmsg(f, iov, v - iov);
1331 break;
1332 }
1333 f->f_prevcount = 0;
1334 }
1335
1336 /*
1337 * WALLMSG -- Write a message to the world at large
1338 *
1339 * Write the specified message to either the entire
1340 * world, or a list of approved users.
1341 */
1342 void
1343 wallmsg(struct filed *f, struct iovec *iov, size_t iovcnt)
1344 {
1345 static int reenter; /* avoid calling ourselves */
1346 int i;
1347 char *p;
1348 static struct utmpentry *ohead = NULL;
1349 struct utmpentry *ep;
1350
1351 if (reenter++)
1352 return;
1353
1354 (void)getutentries(NULL, &ep);
1355 if (ep != ohead) {
1356 freeutentries(ohead);
1357 ohead = ep;
1358 }
1359 /* NOSTRICT */
1360 for (; ep; ep = ep->next) {
1361 if (f->f_type == F_WALL) {
1362 if ((p = ttymsg(iov, iovcnt, ep->line, TTYMSGTIME))
1363 != NULL) {
1364 errno = 0; /* already in msg */
1365 logerror(p);
1366 }
1367 continue;
1368 }
1369 /* should we send the message to this user? */
1370 for (i = 0; i < MAXUNAMES; i++) {
1371 if (!f->f_un.f_uname[i][0])
1372 break;
1373 if (strcmp(f->f_un.f_uname[i], ep->name) == 0) {
1374 if ((p = ttymsg(iov, iovcnt, ep->line,
1375 TTYMSGTIME)) != NULL) {
1376 errno = 0; /* already in msg */
1377 logerror(p);
1378 }
1379 break;
1380 }
1381 }
1382 }
1383 reenter = 0;
1384 }
1385
1386 void
1387 reapchild(struct kevent *ev)
1388 {
1389 int status;
1390 pid_t pid;
1391 struct filed *f;
1392
1393 while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
1394 if (!Initialized || ShuttingDown) {
1395 /*
1396 * Be silent while we are initializing or
1397 * shutting down.
1398 */
1399 continue;
1400 }
1401
1402 if (deadq_remove(pid))
1403 continue;
1404
1405 /* Now, look in the list of active processes. */
1406 for (f = Files; f != NULL; f = f->f_next) {
1407 if (f->f_type == F_PIPE &&
1408 f->f_un.f_pipe.f_pid == pid) {
1409 (void) close(f->f_file);
1410 f->f_un.f_pipe.f_pid = 0;
1411 log_deadchild(pid, status,
1412 f->f_un.f_pipe.f_pname);
1413 break;
1414 }
1415 }
1416 }
1417 }
1418
1419 /*
1420 * Return a printable representation of a host address.
1421 */
1422 char *
1423 cvthname(struct sockaddr_storage *f)
1424 {
1425 int error;
1426 const int niflag = NI_DGRAM;
1427 static char host[NI_MAXHOST], ip[NI_MAXHOST];
1428
1429 error = getnameinfo((struct sockaddr*)f, ((struct sockaddr*)f)->sa_len,
1430 ip, sizeof ip, NULL, 0, NI_NUMERICHOST|niflag);
1431
1432 dprintf("cvthname(%s)\n", ip);
1433
1434 if (error) {
1435 dprintf("Malformed from address %s\n", gai_strerror(error));
1436 return ("???");
1437 }
1438
1439 if (!UseNameService)
1440 return (ip);
1441
1442 error = getnameinfo((struct sockaddr*)f, ((struct sockaddr*)f)->sa_len,
1443 host, sizeof host, NULL, 0, niflag);
1444 if (error) {
1445 dprintf("Host name for your address (%s) unknown\n", ip);
1446 return (ip);
1447 }
1448
1449 trim_localdomain(host);
1450
1451 return (host);
1452 }
1453
1454 void
1455 trim_localdomain(char *host)
1456 {
1457 size_t hl;
1458
1459 hl = strlen(host);
1460 if (hl > 0 && host[hl - 1] == '.')
1461 host[--hl] = '\0';
1462
1463 if (hl > LocalDomainLen && host[hl - LocalDomainLen - 1] == '.' &&
1464 strcasecmp(&host[hl - LocalDomainLen], LocalDomain) == 0)
1465 host[hl - LocalDomainLen - 1] = '\0';
1466 }
1467
1468 void
1469 domark(struct kevent *ev)
1470 {
1471 struct filed *f;
1472 dq_t q, nextq;
1473
1474 /*
1475 * XXX Should we bother to adjust for the # of times the timer
1476 * has expired (i.e. in case we miss one?). This information is
1477 * returned to us in ev->data.
1478 */
1479
1480 now = time((time_t *)NULL);
1481 MarkSeq += TIMERINTVL;
1482 if (MarkSeq >= MarkInterval) {
1483 logmsg(LOG_INFO, "-- MARK --", LocalHostName, ADDDATE|MARK);
1484 MarkSeq = 0;
1485 }
1486
1487 for (f = Files; f; f = f->f_next) {
1488 if (f->f_prevcount && now >= REPEATTIME(f)) {
1489 dprintf("Flush %s: repeated %d times, %d sec.\n",
1490 TypeNames[f->f_type], f->f_prevcount,
1491 repeatinterval[f->f_repeatcount]);
1492 fprintlog(f, 0, (char *)NULL);
1493 BACKOFF(f);
1494 }
1495 }
1496
1497 /* Walk the dead queue, and see if we should signal somebody. */
1498 for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = nextq) {
1499 nextq = TAILQ_NEXT(q, dq_entries);
1500 switch (q->dq_timeout) {
1501 case 0:
1502 /* Already signalled once, try harder now. */
1503 if (kill(q->dq_pid, SIGKILL) != 0)
1504 (void) deadq_remove(q->dq_pid);
1505 break;
1506
1507 case 1:
1508 /*
1509 * Timed out on the dead queue, send terminate
1510 * signal. Note that we leave the removal from
1511 * the dead queue to reapchild(), which will
1512 * also log the event (unless the process
1513 * didn't even really exist, in case we simply
1514 * drop it from the dead queue).
1515 */
1516 if (kill(q->dq_pid, SIGTERM) != 0) {
1517 (void) deadq_remove(q->dq_pid);
1518 break;
1519 }
1520 /* FALLTHROUGH */
1521
1522 default:
1523 q->dq_timeout--;
1524 }
1525 }
1526 }
1527
1528 /*
1529 * Print syslogd errors some place.
1530 */
1531 void
1532 logerror(const char *fmt, ...)
1533 {
1534 static int logerror_running;
1535 va_list ap;
1536 char tmpbuf[BUFSIZ];
1537 char buf[BUFSIZ];
1538
1539 /* If there's an error while trying to log an error, give up. */
1540 if (logerror_running)
1541 return;
1542 logerror_running = 1;
1543
1544 va_start(ap, fmt);
1545
1546 (void)vsnprintf(tmpbuf, sizeof(tmpbuf), fmt, ap);
1547
1548 va_end(ap);
1549
1550 if (errno)
1551 (void)snprintf(buf, sizeof(buf), "syslogd: %s: %s",
1552 tmpbuf, strerror(errno));
1553 else
1554 (void)snprintf(buf, sizeof(buf), "syslogd: %s", tmpbuf);
1555
1556 if (daemonized)
1557 logmsg(LOG_SYSLOG|LOG_ERR, buf, LocalHostName, ADDDATE);
1558 if (!daemonized && Debug)
1559 dprintf("%s\n", buf);
1560 if (!daemonized && !Debug)
1561 printf("%s\n", buf);
1562
1563 logerror_running = 0;
1564 }
1565
1566 void
1567 die(struct kevent *ev)
1568 {
1569 struct filed *f;
1570 char **p;
1571
1572 ShuttingDown = 1; /* Don't log SIGCHLDs. */
1573 for (f = Files; f != NULL; f = f->f_next) {
1574 /* flush any pending output */
1575 if (f->f_prevcount)
1576 fprintlog(f, 0, (char *)NULL);
1577 if (f->f_type == F_PIPE && f->f_un.f_pipe.f_pid > 0) {
1578 (void) close(f->f_file);
1579 f->f_un.f_pipe.f_pid = 0;
1580 }
1581 }
1582 errno = 0;
1583 if (ev != NULL)
1584 logerror("Exiting on signal %d", (int) ev->ident);
1585 else
1586 logerror("Fatal error, exiting");
1587 for (p = LogPaths; p && *p; p++)
1588 unlink(*p);
1589 exit(0);
1590 }
1591
1592 /*
1593 * INIT -- Initialize syslogd from configuration table
1594 */
1595 void
1596 init(struct kevent *ev)
1597 {
1598 int i;
1599 FILE *cf;
1600 struct filed *f, *next, **nextp;
1601 char *p;
1602 char cline[LINE_MAX];
1603 char prog[NAME_MAX + 1];
1604 char host[MAXHOSTNAMELEN];
1605 char hostMsg[2*MAXHOSTNAMELEN + 40];
1606
1607 dprintf("init\n");
1608
1609 (void)strlcpy(oldLocalHostName, LocalHostName,
1610 sizeof(oldLocalHostName));
1611 (void)gethostname(LocalHostName, sizeof(LocalHostName));
1612 if ((p = strchr(LocalHostName, '.')) != NULL) {
1613 *p++ = '\0';
1614 LocalDomain = p;
1615 } else
1616 LocalDomain = "";
1617 LocalDomainLen = strlen(LocalDomain);
1618
1619 /*
1620 * Close all open log files.
1621 */
1622 Initialized = 0;
1623 for (f = Files; f != NULL; f = next) {
1624 /* flush any pending output */
1625 if (f->f_prevcount)
1626 fprintlog(f, 0, (char *)NULL);
1627
1628 switch (f->f_type) {
1629 case F_FILE:
1630 case F_TTY:
1631 case F_CONSOLE:
1632 (void)close(f->f_file);
1633 break;
1634 case F_PIPE:
1635 if (f->f_un.f_pipe.f_pid > 0) {
1636 (void)close(f->f_file);
1637 deadq_enter(f->f_un.f_pipe.f_pid,
1638 f->f_un.f_pipe.f_pname);
1639 }
1640 f->f_un.f_pipe.f_pid = 0;
1641 break;
1642 case F_FORW:
1643 if (f->f_un.f_forw.f_addr)
1644 freeaddrinfo(f->f_un.f_forw.f_addr);
1645 break;
1646 }
1647 next = f->f_next;
1648 if (f->f_program != NULL)
1649 free(f->f_program);
1650 if (f->f_host != NULL)
1651 free(f->f_host);
1652 free((char *)f);
1653 }
1654 Files = NULL;
1655 nextp = &Files;
1656
1657 /*
1658 * Close all open sockets
1659 */
1660
1661 if (finet) {
1662 for (i = 0; i < *finet; i++) {
1663 if (close(finet[i+1]) < 0) {
1664 logerror("close() failed");
1665 die(NULL);
1666 }
1667 }
1668 }
1669
1670 /*
1671 * Reset counter of forwarding actions
1672 */
1673
1674 NumForwards=0;
1675
1676 /* open the configuration file */
1677 if ((cf = fopen(ConfFile, "r")) == NULL) {
1678 dprintf("Cannot open `%s'\n", ConfFile);
1679 *nextp = (struct filed *)calloc(1, sizeof(*f));
1680 cfline("*.ERR\t/dev/console", *nextp, "*", "*");
1681 (*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
1682 cfline("*.PANIC\t*", (*nextp)->f_next, "*", "*");
1683 Initialized = 1;
1684 return;
1685 }
1686
1687 /*
1688 * Foreach line in the conf table, open that file.
1689 */
1690 f = NULL;
1691 strcpy(prog, "*");
1692 strcpy(host, "*");
1693 while (fgets(cline, sizeof(cline), cf) != NULL) {
1694 /*
1695 * check for end-of-section, comments, strip off trailing
1696 * spaces and newline character. #!prog is treated specially:
1697 * following lines apply only to that program.
1698 */
1699 for (p = cline; isspace((unsigned char)*p); ++p)
1700 continue;
1701 if (*p == '\0')
1702 continue;
1703 if (*p == '#') {
1704 p++;
1705 if (*p != '!' && *p != '+' && *p != '-')
1706 continue;
1707 }
1708 if (*p == '+' || *p == '-') {
1709 host[0] = *p++;
1710 while (isspace((unsigned char)*p))
1711 p++;
1712 if (*p == '\0' || *p == '*') {
1713 strcpy(host, "*");
1714 continue;
1715 }
1716 if (*p == '@')
1717 p = LocalHostName;
1718 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
1719 if (!isalnum((unsigned char)*p) &&
1720 *p != '.' && *p != '-' && *p != ',')
1721 break;
1722 host[i] = *p++;
1723 }
1724 host[i] = '\0';
1725 continue;
1726 }
1727 if (*p == '!') {
1728 p++;
1729 while (isspace((unsigned char)*p))
1730 p++;
1731 if (*p == '\0' || *p == '*') {
1732 strcpy(prog, "*");
1733 continue;
1734 }
1735 for (i = 0; i < NAME_MAX; i++) {
1736 if (!isprint((unsigned char)p[i]))
1737 break;
1738 prog[i] = p[i];
1739 }
1740 prog[i] = '\0';
1741 continue;
1742 }
1743 for (p = strchr(cline, '\0'); isspace((unsigned char)*--p);)
1744 continue;
1745 *++p = '\0';
1746 f = (struct filed *)calloc(1, sizeof(*f));
1747 *nextp = f;
1748 nextp = &f->f_next;
1749 cfline(cline, f, prog, host);
1750 }
1751
1752 /* close the configuration file */
1753 (void)fclose(cf);
1754
1755 Initialized = 1;
1756
1757 if (Debug) {
1758 for (f = Files; f; f = f->f_next) {
1759 for (i = 0; i <= LOG_NFACILITIES; i++)
1760 if (f->f_pmask[i] == INTERNAL_NOPRI)
1761 printf("X ");
1762 else
1763 printf("%d ", f->f_pmask[i]);
1764 printf("%s: ", TypeNames[f->f_type]);
1765 switch (f->f_type) {
1766 case F_FILE:
1767 case F_TTY:
1768 case F_CONSOLE:
1769 printf("%s", f->f_un.f_fname);
1770 break;
1771
1772 case F_FORW:
1773 printf("%s", f->f_un.f_forw.f_hname);
1774 break;
1775
1776 case F_PIPE:
1777 printf("%s", f->f_un.f_pipe.f_pname);
1778 break;
1779
1780 case F_USERS:
1781 for (i = 0;
1782 i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
1783 printf("%s, ", f->f_un.f_uname[i]);
1784 break;
1785 }
1786 if (f->f_program != NULL)
1787 printf(" (%s)", f->f_program);
1788 printf("\n");
1789 }
1790 }
1791
1792 finet = socksetup(PF_UNSPEC, bindhostname);
1793 if (finet) {
1794 if (SecureMode) {
1795 for (i = 0; i < *finet; i++) {
1796 if (shutdown(finet[i+1], SHUT_RD) < 0) {
1797 logerror("shutdown() failed");
1798 die(NULL);
1799 }
1800 }
1801 } else
1802 dprintf("Listening on inet and/or inet6 socket\n");
1803 dprintf("Sending on inet and/or inet6 socket\n");
1804 }
1805
1806 logmsg(LOG_SYSLOG|LOG_INFO, "syslogd: restart", LocalHostName, ADDDATE);
1807 dprintf("syslogd: restarted\n");
1808 /*
1809 * Log a change in hostname, but only on a restart (we detect this
1810 * by checking to see if we're passed a kevent).
1811 */
1812 if (ev != NULL && strcmp(oldLocalHostName, LocalHostName) != 0) {
1813 (void)snprintf(hostMsg, sizeof(hostMsg),
1814 "syslogd: host name changed, \"%s\" to \"%s\"",
1815 oldLocalHostName, LocalHostName);
1816 logmsg(LOG_SYSLOG|LOG_INFO, hostMsg, LocalHostName, ADDDATE);
1817 dprintf("%s\n", hostMsg);
1818 }
1819 }
1820
1821 /*
1822 * Crack a configuration file line
1823 */
1824 void
1825 cfline(char *line, struct filed *f, char *prog, char *host)
1826 {
1827 struct addrinfo hints, *res;
1828 int error, i, pri, syncfile;
1829 char *bp, *p, *q;
1830 char buf[MAXLINE];
1831
1832 dprintf("cfline(\"%s\", f, \"%s\", \"%s\")\n", line, prog, host);
1833
1834 errno = 0; /* keep strerror() stuff out of logerror messages */
1835
1836 /* clear out file entry */
1837 memset(f, 0, sizeof(*f));
1838 for (i = 0; i <= LOG_NFACILITIES; i++)
1839 f->f_pmask[i] = INTERNAL_NOPRI;
1840
1841 /*
1842 * There should not be any space before the log facility.
1843 * Check this is okay, complain and fix if it is not.
1844 */
1845 q = line;
1846 if (isblank((unsigned char)*line)) {
1847 errno = 0;
1848 logerror(
1849 "Warning: `%s' space or tab before the log facility",
1850 line);
1851 /* Fix: strip all spaces/tabs before the log facility */
1852 while (*q++ && isblank((unsigned char)*q))
1853 /* skip blanks */;
1854 line = q;
1855 }
1856
1857 /*
1858 * q is now at the first char of the log facility
1859 * There should be at least one tab after the log facility
1860 * Check this is okay, and complain and fix if it is not.
1861 */
1862 q = line + strlen(line);
1863 while (!isblank((unsigned char)*q) && (q != line))
1864 q--;
1865 if ((q == line) && strlen(line)) {
1866 /* No tabs or space in a non empty line: complain */
1867 errno = 0;
1868 logerror(
1869 "Error: `%s' log facility or log target missing",
1870 line);
1871 return;
1872 }
1873
1874 /* save host name, if any */
1875 if (*host == '*')
1876 f->f_host = NULL;
1877 else {
1878 f->f_host = strdup(host);
1879 trim_localdomain(f->f_host);
1880 }
1881
1882 /* save program name, if any */
1883 if (*prog == '*')
1884 f->f_program = NULL;
1885 else
1886 f->f_program = strdup(prog);
1887
1888 /* scan through the list of selectors */
1889 for (p = line; *p && !isblank((unsigned char)*p);) {
1890 int pri_done, pri_cmp, pri_invert;
1891
1892 /* find the end of this facility name list */
1893 for (q = p; *q && !isblank((unsigned char)*q) && *q++ != '.'; )
1894 continue;
1895
1896 /* get the priority comparison */
1897 pri_cmp = 0;
1898 pri_done = 0;
1899 pri_invert = 0;
1900 if (*q == '!') {
1901 pri_invert = 1;
1902 q++;
1903 }
1904 while (! pri_done) {
1905 switch (*q) {
1906 case '<':
1907 pri_cmp = PRI_LT;
1908 q++;
1909 break;
1910 case '=':
1911 pri_cmp = PRI_EQ;
1912 q++;
1913 break;
1914 case '>':
1915 pri_cmp = PRI_GT;
1916 q++;
1917 break;
1918 default:
1919 pri_done = 1;
1920 break;
1921 }
1922 }
1923
1924 /* collect priority name */
1925 for (bp = buf; *q && !strchr("\t ,;", *q); )
1926 *bp++ = *q++;
1927 *bp = '\0';
1928
1929 /* skip cruft */
1930 while (strchr(",;", *q))
1931 q++;
1932
1933 /* decode priority name */
1934 if (*buf == '*') {
1935 pri = LOG_PRIMASK + 1;
1936 pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
1937 } else {
1938 pri = decode(buf, prioritynames);
1939 if (pri < 0) {
1940 errno = 0;
1941 logerror("Unknown priority name `%s'", buf);
1942 return;
1943 }
1944 }
1945 if (pri_cmp == 0)
1946 pri_cmp = UniquePriority ? PRI_EQ
1947 : PRI_EQ | PRI_GT;
1948 if (pri_invert)
1949 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
1950
1951 /* scan facilities */
1952 while (*p && !strchr("\t .;", *p)) {
1953 for (bp = buf; *p && !strchr("\t ,;.", *p); )
1954 *bp++ = *p++;
1955 *bp = '\0';
1956 if (*buf == '*')
1957 for (i = 0; i < LOG_NFACILITIES; i++) {
1958 f->f_pmask[i] = pri;
1959 f->f_pcmp[i] = pri_cmp;
1960 }
1961 else {
1962 i = decode(buf, facilitynames);
1963 if (i < 0) {
1964 errno = 0;
1965 logerror("Unknown facility name `%s'",
1966 buf);
1967 return;
1968 }
1969 f->f_pmask[i >> 3] = pri;
1970 f->f_pcmp[i >> 3] = pri_cmp;
1971 }
1972 while (*p == ',' || *p == ' ')
1973 p++;
1974 }
1975
1976 p = q;
1977 }
1978
1979 /* skip to action part */
1980 while (isblank((unsigned char)*p))
1981 p++;
1982
1983 if (*p == '-') {
1984 syncfile = 0;
1985 p++;
1986 } else
1987 syncfile = 1;
1988
1989 switch (*p) {
1990 case '@':
1991 (void)strlcpy(f->f_un.f_forw.f_hname, ++p,
1992 sizeof(f->f_un.f_forw.f_hname));
1993 memset(&hints, 0, sizeof(hints));
1994 hints.ai_family = AF_UNSPEC;
1995 hints.ai_socktype = SOCK_DGRAM;
1996 hints.ai_protocol = 0;
1997 error = getaddrinfo(f->f_un.f_forw.f_hname, "syslog", &hints,
1998 &res);
1999 if (error) {
2000 logerror(gai_strerror(error));
2001 break;
2002 }
2003 f->f_un.f_forw.f_addr = res;
2004 f->f_type = F_FORW;
2005 NumForwards++;
2006 break;
2007
2008 case '/':
2009 (void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
2010 if ((f->f_file = open(p, O_WRONLY|O_APPEND, 0)) < 0) {
2011 f->f_type = F_UNUSED;
2012 logerror(p);
2013 break;
2014 }
2015 if (syncfile)
2016 f->f_flags |= FFLAG_SYNC;
2017 if (isatty(f->f_file))
2018 f->f_type = F_TTY;
2019 else
2020 f->f_type = F_FILE;
2021 if (strcmp(p, ctty) == 0)
2022 f->f_type = F_CONSOLE;
2023 break;
2024
2025 case '|':
2026 f->f_un.f_pipe.f_pid = 0;
2027 (void) strlcpy(f->f_un.f_pipe.f_pname, p + 1,
2028 sizeof(f->f_un.f_pipe.f_pname));
2029 f->f_type = F_PIPE;
2030 break;
2031
2032 case '*':
2033 f->f_type = F_WALL;
2034 break;
2035
2036 default:
2037 for (i = 0; i < MAXUNAMES && *p; i++) {
2038 for (q = p; *q && *q != ','; )
2039 q++;
2040 (void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
2041 if ((q - p) > UT_NAMESIZE)
2042 f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
2043 else
2044 f->f_un.f_uname[i][q - p] = '\0';
2045 while (*q == ',' || *q == ' ')
2046 q++;
2047 p = q;
2048 }
2049 f->f_type = F_USERS;
2050 break;
2051 }
2052 }
2053
2054
2055 /*
2056 * Decode a symbolic name to a numeric value
2057 */
2058 int
2059 decode(const char *name, CODE *codetab)
2060 {
2061 CODE *c;
2062 char *p, buf[40];
2063
2064 if (isdigit((unsigned char)*name))
2065 return (atoi(name));
2066
2067 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
2068 if (isupper((unsigned char)*name))
2069 *p = tolower((unsigned char)*name);
2070 else
2071 *p = *name;
2072 }
2073 *p = '\0';
2074 for (c = codetab; c->c_name; c++)
2075 if (!strcmp(buf, c->c_name))
2076 return (c->c_val);
2077
2078 return (-1);
2079 }
2080
2081 /*
2082 * Retrieve the size of the kernel message buffer, via sysctl.
2083 */
2084 int
2085 getmsgbufsize(void)
2086 {
2087 int msgbufsize, mib[2];
2088 size_t size;
2089
2090 mib[0] = CTL_KERN;
2091 mib[1] = KERN_MSGBUFSIZE;
2092 size = sizeof msgbufsize;
2093 if (sysctl(mib, 2, &msgbufsize, &size, NULL, 0) == -1) {
2094 dprintf("Couldn't get kern.msgbufsize\n");
2095 return (0);
2096 }
2097 return (msgbufsize);
2098 }
2099
2100 int *
2101 socksetup(int af, const char *hostname)
2102 {
2103 struct addrinfo hints, *res, *r;
2104 struct kevent *ev;
2105 int error, maxs, *s, *socks;
2106 const int on = 1;
2107
2108 if(SecureMode && !NumForwards)
2109 return(NULL);
2110
2111 memset(&hints, 0, sizeof(hints));
2112 hints.ai_flags = AI_PASSIVE;
2113 hints.ai_family = af;
2114 hints.ai_socktype = SOCK_DGRAM;
2115 error = getaddrinfo(hostname, "syslog", &hints, &res);
2116 if (error) {
2117 logerror(gai_strerror(error));
2118 errno = 0;
2119 die(NULL);
2120 }
2121
2122 /* Count max number of sockets we may open */
2123 for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
2124 continue;
2125 socks = malloc((maxs+1) * sizeof(int));
2126 if (!socks) {
2127 logerror("Couldn't allocate memory for sockets");
2128 die(NULL);
2129 }
2130
2131 *socks = 0; /* num of sockets counter at start of array */
2132 s = socks + 1;
2133 for (r = res; r; r = r->ai_next) {
2134 *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
2135 if (*s < 0) {
2136 logerror("socket() failed");
2137 continue;
2138 }
2139 if (r->ai_family == AF_INET6 && setsockopt(*s, IPPROTO_IPV6,
2140 IPV6_V6ONLY, &on, sizeof(on)) < 0) {
2141 logerror("setsockopt(IPV6_V6ONLY) failed");
2142 close(*s);
2143 continue;
2144 }
2145
2146 if (!SecureMode) {
2147 if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) {
2148 logerror("bind() failed");
2149 close(*s);
2150 continue;
2151 }
2152 ev = allocevchange();
2153 EV_SET(ev, *s, EVFILT_READ, EV_ADD | EV_ENABLE,
2154 0, 0, (intptr_t) dispatch_read_finet);
2155 }
2156
2157 *socks = *socks + 1;
2158 s++;
2159 }
2160
2161 if (*socks == 0) {
2162 free (socks);
2163 if(Debug)
2164 return(NULL);
2165 else
2166 die(NULL);
2167 }
2168 if (res)
2169 freeaddrinfo(res);
2170
2171 return(socks);
2172 }
2173
2174 /*
2175 * Fairly similar to popen(3), but returns an open descriptor, as opposed
2176 * to a FILE *.
2177 */
2178 int
2179 p_open(char *prog, pid_t *rpid)
2180 {
2181 int pfd[2], nulldesc, i;
2182 pid_t pid;
2183 char *argv[4]; /* sh -c cmd NULL */
2184 char errmsg[200];
2185
2186 if (pipe(pfd) == -1)
2187 return (-1);
2188 if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1) {
2189 /* We are royally screwed anyway. */
2190 return (-1);
2191 }
2192
2193 switch ((pid = fork())) {
2194 case -1:
2195 (void) close(nulldesc);
2196 return (-1);
2197
2198 case 0:
2199 argv[0] = "sh";
2200 argv[1] = "-c";
2201 argv[2] = prog;
2202 argv[3] = NULL;
2203
2204 (void) setsid(); /* avoid catching SIGHUPs. */
2205
2206 /*
2207 * Reset ignored signals to their default behavior.
2208 */
2209 (void)signal(SIGTERM, SIG_DFL);
2210 (void)signal(SIGINT, SIG_DFL);
2211 (void)signal(SIGQUIT, SIG_DFL);
2212 (void)signal(SIGPIPE, SIG_DFL);
2213 (void)signal(SIGHUP, SIG_DFL);
2214
2215 dup2(pfd[0], STDIN_FILENO);
2216 dup2(nulldesc, STDOUT_FILENO);
2217 dup2(nulldesc, STDERR_FILENO);
2218 for (i = getdtablesize(); i > 2; i--)
2219 (void) close(i);
2220
2221 (void) execvp(_PATH_BSHELL, argv);
2222 _exit(255);
2223 }
2224
2225 (void) close(nulldesc);
2226 (void) close(pfd[0]);
2227
2228 /*
2229 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
2230 * supposed to get an EWOULDBLOCK on writev(2), which is
2231 * caught by the logic above anyway, which will in turn
2232 * close the pipe, and fork a new logging subprocess if
2233 * necessary. The stale subprocess will be killed some
2234 * time later unless it terminated itself due to closing
2235 * its input pipe.
2236 */
2237 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
2238 /* This is bad. */
2239 (void) snprintf(errmsg, sizeof(errmsg),
2240 "Warning: cannot change pipe to pid %d to "
2241 "non-blocking.", (int) pid);
2242 logerror(errmsg);
2243 }
2244 *rpid = pid;
2245 return (pfd[1]);
2246 }
2247
2248 void
2249 deadq_enter(pid_t pid, const char *name)
2250 {
2251 dq_t p;
2252 int status;
2253
2254 /*
2255 * Be paranoid: if we can't signal the process, don't enter it
2256 * into the dead queue (perhaps it's already dead). If possible,
2257 * we try to fetch and log the child's status.
2258 */
2259 if (kill(pid, 0) != 0) {
2260 if (waitpid(pid, &status, WNOHANG) > 0)
2261 log_deadchild(pid, status, name);
2262 return;
2263 }
2264
2265 p = malloc(sizeof(*p));
2266 if (p == NULL) {
2267 errno = 0;
2268 logerror("panic: out of memory!");
2269 exit(1);
2270 }
2271
2272 p->dq_pid = pid;
2273 p->dq_timeout = DQ_TIMO_INIT;
2274 TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
2275 }
2276
2277 int
2278 deadq_remove(pid_t pid)
2279 {
2280 dq_t q;
2281
2282 for (q = TAILQ_FIRST(&deadq_head); q != NULL;
2283 q = TAILQ_NEXT(q, dq_entries)) {
2284 if (q->dq_pid == pid) {
2285 TAILQ_REMOVE(&deadq_head, q, dq_entries);
2286 free(q);
2287 return (1);
2288 }
2289 }
2290 return (0);
2291 }
2292
2293 void
2294 log_deadchild(pid_t pid, int status, const char *name)
2295 {
2296 int code;
2297 char buf[256];
2298 const char *reason;
2299
2300 /* Keep strerror() struff out of logerror messages. */
2301 errno = 0;
2302 if (WIFSIGNALED(status)) {
2303 reason = "due to signal";
2304 code = WTERMSIG(status);
2305 } else {
2306 reason = "with status";
2307 code = WEXITSTATUS(status);
2308 if (code == 0)
2309 return;
2310 }
2311 (void) snprintf(buf, sizeof(buf),
2312 "Logging subprocess %d (%s) exited %s %d.",
2313 pid, name, reason, code);
2314 logerror(buf);
2315 }
2316
2317 static struct kevent changebuf[8];
2318 static int nchanges;
2319
2320 static struct kevent *
2321 allocevchange(void)
2322 {
2323
2324 if (nchanges == A_CNT(changebuf)) {
2325 /* XXX Error handling could be improved. */
2326 (void) wait_for_events(NULL, 0);
2327 }
2328
2329 return (&changebuf[nchanges++]);
2330 }
2331
2332 static int
2333 wait_for_events(struct kevent *events, size_t nevents)
2334 {
2335 int rv;
2336
2337 rv = kevent(fkq, nchanges ? changebuf : NULL, nchanges,
2338 events, nevents, NULL);
2339 nchanges = 0;
2340 return (rv);
2341 }
2342