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