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