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