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