syslogd.c revision 1.89 1 /* $NetBSD: syslogd.c,v 1.89 2008/11/03 22:59:51 christos Exp $ */
2
3 /*
4 * Copyright (c) 1983, 1988, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32 #include <sys/cdefs.h>
33 #ifndef lint
34 __COPYRIGHT("@(#) Copyright (c) 1983, 1988, 1993, 1994\
35 The Regents of the University of California. All rights reserved.");
36 #endif /* not lint */
37
38 #ifndef lint
39 #if 0
40 static char sccsid[] = "@(#)syslogd.c 8.3 (Berkeley) 4/4/94";
41 #else
42 __RCSID("$NetBSD: syslogd.c,v 1.89 2008/11/03 22:59:51 christos Exp $");
43 #endif
44 #endif /* not lint */
45
46 /*
47 * syslogd -- log system messages
48 *
49 * This program implements a system log. It takes a series of lines.
50 * Each line may have a priority, signified as "<n>" as
51 * the first characters of the line. If this is
52 * not present, a default priority is used.
53 *
54 * To kill syslogd, send a signal 15 (terminate). A signal 1 (hup) will
55 * cause it to reread its configuration file.
56 *
57 * Defined Constants:
58 *
59 * MAXLINE -- the maximimum line length that can be handled.
60 * DEFUPRI -- the default priority for user messages
61 * DEFSPRI -- the default priority for kernel messages
62 *
63 * Author: Eric Allman
64 * extensive changes by Ralph Campbell
65 * more extensive changes by Eric Allman (again)
66 * Extension to log by program name as well as facility and priority
67 * by Peter da Silva.
68 * -U and -v by Harlan Stenn.
69 * Priority comparison code by Harlan Stenn.
70 * TLS, syslog-protocol, and syslog-sign code by Martin Schuette.
71 */
72 #define SYSLOG_NAMES
73 #include "syslogd.h"
74 #include "extern.h"
75
76 #ifndef DISABLE_SIGN
77 #include "sign.h"
78 struct sign_global_t GlobalSign = {
79 .rsid = 0,
80 .sig2_delims = STAILQ_HEAD_INITIALIZER(GlobalSign.sig2_delims)
81 };
82 #endif /* !DISABLE_SIGN */
83
84 #ifndef DISABLE_TLS
85 #include "tls.h"
86 #endif /* !DISABLE_TLS */
87
88 #ifdef LIBWRAP
89 int allow_severity = LOG_AUTH|LOG_INFO;
90 int deny_severity = LOG_AUTH|LOG_WARNING;
91 #endif
92
93 const char *ConfFile = _PATH_LOGCONF;
94 char ctty[] = _PATH_CONSOLE;
95
96 /*
97 * Queue of about-to-be-dead processes we should watch out for.
98 */
99 TAILQ_HEAD(, deadq_entry) deadq_head = TAILQ_HEAD_INITIALIZER(deadq_head);
100
101 typedef struct deadq_entry {
102 pid_t dq_pid;
103 int dq_timeout;
104 TAILQ_ENTRY(deadq_entry) dq_entries;
105 } *dq_t;
106
107 /*
108 * The timeout to apply to processes waiting on the dead queue. Unit
109 * of measure is "mark intervals", i.e. 20 minutes by default.
110 * Processes on the dead queue will be terminated after that time.
111 */
112 #define DQ_TIMO_INIT 2
113
114 /*
115 * Intervals at which we flush out "message repeated" messages,
116 * in seconds after previous message is logged. After each flush,
117 * we move to the next interval until we reach the largest.
118 */
119 int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */
120 #define MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1)
121 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount])
122 #define BACKOFF(f) { if (++(f)->f_repeatcount > MAXREPEAT) \
123 (f)->f_repeatcount = MAXREPEAT; \
124 }
125
126 /* values for f_type */
127 #define F_UNUSED 0 /* unused entry */
128 #define F_FILE 1 /* regular file */
129 #define F_TTY 2 /* terminal */
130 #define F_CONSOLE 3 /* console terminal */
131 #define F_FORW 4 /* remote machine */
132 #define F_USERS 5 /* list of users */
133 #define F_WALL 6 /* everyone logged on */
134 #define F_PIPE 7 /* pipe to program */
135 #define F_TLS 8
136
137 struct TypeInfo {
138 const char *name;
139 char *queue_length_string;
140 const char *default_length_string;
141 char *queue_size_string;
142 const char *default_size_string;
143 int64_t queue_length;
144 int64_t queue_size;
145 int max_msg_length;
146 } TypeInfo[] = {
147 /* numeric values are set in init()
148 * -1 in length/size or max_msg_length means infinite */
149 {"UNUSED", NULL, "0", NULL, "0", 0, 0, 0},
150 {"FILE", NULL, "1024", NULL, "1M", 0, 0, 16384},
151 {"TTY", NULL, "0", NULL, "0", 0, 0, 1024},
152 {"CONSOLE", NULL, "0", NULL, "0", 0, 0, 1024},
153 {"FORW", NULL, "0", NULL, "1M", 0, 0, 16384},
154 {"USERS", NULL, "0", NULL, "0", 0, 0, 1024},
155 {"WALL", NULL, "0", NULL, "0", 0, 0, 1024},
156 {"PIPE", NULL, "1024", NULL, "1M", 0, 0, 16384},
157 #ifndef DISABLE_TLS
158 {"TLS", NULL, "-1", NULL, "16M", 0, 0, 16384}
159 #endif /* !DISABLE_TLS */
160 };
161
162 struct filed *Files = NULL;
163 struct filed consfile;
164
165 time_t now;
166 int Debug = D_NONE; /* debug flag */
167 int daemonized = 0; /* we are not daemonized yet */
168 char *LocalFQDN = NULL; /* our FQDN */
169 char *oldLocalFQDN = NULL; /* our previous FQDN */
170 char LocalHostName[MAXHOSTNAMELEN]; /* our hostname */
171 struct socketEvent *finet; /* Internet datagram sockets and events */
172 int *funix; /* Unix domain datagram sockets */
173 #ifndef DISABLE_TLS
174 struct socketEvent *TLS_Listen_Set; /* TLS/TCP sockets and events */
175 #endif /* !DISABLE_TLS */
176 int Initialized = 0; /* set when we have initialized ourselves */
177 int ShuttingDown; /* set when we die() */
178 int MarkInterval = 20 * 60; /* interval between marks in seconds */
179 int MarkSeq = 0; /* mark sequence number */
180 int SecureMode = 0; /* listen only on unix domain socks */
181 int UseNameService = 1; /* make domain name queries */
182 int NumForwards = 0; /* number of forwarding actions in conf file */
183 char **LogPaths; /* array of pathnames to read messages from */
184 int NoRepeat = 0; /* disable "repeated"; log always */
185 int RemoteAddDate = 0; /* always add date to messages from network */
186 int SyncKernel = 0; /* write kernel messages synchronously */
187 int UniquePriority = 0; /* only log specified priority */
188 int LogFacPri = 0; /* put facility and priority in log messages: */
189 /* 0=no, 1=numeric, 2=names */
190 bool BSDOutputFormat = true; /* if true emit traditional BSD Syslog lines,
191 * otherwise new syslog-protocol lines
192 *
193 * Open Issue: having a global flag is the
194 * easiest solution. If we get a more detailed
195 * config file this could/should be changed
196 * into a destination-specific flag.
197 * Most output code should be ready to handle
198 * this, it will only break some syslog-sign
199 * configurations (e.g. with SG="0").
200 */
201 char appname[] = "syslogd";/* the APPNAME for own messages */
202 char *include_pid = NULL; /* include PID in own messages */
203
204
205 /* init and setup */
206 void usage(void) __attribute__((__noreturn__));
207 void logpath_add(char ***, int *, int *, const char *);
208 void logpath_fileadd(char ***, int *, int *, const char *);
209 void init(int fd, short event, void *ev); /* SIGHUP kevent dispatch routine */
210 struct socketEvent*
211 socksetup(int, const char *);
212 int getmsgbufsize(void);
213 char *getLocalFQDN(void);
214 void trim_anydomain(char *);
215 /* pipe & subprocess handling */
216 int p_open(char *, pid_t *);
217 void deadq_enter(pid_t, const char *);
218 int deadq_remove(pid_t);
219 void log_deadchild(pid_t, int, const char *);
220 void reapchild(int fd, short event, void *ev); /* SIGCHLD kevent dispatch routine */
221 /* input message parsing & formatting */
222 const char *cvthname(struct sockaddr_storage *);
223 void printsys(char *);
224 struct buf_msg *printline_syslogprotocol(const char*, char*, int, int);
225 struct buf_msg *printline_bsdsyslog(const char*, char*, int, int);
226 struct buf_msg *printline_kernelprintf(const char*, char*, int, int);
227 size_t check_timestamp(unsigned char *, char **, bool, bool);
228 char *copy_utf8_ascii(char*, size_t);
229 uint_fast32_t get_utf8_value(const char*);
230 unsigned valid_utf8(const char *);
231 static unsigned check_sd(char*);
232 static unsigned check_msgid(char *);
233 /* event handling */
234 static void dispatch_read_klog(int fd, short event, void *ev);
235 static void dispatch_read_finet(int fd, short event, void *ev);
236 static void dispatch_read_funix(int fd, short event, void *ev);
237 static void domark(int fd, short event, void *ev); /* timer kevent dispatch routine */
238 /* log messages */
239 void logmsg_async(int, const char *, const char *, int);
240 void logmsg(struct buf_msg *);
241 int matches_spec(const char *, const char *,
242 char *(*)(const char *, const char *));
243 void udp_send(struct filed *, char *, size_t);
244 void wallmsg(struct filed *, struct iovec *, size_t);
245 /* buffer & queue functions */
246 size_t message_queue_purge(struct filed *f, size_t, int);
247 size_t message_allqueues_check(void);
248 static struct buf_queue *
249 find_qentry_to_delete(const struct buf_queue_head *, int, bool);
250 struct buf_queue *
251 message_queue_add(struct filed *, struct buf_msg *);
252 size_t buf_queue_obj_size(struct buf_queue*);
253 /* configuration & parsing */
254 void cfline(size_t, const char *, struct filed *, const char *,
255 const char *);
256 void read_config_file(FILE*, struct filed**);
257 void store_sign_delim_sg2(char*);
258 int decode(const char *, CODE *);
259 bool copy_config_value(const char *, char **, const char **,
260 const char *, int);
261 bool copy_config_value_word(char **, const char **);
262
263 /* config parsing */
264 #ifndef DISABLE_TLS
265 void free_cred_SLIST(struct peer_cred_head *);
266 static inline void
267 free_incoming_tls_sockets(void);
268 #endif /* !DISABLE_TLS */
269
270 /* for make_timestamp() */
271 #define TIMESTAMPBUFSIZE 35
272 char timestamp[TIMESTAMPBUFSIZE];
273
274 /*
275 * Global line buffer. Since we only process one event at a time,
276 * a global one will do.
277 */
278 char *linebuf;
279 size_t linebufsize;
280
281 static const char *bindhostname = NULL;
282
283 #ifndef DISABLE_TLS
284 struct TLS_Incoming TLS_Incoming_Head = \
285 SLIST_HEAD_INITIALIZER(TLS_Incoming_Head);
286 extern char *SSL_ERRCODE[];
287 struct tls_global_options_t tls_opt;
288 #endif /* !DISABLE_TLS */
289
290 int
291 main(int argc, char *argv[])
292 {
293 int ch, j, fklog;
294 int funixsize = 0, funixmaxsize = 0;
295 struct sockaddr_un sunx;
296 char **pp;
297 struct event *ev;
298 uid_t uid = 0;
299 gid_t gid = 0;
300 char *user = NULL;
301 char *group = NULL;
302 const char *root = "/";
303 char *endp;
304 struct group *gr;
305 struct passwd *pw;
306 unsigned long l;
307
308 /* should we set LC_TIME="C" to ensure correct timestamps&parsing? */
309 (void)setlocale(LC_ALL, "");
310
311 while ((ch = getopt(argc, argv, "b:dnsSf:m:o:p:P:ru:g:t:TUv")) != -1)
312 switch(ch) {
313 case 'b':
314 bindhostname = optarg;
315 break;
316 case 'd': /* debug */
317 Debug = D_DEFAULT;
318 /* is there a way to read the integer value
319 * for Debug as an optional argument? */
320 break;
321 case 'f': /* configuration file */
322 ConfFile = optarg;
323 break;
324 case 'g':
325 group = optarg;
326 if (*group == '\0')
327 usage();
328 break;
329 case 'm': /* mark interval */
330 MarkInterval = atoi(optarg) * 60;
331 break;
332 case 'n': /* turn off DNS queries */
333 UseNameService = 0;
334 break;
335 case 'o': /* message format */
336 if (!strncmp(optarg, "rfc3164", sizeof("rfc3164")-1))
337 BSDOutputFormat = true;
338 else if (!strncmp(optarg, "syslog", sizeof("syslog")-1))
339 BSDOutputFormat = false;
340 else
341 usage();
342 /* TODO: implement additional output option "osyslog"
343 * for old syslogd behaviour as introduced after
344 * FreeBSD PR#bin/7055.
345 */
346 break;
347 case 'p': /* path */
348 logpath_add(&LogPaths, &funixsize,
349 &funixmaxsize, optarg);
350 break;
351 case 'P': /* file of paths */
352 logpath_fileadd(&LogPaths, &funixsize,
353 &funixmaxsize, optarg);
354 break;
355 case 'r': /* disable "repeated" compression */
356 NoRepeat++;
357 break;
358 case 's': /* no network listen mode */
359 SecureMode++;
360 break;
361 case 'S':
362 SyncKernel = 1;
363 break;
364 case 't':
365 root = optarg;
366 if (*root == '\0')
367 usage();
368 break;
369 case 'T':
370 RemoteAddDate = 1;
371 break;
372 case 'u':
373 user = optarg;
374 if (*user == '\0')
375 usage();
376 break;
377 case 'U': /* only log specified priority */
378 UniquePriority = 1;
379 break;
380 case 'v': /* log facility and priority */
381 if (LogFacPri < 2)
382 LogFacPri++;
383 break;
384 default:
385 usage();
386 }
387 if ((argc -= optind) != 0)
388 usage();
389
390 setlinebuf(stdout);
391
392 if (user != NULL) {
393 if (isdigit((unsigned char)*user)) {
394 errno = 0;
395 endp = NULL;
396 l = strtoul(user, &endp, 0);
397 if (errno || *endp != '\0')
398 goto getuser;
399 uid = (uid_t)l;
400 if (uid != l) {/* TODO: never executed */
401 errno = 0;
402 logerror("UID out of range");
403 die(0, 0, NULL);
404 }
405 } else {
406 getuser:
407 if ((pw = getpwnam(user)) != NULL) {
408 uid = pw->pw_uid;
409 } else {
410 errno = 0;
411 logerror("Cannot find user `%s'", user);
412 die(0, 0, NULL);
413 }
414 }
415 }
416
417 if (group != NULL) {
418 if (isdigit((unsigned char)*group)) {
419 errno = 0;
420 endp = NULL;
421 l = strtoul(group, &endp, 0);
422 if (errno || *endp != '\0')
423 goto getgroup;
424 gid = (gid_t)l;
425 if (gid != l) {/* TODO: never executed */
426 errno = 0;
427 logerror("GID out of range");
428 die(0, 0, NULL);
429 }
430 } else {
431 getgroup:
432 if ((gr = getgrnam(group)) != NULL) {
433 gid = gr->gr_gid;
434 } else {
435 errno = 0;
436 logerror("Cannot find group `%s'", group);
437 die(0, 0, NULL);
438 }
439 }
440 }
441
442 if (access(root, F_OK | R_OK)) {
443 logerror("Cannot access `%s'", root);
444 die(0, 0, NULL);
445 }
446
447 consfile.f_type = F_CONSOLE;
448 (void)strlcpy(consfile.f_un.f_fname, ctty,
449 sizeof(consfile.f_un.f_fname));
450 linebufsize = getmsgbufsize();
451 if (linebufsize < MAXLINE)
452 linebufsize = MAXLINE;
453 linebufsize++;
454
455 if (!(linebuf = malloc(linebufsize))) {
456 logerror("Couldn't allocate buffer");
457 die(0, 0, NULL);
458 }
459
460 #ifndef SUN_LEN
461 #define SUN_LEN(unp) (strlen((unp)->sun_path) + 2)
462 #endif
463 if (funixsize == 0)
464 logpath_add(&LogPaths, &funixsize,
465 &funixmaxsize, _PATH_LOG);
466 funix = (int *)malloc(sizeof(int) * funixsize);
467 if (funix == NULL) {
468 logerror("Couldn't allocate funix descriptors");
469 die(0, 0, NULL);
470 }
471 for (j = 0, pp = LogPaths; *pp; pp++, j++) {
472 DPRINTF(D_NET, "Making unix dgram socket `%s'\n", *pp);
473 unlink(*pp);
474 memset(&sunx, 0, sizeof(sunx));
475 sunx.sun_family = AF_LOCAL;
476 (void)strncpy(sunx.sun_path, *pp, sizeof(sunx.sun_path));
477 funix[j] = socket(AF_LOCAL, SOCK_DGRAM, 0);
478 if (funix[j] < 0 || bind(funix[j],
479 (struct sockaddr *)&sunx, SUN_LEN(&sunx)) < 0 ||
480 chmod(*pp, 0666) < 0) {
481 logerror("Cannot create `%s'", *pp);
482 die(0, 0, NULL);
483 }
484 DPRINTF(D_NET, "Listening on unix dgram socket `%s'\n", *pp);
485 }
486
487 if ((fklog = open(_PATH_KLOG, O_RDONLY, 0)) < 0) {
488 DPRINTF(D_FILE, "Can't open `%s' (%d)\n", _PATH_KLOG, errno);
489 } else {
490 DPRINTF(D_FILE, "Listening on kernel log `%s' with fd %d\n",
491 _PATH_KLOG, fklog);
492 }
493
494 #if (!defined(DISABLE_TLS) && !defined(DISABLE_SIGN))
495 /* basic OpenSSL init */
496 SSL_load_error_strings();
497 (void) SSL_library_init();
498 OpenSSL_add_all_digests();
499 /* OpenSSL PRNG needs /dev/urandom, thus initialize before chroot() */
500 if (!RAND_status())
501 logerror("Unable to initialize OpenSSL PRNG");
502 else {
503 DPRINTF(D_TLS, "Initializing PRNG\n");
504 }
505 #endif /* (!defined(DISABLE_TLS) && !defined(DISABLE_SIGN)) */
506 #ifndef DISABLE_SIGN
507 /* initialize rsid -- we will use that later to determine
508 * whether sign_global_init() was already called */
509 GlobalSign.rsid = 0;
510 #endif /* !DISABLE_SIGN */
511 #if (IETF_NUM_PRIVALUES != (LOG_NFACILITIES<<3))
512 logerror("Warning: system defines %d priority values, but "
513 "syslog-protocol/syslog-sign specify %d values",
514 LOG_NFACILITIES, SIGN_NUM_PRIVALS);
515 #endif
516
517 /*
518 * All files are open, we can drop privileges and chroot
519 */
520 DPRINTF(D_MISC, "Attempt to chroot to `%s'\n", root);
521 if (chroot(root)) {
522 logerror("Failed to chroot to `%s'", root);
523 die(0, 0, NULL);
524 }
525 DPRINTF(D_MISC, "Attempt to set GID/EGID to `%d'\n", gid);
526 if (setgid(gid) || setegid(gid)) {
527 logerror("Failed to set gid to `%d'", gid);
528 die(0, 0, NULL);
529 }
530 DPRINTF(D_MISC, "Attempt to set UID/EUID to `%d'\n", uid);
531 if (setuid(uid) || seteuid(uid)) {
532 logerror("Failed to set uid to `%d'", uid);
533 die(0, 0, NULL);
534 }
535 /*
536 * We cannot detach from the terminal before we are sure we won't
537 * have a fatal error, because error message would not go to the
538 * terminal and would not be logged because syslogd dies.
539 * All die() calls are behind us, we can call daemon()
540 */
541 if (!Debug) {
542 (void)daemon(0, 0);
543 daemonized = 1;
544 /* tuck my process id away, if i'm not in debug mode */
545 #ifdef __NetBSD_Version__
546 pidfile(NULL);
547 #endif /* __NetBSD_Version__ */
548 }
549
550 #define MAX_PID_LEN 5
551 include_pid = malloc(MAX_PID_LEN+1);
552 snprintf(include_pid, MAX_PID_LEN+1, "%d", getpid());
553
554 /*
555 * Create the global kernel event descriptor.
556 *
557 * NOTE: We MUST do this after daemon(), bacause the kqueue()
558 * API dictates that kqueue descriptors are not inherited
559 * across forks (lame!).
560 */
561 (void)event_init();
562
563 /*
564 * We must read the configuration file for the first time
565 * after the kqueue descriptor is created, because we install
566 * events during this process.
567 */
568 init(0, 0, NULL);
569
570 /*
571 * Always exit on SIGTERM. Also exit on SIGINT and SIGQUIT
572 * if we're debugging.
573 */
574 (void)signal(SIGTERM, SIG_IGN);
575 (void)signal(SIGINT, SIG_IGN);
576 (void)signal(SIGQUIT, SIG_IGN);
577
578 ev = allocev();
579 signal_set(ev, SIGTERM, die, ev);
580 EVENT_ADD(ev);
581
582 if (Debug) {
583 ev = allocev();
584 signal_set(ev, SIGINT, die, ev);
585 EVENT_ADD(ev);
586 ev = allocev();
587 signal_set(ev, SIGQUIT, die, ev);
588 EVENT_ADD(ev);
589 }
590
591 ev = allocev();
592 signal_set(ev, SIGCHLD, reapchild, ev);
593 EVENT_ADD(ev);
594
595 ev = allocev();
596 schedule_event(&ev,
597 &((struct timeval){TIMERINTVL, 0}),
598 domark, ev);
599
600 (void)signal(SIGPIPE, SIG_IGN); /* We'll catch EPIPE instead. */
601
602 /* Re-read configuration on SIGHUP. */
603 (void) signal(SIGHUP, SIG_IGN);
604 ev = allocev();
605 signal_set(ev, SIGHUP, init, ev);
606 EVENT_ADD(ev);
607
608 #ifndef DISABLE_TLS
609 ev = allocev();
610 signal_set(ev, SIGUSR1, dispatch_force_tls_reconnect, ev);
611 EVENT_ADD(ev);
612 #endif /* !DISABLE_TLS */
613
614 if (fklog >= 0) {
615 ev = allocev();
616 DPRINTF(D_EVENT,
617 "register klog for fd %d with ev@%p\n", fklog, ev);
618 event_set(ev, fklog, EV_READ | EV_PERSIST,
619 dispatch_read_klog, ev);
620 EVENT_ADD(ev);
621 }
622 for (j = 0, pp = LogPaths; *pp; pp++, j++) {
623 ev = allocev();
624 event_set(ev, funix[j], EV_READ | EV_PERSIST,
625 dispatch_read_funix, ev);
626 EVENT_ADD(ev);
627 }
628
629 DPRINTF(D_MISC, "Off & running....\n");
630
631 j = event_dispatch();
632 /* normal termination via die(), reaching this is an error */
633 DPRINTF(D_MISC, "event_dispatch() returned %d\n", j);
634 die(0, 0, NULL);
635 /*NOTREACHED*/
636 return 0;
637 }
638
639 void
640 usage(void)
641 {
642
643 (void)fprintf(stderr,
644 "usage: %s [-dnrSsTUv] [-b bind_address] [-f config_file] [-g group]\n"
645 "\t[-m mark_interval] [-P file_list] [-p log_socket\n"
646 "\t[-p log_socket2 ...]] [-t chroot_dir] [-u user]\n",
647 getprogname());
648 exit(1);
649 }
650
651 /*
652 * Dispatch routine for reading /dev/klog
653 *
654 * Note: slightly different semantic in dispatch_read functions:
655 * - read_klog() might give multiple messages in linebuf and
656 * leaves the task of splitting them to printsys()
657 * - all other read functions receive one message and
658 * then call printline() with one buffer.
659 */
660 static void
661 dispatch_read_klog(int fd, short event, void *ev)
662 {
663 ssize_t rv;
664
665 DPRINTF((D_CALL|D_EVENT), "Kernel log active (%d, %d, %p)"
666 " with linebuf@%p, length %zu)\n", fd, event, ev,
667 linebuf, linebufsize);
668
669 rv = read(fd, linebuf, linebufsize - 1);
670 if (rv > 0) {
671 linebuf[rv] = '\0';
672 printsys(linebuf);
673 } else if (rv < 0 && errno != EINTR) {
674 /*
675 * /dev/klog has croaked. Disable the event
676 * so it won't bother us again.
677 */
678 logerror("klog failed");
679 event_del(ev);
680 }
681 }
682
683 /*
684 * Dispatch routine for reading Unix domain sockets.
685 */
686 static void
687 dispatch_read_funix(int fd, short event, void *ev)
688 {
689 struct sockaddr_un myname, fromunix;
690 ssize_t rv;
691 socklen_t sunlen;
692
693 sunlen = sizeof(myname);
694 if (getsockname(fd, (struct sockaddr *)&myname, &sunlen) != 0) {
695 /*
696 * This should never happen, so ensure that it doesn't
697 * happen again.
698 */
699 logerror("getsockname() unix failed");
700 event_del(ev);
701 return;
702 }
703
704 DPRINTF((D_CALL|D_EVENT|D_NET), "Unix socket (%.*s) active (%d, %d %p)"
705 " with linebuf@%p, size %zu)\n", (int)(myname.sun_len
706 - sizeof(myname.sun_len) - sizeof(myname.sun_family)),
707 myname.sun_path, fd, event, ev, linebuf, linebufsize-1);
708
709 sunlen = sizeof(fromunix);
710 rv = recvfrom(fd, linebuf, linebufsize-1, 0,
711 (struct sockaddr *)&fromunix, &sunlen);
712 if (rv > 0) {
713 linebuf[rv] = '\0';
714 printline(LocalFQDN, linebuf, 0);
715 } else if (rv < 0 && errno != EINTR) {
716 logerror("recvfrom() unix `%.*s'",
717 myname.sun_len, myname.sun_path);
718 }
719 }
720
721 /*
722 * Dispatch routine for reading Internet sockets.
723 */
724 static void
725 dispatch_read_finet(int fd, short event, void *ev)
726 {
727 #ifdef LIBWRAP
728 struct request_info req;
729 #endif
730 struct sockaddr_storage frominet;
731 ssize_t rv;
732 socklen_t len;
733 int reject = 0;
734
735 DPRINTF((D_CALL|D_EVENT|D_NET), "inet socket active (%d, %d %p) "
736 " with linebuf@%p, size %zu)\n",
737 fd, event, ev, linebuf, linebufsize-1);
738
739 #ifdef LIBWRAP
740 request_init(&req, RQ_DAEMON, appname, RQ_FILE, fd, NULL);
741 fromhost(&req);
742 reject = !hosts_access(&req);
743 if (reject)
744 DPRINTF(D_NET, "access denied\n");
745 #endif
746
747 len = sizeof(frominet);
748 rv = recvfrom(fd, linebuf, linebufsize-1, 0,
749 (struct sockaddr *)&frominet, &len);
750 if (rv == 0 || (rv < 0 && errno == EINTR))
751 return;
752 else if (rv < 0) {
753 logerror("recvfrom inet");
754 return;
755 }
756
757 linebuf[rv] = '\0';
758 if (!reject)
759 printline(cvthname(&frominet), linebuf,
760 RemoteAddDate ? ADDDATE : 0);
761 }
762
763 /*
764 * given a pointer to an array of char *'s, a pointer to its current
765 * size and current allocated max size, and a new char * to add, add
766 * it, update everything as necessary, possibly allocating a new array
767 */
768 void
769 logpath_add(char ***lp, int *szp, int *maxszp, const char *new)
770 {
771 char **nlp;
772 int newmaxsz;
773
774 DPRINTF(D_FILE, "Adding `%s' to the %p logpath list\n", new, *lp);
775 if (*szp == *maxszp) {
776 if (*maxszp == 0) {
777 newmaxsz = 4; /* start of with enough for now */
778 *lp = NULL;
779 } else
780 newmaxsz = *maxszp * 2;
781 nlp = realloc(*lp, sizeof(char *) * (newmaxsz + 1));
782 if (nlp == NULL) {
783 logerror("Couldn't allocate line buffer");
784 die(0, 0, NULL);
785 }
786 *lp = nlp;
787 *maxszp = newmaxsz;
788 }
789 if (((*lp)[(*szp)++] = strdup(new)) == NULL) {
790 logerror("Couldn't allocate logpath");
791 die(0, 0, NULL);
792 }
793 (*lp)[(*szp)] = NULL; /* always keep it NULL terminated */
794 }
795
796 /* do a file of log sockets */
797 void
798 logpath_fileadd(char ***lp, int *szp, int *maxszp, const char *file)
799 {
800 FILE *fp;
801 char *line;
802 size_t len;
803
804 fp = fopen(file, "r");
805 if (fp == NULL) {
806 logerror("Could not open socket file list `%s'", file);
807 die(0, 0, NULL);
808 }
809
810 while ((line = fgetln(fp, &len)) != NULL) {
811 line[len - 1] = 0;
812 logpath_add(lp, szp, maxszp, line);
813 }
814 fclose(fp);
815 }
816
817 /*
818 * checks UTF-8 codepoint
819 * returns either its length in bytes or 0 if *input is invalid
820 */
821 unsigned
822 valid_utf8(const char *c) {
823 unsigned rc, nb;
824
825 /* first byte gives sequence length */
826 if ((*c & 0x80) == 0x00) return 1; /* 0bbbbbbb -- ASCII */
827 else if ((*c & 0xc0) == 0x80) return 0; /* 10bbbbbb -- trailing byte */
828 else if ((*c & 0xe0) == 0xc0) nb = 2; /* 110bbbbb */
829 else if ((*c & 0xf0) == 0xe0) nb = 3; /* 1110bbbb */
830 else if ((*c & 0xf8) == 0xf0) nb = 4; /* 11110bbb */
831 else return 0; /* UTF-8 allows only up to 4 bytes */
832
833 /* catch overlong encodings */
834 if ((*c & 0xfe) == 0xc0)
835 return 0; /* 1100000b ... */
836 else if (((*c & 0xff) == 0xe0) && ((*(c+1) & 0xe0) == 0x80))
837 return 0; /* 11100000 100bbbbb ... */
838 else if (((*c & 0xff) == 0xf0) && ((*(c+1) & 0xf0) == 0x80))
839 return 0; /* 11110000 1000bbbb ... ... */
840
841 /* and also filter UTF-16 surrogates (=invalid in UTF-8) */
842 if (((*c & 0xff) == 0xed) && ((*(c+1) & 0xe0) == 0xa0))
843 return 0; /* 11101101 101bbbbb ... */
844
845 rc = nb;
846 /* check trailing bytes */
847 switch (nb) {
848 default: return 0;
849 case 4: if ((*(c+3) & 0xc0) != 0x80) return 0; /*FALLTHROUGH*/
850 case 3: if ((*(c+2) & 0xc0) != 0x80) return 0; /*FALLTHROUGH*/
851 case 2: if ((*(c+1) & 0xc0) != 0x80) return 0; /*FALLTHROUGH*/
852 }
853 return rc;
854 }
855 #define UTF8CHARMAX 4
856
857 /*
858 * read UTF-8 value
859 * returns a the codepoint number
860 */
861 uint_fast32_t
862 get_utf8_value(const char *c) {
863 uint_fast32_t sum;
864 unsigned nb, i;
865
866 /* first byte gives sequence length */
867 if ((*c & 0x80) == 0x00) return *c;/* 0bbbbbbb -- ASCII */
868 else if ((*c & 0xc0) == 0x80) return 0; /* 10bbbbbb -- trailing byte */
869 else if ((*c & 0xe0) == 0xc0) { /* 110bbbbb */
870 nb = 2;
871 sum = (*c & ~0xe0) & 0xff;
872 } else if ((*c & 0xf0) == 0xe0) { /* 1110bbbb */
873 nb = 3;
874 sum = (*c & ~0xf0) & 0xff;
875 } else if ((*c & 0xf8) == 0xf0) { /* 11110bbb */
876 nb = 4;
877 sum = (*c & ~0xf8) & 0xff;
878 } else return 0; /* UTF-8 allows only up to 4 bytes */
879
880 /* check trailing bytes -- 10bbbbbb */
881 i = 1;
882 while (i < nb) {
883 sum <<= 6;
884 sum |= ((*(c+i) & ~0xc0) & 0xff);
885 i++;
886 }
887 return sum;
888 }
889
890 /* note previous versions transscribe
891 * control characters, e.g. \007 --> "^G"
892 * did anyone rely on that?
893 *
894 * this new version works on only one buffer and
895 * replaces control characters with a space
896 */
897 #define NEXTFIELD(ptr) if (*(p) == ' ') (p)++; /* SP */ \
898 else { \
899 DPRINTF(D_DATA, "format error\n"); \
900 if (*(p) == '\0') start = (p); \
901 goto all_syslog_msg; \
902 }
903 #define FORCE2ASCII(c) ((iscntrl((unsigned char)(c)) && (c) != '\t') \
904 ? ((c) == '\n' ? ' ' : '?') \
905 : (c) & 0177)
906
907 /* following syslog-protocol */
908 #define printusascii(ch) (ch >= 33 && ch <= 126)
909 #define sdname(ch) (ch != '=' && ch != ' ' \
910 && ch != ']' && ch != '"' \
911 && printusascii(ch))
912
913 /* checks whether the first word of string p can be interpreted as
914 * a syslog-protocol MSGID and if so returns its length.
915 *
916 * otherwise returns 0
917 */
918 static unsigned
919 check_msgid(char *p)
920 {
921 char *q = p;
922
923 /* consider the NILVALUE to be valid */
924 if (*q == '-' && *(q+1) == ' ')
925 return 1;
926
927 for (;;) {
928 if (*q == ' ')
929 return q - p;
930 else if (*q == '\0' || !printusascii(*q) || q - p >= MSGID_MAX)
931 return 0;
932 else
933 q++;
934 }
935 }
936
937 /*
938 * returns number of chars found in SD at beginning of string p
939 * thus returns 0 if no valid SD is found
940 *
941 * if ascii == true then substitute all non-ASCII chars
942 * otherwise use syslog-protocol rules to allow UTF-8 in values
943 * note: one pass for filtering and scanning, so a found SD
944 * is always filtered, but an invalid one could be partially
945 * filtered up to the format error.
946 */
947 static unsigned
948 check_sd(char* p)
949 {
950 char *q = p;
951 bool esc = false;
952
953 /* consider the NILVALUE to be valid */
954 if (*q == '-' && (*(q+1) == ' ' || *(q+1) == '\0'))
955 return 1;
956
957 for(;;) { /* SD-ELEMENT */
958 if (*q++ != '[') return 0;
959 /* SD-ID */
960 if (!sdname(*q)) return 0;
961 while (sdname(*q)) {
962 *q = FORCE2ASCII(*q);
963 q++;
964 }
965 for(;;) { /* SD-PARAM */
966 if (*q == ']') {
967 q++;
968 if (*q == ' ' || *q == '\0') return q - p;
969 else if (*q == '[') break;
970 } else if (*q++ != ' ') return 0;
971
972 /* PARAM-NAME */
973 if (!sdname(*q)) return 0;
974 while (sdname(*q)) {
975 *q = FORCE2ASCII(*q);
976 q++;
977 }
978
979 if (*q++ != '=') return 0;
980 if (*q++ != '"') return 0;
981
982 for(;;) { /* PARAM-VALUE */
983 if (esc) {
984 esc = false;
985 if (*q == '\\' || *q == '"' ||
986 *q == ']') {
987 q++;
988 continue;
989 }
990 /* no else because invalid
991 * escape sequences are accepted */
992 }
993 else if (*q == '"') break;
994 else if (*q == '\0' || *q == ']') return 0;
995 else if (*q == '\\') esc = true;
996 else {
997 int i;
998 i = valid_utf8(q);
999 if (i == 0)
1000 *q = '?';
1001 else if (i == 1)
1002 *q = FORCE2ASCII(*q);
1003 else /* multi byte char */
1004 q += (i-1);
1005 }
1006 q++;
1007 }
1008 q++;
1009 }
1010 }
1011 }
1012
1013 struct buf_msg *
1014 printline_syslogprotocol(const char *hname, char *msg,
1015 int flags, int pri)
1016 {
1017 struct buf_msg *buffer;
1018 char *p, *start;
1019 unsigned sdlen = 0, i = 0;
1020 bool utf8allowed = false; /* for some fields */
1021
1022 DPRINTF((D_CALL|D_BUFFER|D_DATA), "printline_syslogprotocol("
1023 "\"%s\", \"%s\", %d, %d)\n", hname, msg, flags, pri);
1024
1025 buffer = buf_msg_new(0);
1026 p = msg;
1027 start = p += check_timestamp((unsigned char*) p,
1028 &buffer->timestamp, true, !BSDOutputFormat);
1029 DPRINTF(D_DATA, "Got timestamp \"%s\"\n", buffer->timestamp);
1030
1031 NEXTFIELD(p);
1032 /* extract host */
1033 for (start = p;; p++) {
1034 if ((*p == ' ' || *p == '\0')
1035 && start == p-1 && *(p-1) == '-') {
1036 /* NILVALUE */
1037 break;
1038 } else if ((*p == ' ' || *p == '\0')
1039 && (start != p-1 || *(p-1) != '-')) {
1040 buffer->host = strndup(start, p - start);
1041 break;
1042 } else {
1043 *p = FORCE2ASCII(*p);
1044 }
1045 }
1046 /* p @ SP after host */
1047 DPRINTF(D_DATA, "Got host \"%s\"\n", buffer->host);
1048
1049 /* extract app-name */
1050 NEXTFIELD(p);
1051 for (start = p;; p++) {
1052 if ((*p == ' ' || *p == '\0')
1053 && start == p-1 && *(p-1) == '-') {
1054 /* NILVALUE */
1055 break;
1056 } else if ((*p == ' ' || *p == '\0')
1057 && (start != p-1 || *(p-1) != '-')) {
1058 buffer->prog = strndup(start, p - start);
1059 break;
1060 } else {
1061 *p = FORCE2ASCII(*p);
1062 }
1063 }
1064 DPRINTF(D_DATA, "Got prog \"%s\"\n", buffer->prog);
1065
1066 /* extract procid */
1067 NEXTFIELD(p);
1068 for (start = p;; p++) {
1069 if ((*p == ' ' || *p == '\0')
1070 && start == p-1 && *(p-1) == '-') {
1071 /* NILVALUE */
1072 break;
1073 } else if ((*p == ' ' || *p == '\0')
1074 && (start != p-1 || *(p-1) != '-')) {
1075 buffer->pid = strndup(start, p - start);
1076 start = p;
1077 break;
1078 } else {
1079 *p = FORCE2ASCII(*p);
1080 }
1081 }
1082 DPRINTF(D_DATA, "Got pid \"%s\"\n", buffer->pid);
1083
1084 /* extract msgid */
1085 NEXTFIELD(p);
1086 for (start = p;; p++) {
1087 if ((*p == ' ' || *p == '\0')
1088 && start == p-1 && *(p-1) == '-') {
1089 /* NILVALUE */
1090 start = p+1;
1091 break;
1092 } else if ((*p == ' ' || *p == '\0')
1093 && (start != p-1 || *(p-1) != '-')) {
1094 buffer->msgid = strndup(start, p - start);
1095 start = p+1;
1096 break;
1097 } else {
1098 *p = FORCE2ASCII(*p);
1099 }
1100 }
1101 DPRINTF(D_DATA, "Got msgid \"%s\"\n", buffer->msgid);
1102
1103 /* extract SD */
1104 NEXTFIELD(p);
1105 start = p;
1106 sdlen = check_sd(p);
1107 DPRINTF(D_DATA, "check_sd(\"%s\") returned %d\n", p, sdlen);
1108
1109 if (sdlen == 1 && *p == '-') {
1110 /* NILVALUE */
1111 p++;
1112 } else if (sdlen > 1) {
1113 buffer->sd = strndup(p, sdlen);
1114 p += sdlen;
1115 } else {
1116 DPRINTF(D_DATA, "format error\n");
1117 }
1118 if (*p == '\0') start = p;
1119 else if (*p == ' ') start = ++p; /* SP */
1120 DPRINTF(D_DATA, "Got SD \"%s\"\n", buffer->sd);
1121
1122 /* and now the message itself
1123 * note: move back to last start to check for BOM
1124 */
1125 all_syslog_msg:
1126 p = start;
1127
1128 /* check for UTF-8-BOM */
1129 if (IS_BOM(p)) {
1130 DPRINTF(D_DATA, "UTF-8 BOM\n");
1131 utf8allowed = true;
1132 p += 3;
1133 }
1134
1135 if (*p != '\0' && !utf8allowed) {
1136 size_t msglen;
1137
1138 msglen = strlen(p);
1139 assert(!buffer->msg);
1140 buffer->msg = copy_utf8_ascii(p, msglen);
1141 buffer->msgorig = buffer->msg;
1142 buffer->msglen = buffer->msgsize = strlen(buffer->msg)+1;
1143 } else if (*p != '\0' && utf8allowed) {
1144 while (*p != '\0') {
1145 i = valid_utf8(p);
1146 if (i == 0)
1147 *p++ = '?';
1148 else if (i == 1)
1149 *p = FORCE2ASCII(*p);
1150 p += i;
1151 }
1152 assert(p != start);
1153 assert(!buffer->msg);
1154 buffer->msg = strndup(start, p - start);
1155 buffer->msgorig = buffer->msg;
1156 buffer->msglen = buffer->msgsize = 1 + p - start;
1157 }
1158 DPRINTF(D_DATA, "Got msg \"%s\"\n", buffer->msg);
1159
1160 buffer->recvhost = strdup(hname);
1161 buffer->pri = pri;
1162 buffer->flags = flags;
1163
1164 return buffer;
1165 }
1166
1167 /* copies an input into a new ASCII buffer
1168 * ASCII controls are converted to format "^X"
1169 * multi-byte UTF-8 chars are converted to format "<ab><cd>"
1170 */
1171 #define INIT_BUFSIZE 512
1172 char *
1173 copy_utf8_ascii(char *p, size_t p_len)
1174 {
1175 size_t idst = 0, isrc = 0, dstsize = INIT_BUFSIZE, i;
1176 char *dst, *tmp_dst;
1177
1178 MALLOC(dst, dstsize);
1179 while (isrc < p_len) {
1180 if (dstsize < idst + 10) {
1181 /* check for enough space for \0 and a UTF-8
1182 * conversion; longest possible is <U+123456> */
1183 tmp_dst = realloc(dst, dstsize + INIT_BUFSIZE);
1184 if (!tmp_dst)
1185 break;
1186 dst = tmp_dst;
1187 dstsize += INIT_BUFSIZE;
1188 }
1189
1190 i = valid_utf8(&p[isrc]);
1191 if (i == 0) { /* invalid encoding */
1192 dst[idst++] = '?';
1193 isrc++;
1194 } else if (i == 1) { /* check printable */
1195 if (iscntrl((unsigned char)p[isrc])
1196 && p[isrc] != '\t') {
1197 if (p[isrc] == '\n') {
1198 dst[idst++] = ' ';
1199 isrc++;
1200 } else {
1201 dst[idst++] = '^';
1202 dst[idst++] = p[isrc++] ^ 0100;
1203 }
1204 } else
1205 dst[idst++] = p[isrc++];
1206 } else { /* convert UTF-8 to ASCII */
1207 dst[idst++] = '<';
1208 idst += snprintf(&dst[idst], dstsize - idst, "U+%x",
1209 get_utf8_value(&p[isrc]));
1210 isrc += i;
1211 dst[idst++] = '>';
1212 }
1213 }
1214 dst[idst] = '\0';
1215
1216 /* shrink buffer to right size */
1217 tmp_dst = realloc(dst, idst+1);
1218 if (tmp_dst)
1219 return tmp_dst;
1220 else
1221 return dst;
1222 }
1223
1224 struct buf_msg *
1225 printline_bsdsyslog(const char *hname, char *msg,
1226 int flags, int pri)
1227 {
1228 struct buf_msg *buffer;
1229 char *p, *start;
1230 unsigned msgidlen = 0, sdlen = 0;
1231
1232 DPRINTF((D_CALL|D_BUFFER|D_DATA), "printline_bsdsyslog("
1233 "\"%s\", \"%s\", %d, %d)\n", hname, msg, flags, pri);
1234
1235 buffer = buf_msg_new(0);
1236 p = msg;
1237 start = p += check_timestamp((unsigned char*) p,
1238 &buffer->timestamp, false, !BSDOutputFormat);
1239 DPRINTF(D_DATA, "Got timestamp \"%s\"\n", buffer->timestamp);
1240
1241 if (*p == ' ') p++; /* SP */
1242 else goto all_bsd_msg;
1243 /* in any error case we skip header parsing and
1244 * treat all following data as message content */
1245
1246 /* extract host */
1247 for (start = p;; p++) {
1248 if (*p == ' ' || *p == '\0') {
1249 buffer->host = strndup(start, p - start);
1250 break;
1251 } else if (*p == '[' || (*p == ':'
1252 && (*(p+1) == ' ' || *(p+1) == '\0'))) {
1253 /* no host in message */
1254 buffer->host = LocalFQDN;
1255 buffer->prog = strndup(start, p - start);
1256 break;
1257 } else {
1258 *p = FORCE2ASCII(*p);
1259 }
1260 }
1261 DPRINTF(D_DATA, "Got host \"%s\"\n", buffer->host);
1262 /* p @ SP after host, or @ :/[ after prog */
1263
1264 /* extract program */
1265 if (!buffer->prog) {
1266 if (*p == ' ') p++; /* SP */
1267 else goto all_bsd_msg;
1268
1269 for (start = p;; p++) {
1270 if (*p == ' ' || *p == '\0') { /* error */
1271 goto all_bsd_msg;
1272 } else if (*p == '[' || (*p == ':'
1273 && (*(p+1) == ' ' || *(p+1) == '\0'))) {
1274 buffer->prog = strndup(start, p - start);
1275 break;
1276 } else {
1277 *p = FORCE2ASCII(*p);
1278 }
1279 }
1280 }
1281 DPRINTF(D_DATA, "Got prog \"%s\"\n", buffer->prog);
1282 start = p;
1283
1284 /* p @ :/[ after prog */
1285 if (*p == '[') {
1286 p++;
1287 if (*p == ' ') p++; /* SP */
1288 for (start = p;; p++) {
1289 if (*p == ' ' || *p == '\0') { /* error */
1290 goto all_bsd_msg;
1291 } else if (*p == ']') {
1292 buffer->pid = strndup(start, p - start);
1293 break;
1294 } else {
1295 *p = FORCE2ASCII(*p);
1296 }
1297 }
1298 }
1299 DPRINTF(D_DATA, "Got pid \"%s\"\n", buffer->pid);
1300
1301 if (*p == ']') p++;
1302 if (*p == ':') p++;
1303 if (*p == ' ') p++;
1304
1305 /* p @ msgid, @ opening [ of SD or @ first byte of message
1306 * accept either case and try to detect MSGID and SD fields
1307 *
1308 * only limitation: we do not accept UTF-8 data in
1309 * BSD Syslog messages -- so all SD values are ASCII-filtered
1310 *
1311 * I have found one scenario with 'unexpected' behaviour:
1312 * if there is only a SD intended, but a) it is short enough
1313 * to be a MSGID and b) the first word of the message can also
1314 * be parsed as an SD.
1315 * example:
1316 * "<35>Jul 6 12:39:08 tag[123]: [exampleSDID@0] - hello"
1317 * --> parsed as
1318 * MSGID = "[exampleSDID@0]"
1319 * SD = "-"
1320 * MSG = "hello"
1321 */
1322 start = p;
1323 msgidlen = check_msgid(p);
1324 if (msgidlen) /* check for SD in 2nd field */
1325 sdlen = check_sd(p+msgidlen+1);
1326
1327 if (msgidlen && sdlen) {
1328 /* MSGID in 1st and SD in 2nd field
1329 * now check for NILVALUEs and copy */
1330 if (msgidlen == 1 && *p == '-') {
1331 p++; /* - */
1332 p++; /* SP */
1333 DPRINTF(D_DATA, "Got MSGID \"-\"\n");
1334 } else {
1335 /* only has ASCII chars after check_msgid() */
1336 buffer->msgid = strndup(p, msgidlen);
1337 p += msgidlen;
1338 p++; /* SP */
1339 DPRINTF(D_DATA, "Got MSGID \"%s\"\n",
1340 buffer->msgid);
1341 }
1342 } else {
1343 /* either no msgid or no SD in 2nd field
1344 * --> check 1st field for SD */
1345 DPRINTF(D_DATA, "No MSGID\n");
1346 sdlen = check_sd(p);
1347 }
1348
1349 if (sdlen == 0) {
1350 DPRINTF(D_DATA, "No SD\n");
1351 } else if (sdlen > 1) {
1352 buffer->sd = copy_utf8_ascii(p, sdlen);
1353 DPRINTF(D_DATA, "Got SD \"%s\"\n", buffer->sd);
1354 } else if (sdlen == 1 && *p == '-') {
1355 p++;
1356 DPRINTF(D_DATA, "Got SD \"-\"\n");
1357 } else {
1358 DPRINTF(D_DATA, "Error\n");
1359 }
1360
1361 if (*p == ' ') p++;
1362 start = p;
1363 /* and now the message itself
1364 * note: do not reset start, because we might come here
1365 * by goto and want to have the incomplete field as part
1366 * of the msg
1367 */
1368 all_bsd_msg:
1369 if (*p != '\0') {
1370 size_t msglen = strlen(p);
1371 buffer->msg = copy_utf8_ascii(p, msglen);
1372 buffer->msgorig = buffer->msg;
1373 buffer->msglen = buffer->msgsize = strlen(buffer->msg)+1;
1374 }
1375 DPRINTF(D_DATA, "Got msg \"%s\"\n", buffer->msg);
1376
1377 buffer->recvhost = strdup(hname);
1378 buffer->pri = pri;
1379 buffer->flags = flags | BSDSYSLOG;
1380
1381 return buffer;
1382 }
1383
1384 struct buf_msg *
1385 printline_kernelprintf(const char *hname, char *msg,
1386 int flags, int pri)
1387 {
1388 struct buf_msg *buffer;
1389 char *p;
1390 unsigned sdlen = 0;
1391
1392 DPRINTF((D_CALL|D_BUFFER|D_DATA), "printline_kernelprintf("
1393 "\"%s\", \"%s\", %d, %d)\n", hname, msg, flags, pri);
1394
1395 buffer = buf_msg_new(0);
1396 buffer->timestamp = strdup(make_timestamp(NULL, !BSDOutputFormat));
1397 buffer->pri = pri;
1398 buffer->flags = flags;
1399
1400 /* assume there is no MSGID but there might be SD */
1401 p = msg;
1402 sdlen = check_sd(p);
1403
1404 if (sdlen == 0) {
1405 DPRINTF(D_DATA, "No SD\n");
1406 } else if (sdlen > 1) {
1407 buffer->sd = copy_utf8_ascii(p, sdlen);
1408 DPRINTF(D_DATA, "Got SD \"%s\"\n", buffer->sd);
1409 } else if (sdlen == 1 && *p == '-') {
1410 p++;
1411 DPRINTF(D_DATA, "Got SD \"-\"\n");
1412 } else {
1413 DPRINTF(D_DATA, "Error\n");
1414 }
1415
1416 if (*p == ' ') p++;
1417 if (*p != '\0') {
1418 size_t msglen = strlen(p);
1419 buffer->msg = copy_utf8_ascii(p, msglen);
1420 buffer->msgorig = buffer->msg;
1421 buffer->msglen = buffer->msgsize = strlen(buffer->msg)+1;
1422 }
1423 DPRINTF(D_DATA, "Got msg \"%s\"\n", buffer->msg);
1424
1425 return buffer;
1426 }
1427
1428 /*
1429 * Take a raw input line, read priority and version, call the
1430 * right message parsing function, then call logmsg().
1431 */
1432 void
1433 printline(const char *hname, char *msg, int flags)
1434 {
1435 struct buf_msg *buffer;
1436 int pri;
1437 char *p, *q;
1438 long n;
1439 bool bsdsyslog = true;
1440
1441 DPRINTF((D_CALL|D_BUFFER|D_DATA),
1442 "printline(\"%s\", \"%s\", %d)\n", hname, msg, flags);
1443
1444 /* test for special codes */
1445 pri = DEFUPRI;
1446 p = msg;
1447 if (*p == '<') {
1448 errno = 0;
1449 n = strtol(p + 1, &q, 10);
1450 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
1451 p = q + 1;
1452 pri = (int)n;
1453 if (*p == '1') { /* syslog-protocol version */
1454 p += 2; /* skip version and space */
1455 bsdsyslog = false;
1456 } else {
1457 bsdsyslog = true;
1458 }
1459 }
1460 }
1461 if (pri & ~(LOG_FACMASK|LOG_PRIMASK))
1462 pri = DEFUPRI;
1463
1464 /*
1465 * Don't allow users to log kernel messages.
1466 * NOTE: Since LOG_KERN == 0, this will also match
1467 * messages with no facility specified.
1468 */
1469 if ((pri & LOG_FACMASK) == LOG_KERN)
1470 pri = LOG_MAKEPRI(LOG_USER, LOG_PRI(pri));
1471
1472 if (bsdsyslog) {
1473 buffer = printline_bsdsyslog(hname, p, flags, pri);
1474 } else {
1475 buffer = printline_syslogprotocol(hname, p, flags, pri);
1476 }
1477 logmsg(buffer);
1478 DELREF(buffer);
1479 }
1480
1481 /*
1482 * Take a raw input line from /dev/klog, split and format similar to syslog().
1483 */
1484 void
1485 printsys(char *msg)
1486 {
1487 int n, is_printf, pri, flags;
1488 char *p, *q;
1489 struct buf_msg *buffer;
1490
1491 for (p = msg; *p != '\0'; ) {
1492 bool bsdsyslog = true;
1493
1494 is_printf = 1;
1495 flags = ISKERNEL | ADDDATE | BSDSYSLOG;
1496 if (SyncKernel)
1497 flags |= SYNC_FILE;
1498 if (is_printf) /* kernel printf's come out on console */
1499 flags |= IGN_CONS;
1500 pri = DEFSPRI;
1501
1502 if (*p == '<') {
1503 errno = 0;
1504 n = (int)strtol(p + 1, &q, 10);
1505 if (*q == '>' && n >= 0 && n < INT_MAX && errno == 0) {
1506 p = q + 1;
1507 is_printf = 0;
1508 pri = n;
1509 if (*p == '1') { /* syslog-protocol version */
1510 p += 2; /* skip version and space */
1511 bsdsyslog = false;
1512 } else {
1513 bsdsyslog = true;
1514 }
1515 }
1516 }
1517 for (q = p; *q != '\0' && *q != '\n'; q++)
1518 /* look for end of line; no further checks.
1519 * trust the kernel to send ASCII only */;
1520 if (*q != '\0')
1521 *q++ = '\0';
1522
1523 if (pri &~ (LOG_FACMASK|LOG_PRIMASK))
1524 pri = DEFSPRI;
1525
1526 /* allow all kinds of input from kernel */
1527 if (is_printf)
1528 buffer = printline_kernelprintf(
1529 LocalFQDN, p, flags, pri);
1530 else {
1531 if (bsdsyslog)
1532 buffer = printline_bsdsyslog(
1533 LocalFQDN, p, flags, pri);
1534 else
1535 buffer = printline_syslogprotocol(
1536 LocalFQDN, p, flags, pri);
1537 }
1538
1539 /* set fields left open */
1540 if (!buffer->prog)
1541 buffer->prog = strdup(_PATH_UNIX);
1542 if (!buffer->host)
1543 buffer->host = LocalFQDN;
1544 if (!buffer->recvhost)
1545 buffer->recvhost = LocalFQDN;
1546
1547 logmsg(buffer);
1548 DELREF(buffer);
1549 p = q;
1550 }
1551 }
1552
1553 /*
1554 * Check to see if `name' matches the provided specification, using the
1555 * specified strstr function.
1556 */
1557 int
1558 matches_spec(const char *name, const char *spec,
1559 char *(*check)(const char *, const char *))
1560 {
1561 const char *s;
1562 const char *cursor;
1563 char prev, next;
1564 size_t len;
1565
1566 if (name[0] == '\0')
1567 return 0;
1568
1569 if (strchr(name, ',')) /* sanity */
1570 return 0;
1571
1572 len = strlen(name);
1573 cursor = spec;
1574 while ((s = (*check)(cursor, name)) != NULL) {
1575 prev = s == spec ? ',' : *(s - 1);
1576 cursor = s + len;
1577 next = *cursor;
1578
1579 if (prev == ',' && (next == '\0' || next == ','))
1580 return 1;
1581 }
1582
1583 return 0;
1584 }
1585
1586 /*
1587 * wrapper with old function signature,
1588 * keeps calling code shorter and hides buffer allocation
1589 */
1590 void
1591 logmsg_async(int pri, const char *sd, const char *msg, int flags)
1592 {
1593 struct buf_msg *buffer;
1594 size_t msglen;
1595
1596 DPRINTF((D_CALL|D_DATA), "logmsg_async(%d, \"%s\", \"%s\", %d)\n",
1597 pri, sd, msg, flags);
1598
1599 if (msg) {
1600 msglen = strlen(msg);
1601 msglen++; /* adds \0 */
1602 buffer = buf_msg_new(msglen);
1603 buffer->msglen = strlcpy(buffer->msg, msg, msglen) + 1;
1604 } else {
1605 buffer = buf_msg_new(0);
1606 }
1607 if (sd) buffer->sd = strdup(sd);
1608 buffer->timestamp = strdup(make_timestamp(NULL, !BSDOutputFormat));
1609 buffer->prog = appname;
1610 buffer->pid = include_pid;
1611 buffer->recvhost = buffer->host = LocalFQDN;
1612 buffer->pri = pri;
1613 buffer->flags = flags;
1614
1615 logmsg(buffer);
1616 DELREF(buffer);
1617 }
1618
1619 /* read timestamp in from_buf, convert into a timestamp in to_buf
1620 *
1621 * returns length of timestamp found in from_buf (= number of bytes consumed)
1622 */
1623 size_t
1624 check_timestamp(unsigned char *from_buf, char **to_buf,
1625 bool from_iso, bool to_iso)
1626 {
1627 unsigned char *q;
1628 int p;
1629 bool found_ts = false;
1630
1631 DPRINTF((D_CALL|D_DATA), "check_timestamp(%p = \"%s\", from_iso=%d, "
1632 "to_iso=%d)\n", from_buf, from_buf, from_iso, to_iso);
1633
1634 if (!from_buf) return 0;
1635 /*
1636 * Check to see if msg looks non-standard.
1637 * looks at every char because we do not have a msg length yet
1638 */
1639 /* detailed checking adapted from Albert Mietus' sl_timestamp.c */
1640 if (from_iso) {
1641 if (from_buf[4] == '-' && from_buf[7] == '-'
1642 && from_buf[10] == 'T' && from_buf[13] == ':'
1643 && from_buf[16] == ':'
1644 && isdigit(from_buf[0]) && isdigit(from_buf[1])
1645 && isdigit(from_buf[2]) && isdigit(from_buf[3]) /* YYYY */
1646 && isdigit(from_buf[5]) && isdigit(from_buf[6])
1647 && isdigit(from_buf[8]) && isdigit(from_buf[9]) /* mm dd */
1648 && isdigit(from_buf[11]) && isdigit(from_buf[12]) /* HH */
1649 && isdigit(from_buf[14]) && isdigit(from_buf[15]) /* MM */
1650 && isdigit(from_buf[17]) && isdigit(from_buf[18]) /* SS */
1651 ) {
1652 /* time-secfrac */
1653 if (from_buf[19] == '.')
1654 for (p=20; isdigit(from_buf[p]); p++) /* NOP*/;
1655 else
1656 p = 19;
1657 /* time-offset */
1658 if (from_buf[p] == 'Z'
1659 || ((from_buf[p] == '+' || from_buf[p] == '-')
1660 && from_buf[p+3] == ':'
1661 && isdigit(from_buf[p+1]) && isdigit(from_buf[p+2])
1662 && isdigit(from_buf[p+4]) && isdigit(from_buf[p+5])
1663 ))
1664 found_ts = true;
1665 }
1666 } else {
1667 if (from_buf[3] == ' ' && from_buf[6] == ' '
1668 && from_buf[9] == ':' && from_buf[12] == ':'
1669 && (from_buf[4] == ' ' || isdigit(from_buf[4]))
1670 && isdigit(from_buf[5]) /* dd */
1671 && isdigit(from_buf[7]) && isdigit(from_buf[8]) /* HH */
1672 && isdigit(from_buf[10]) && isdigit(from_buf[11]) /* MM */
1673 && isdigit(from_buf[13]) && isdigit(from_buf[14]) /* SS */
1674 && isupper(from_buf[0]) && islower(from_buf[1]) /* month */
1675 && islower(from_buf[2]))
1676 found_ts = true;
1677 }
1678 if (!found_ts && from_buf[0] == '-' && from_buf[1] == ' ') {
1679 /* NILVALUE */
1680 if (to_iso) {
1681 /* with ISO = syslog-protocol output leave
1682 * it as is, because it is better to have
1683 * no timestamp than a wrong one.
1684 */
1685 *to_buf = strdup("-");
1686 } else {
1687 /* with BSD Syslog the field is reqired
1688 * so replace it with current time
1689 */
1690 *to_buf = strdup(make_timestamp(NULL, false));
1691 }
1692 return 2;
1693 }
1694
1695 if (!from_iso && !to_iso) {
1696 /* copy BSD timestamp */
1697 DPRINTF(D_CALL, "check_timestamp(): copy BSD timestamp\n");
1698 *to_buf = strndup((char *)from_buf, BSD_TIMESTAMPLEN);
1699 return BSD_TIMESTAMPLEN;
1700 } else if (from_iso && to_iso) {
1701 /* copy ISO timestamp */
1702 DPRINTF(D_CALL, "check_timestamp(): copy ISO timestamp\n");
1703 if (!(q = (unsigned char *) strchr((char *)from_buf, ' ')))
1704 q = from_buf + strlen((char *)from_buf);
1705 *to_buf = strndup((char *)from_buf, q - from_buf);
1706 return q - from_buf;
1707 } else if (from_iso && !to_iso) {
1708 /* convert ISO->BSD */
1709 struct tm parsed;
1710 time_t timeval;
1711 char tsbuf[MAX_TIMESTAMPLEN];
1712 int i = 0;
1713
1714 DPRINTF(D_CALL, "check_timestamp(): convert ISO->BSD\n");
1715 for(i = 0; i < MAX_TIMESTAMPLEN && from_buf[i] != '\0'
1716 && from_buf[i] != '.' && from_buf[i] != ' '; i++)
1717 tsbuf[i] = from_buf[i]; /* copy date & time */
1718 for(; i < MAX_TIMESTAMPLEN && from_buf[i] != '\0'
1719 && from_buf[i] != '+' && from_buf[i] != '-'
1720 && from_buf[i] != 'Z' && from_buf[i] != ' '; i++)
1721 ; /* skip fraction digits */
1722 for(; i < MAX_TIMESTAMPLEN && from_buf[i] != '\0'
1723 && from_buf[i] != ':' && from_buf[i] != ' ' ; i++)
1724 tsbuf[i] = from_buf[i]; /* copy TZ */
1725 if (from_buf[i] == ':') i++; /* skip colon */
1726 for(; i < MAX_TIMESTAMPLEN && from_buf[i] != '\0'
1727 && from_buf[i] != ' ' ; i++)
1728 tsbuf[i] = from_buf[i]; /* copy TZ */
1729
1730 (void)memset(&parsed, 0, sizeof(parsed));
1731 parsed.tm_isdst = -1;
1732 (void)strptime(tsbuf, "%FT%T%z", &parsed);
1733 timeval = mktime(&parsed);
1734
1735 *to_buf = strndup(make_timestamp(&timeval, false),
1736 BSD_TIMESTAMPLEN);
1737 return i;
1738 } else if (!from_iso && to_iso) {
1739 /* convert BSD->ISO */
1740 struct tm parsed;
1741 struct tm *current;
1742 time_t timeval;
1743 char *rc;
1744
1745 (void)memset(&parsed, 0, sizeof(parsed));
1746 parsed.tm_isdst = -1;
1747 DPRINTF(D_CALL, "check_timestamp(): convert BSD->ISO\n");
1748 rc = strptime((char *)from_buf, "%b %d %T", &parsed);
1749 current = gmtime(&now);
1750
1751 /* use current year and timezone */
1752 parsed.tm_isdst = current->tm_isdst;
1753 parsed.tm_gmtoff = current->tm_gmtoff;
1754 parsed.tm_year = current->tm_year;
1755 if (current->tm_mon == 0 && parsed.tm_mon == 11)
1756 parsed.tm_year--;
1757
1758 timeval = mktime(&parsed);
1759 rc = make_timestamp(&timeval, true);
1760 *to_buf = strndup(rc, MAX_TIMESTAMPLEN-1);
1761
1762 return BSD_TIMESTAMPLEN;
1763 } else {
1764 DPRINTF(D_MISC,
1765 "Executing unreachable code in check_timestamp()\n");
1766 return 0;
1767 }
1768 }
1769
1770 /*
1771 * Log a message to the appropriate log files, users, etc. based on
1772 * the priority.
1773 */
1774 void
1775 logmsg(struct buf_msg *buffer)
1776 {
1777 struct filed *f;
1778 int fac, omask, prilev;
1779
1780 DPRINTF((D_CALL|D_BUFFER), "logmsg: buffer@%p, pri 0%o/%d, flags 0x%x,"
1781 " timestamp \"%s\", from \"%s\", sd \"%s\", msg \"%s\"\n",
1782 buffer, buffer->pri, buffer->pri, buffer->flags,
1783 buffer->timestamp, buffer->recvhost, buffer->sd, buffer->msg);
1784
1785 omask = sigblock(sigmask(SIGHUP)|sigmask(SIGALRM));
1786
1787 /* sanity check */
1788 assert(buffer->refcount == 1);
1789 assert(buffer->msglen <= buffer->msgsize);
1790 assert(buffer->msgorig <= buffer->msg);
1791 assert((buffer->msg && buffer->msglen == strlen(buffer->msg)+1)
1792 || (!buffer->msg && !buffer->msglen));
1793 if (!buffer->msg && !buffer->sd && !buffer->msgid)
1794 DPRINTF(D_BUFFER, "Empty message?\n");
1795
1796 /* extract facility and priority level */
1797 if (buffer->flags & MARK)
1798 fac = LOG_NFACILITIES;
1799 else
1800 fac = LOG_FAC(buffer->pri);
1801 prilev = LOG_PRI(buffer->pri);
1802
1803 /* log the message to the particular outputs */
1804 if (!Initialized) {
1805 f = &consfile;
1806 f->f_file = open(ctty, O_WRONLY, 0);
1807
1808 if (f->f_file >= 0) {
1809 DELREF(f->f_prevmsg);
1810 f->f_prevmsg = NEWREF(buffer);
1811 fprintlog(f, NEWREF(buffer), NULL);
1812 DELREF(buffer);
1813 (void)close(f->f_file);
1814 }
1815 (void)sigsetmask(omask);
1816 return;
1817 }
1818
1819 for (f = Files; f; f = f->f_next) {
1820 /* skip messages that are incorrect priority */
1821 if (!MATCH_PRI(f, fac, prilev)
1822 || f->f_pmask[fac] == INTERNAL_NOPRI)
1823 continue;
1824
1825 /* skip messages with the incorrect host name */
1826 /* do we compare with host (IMHO correct) or recvhost */
1827 /* (compatible)? */
1828 if (f->f_host != NULL && buffer->host != NULL) {
1829 switch (f->f_host[0]) {
1830 case '+':
1831 if (! matches_spec(buffer->host, f->f_host + 1,
1832 strcasestr))
1833 continue;
1834 break;
1835 case '-':
1836 if (matches_spec(buffer->host, f->f_host + 1,
1837 strcasestr))
1838 continue;
1839 break;
1840 }
1841 }
1842
1843 /* skip messages with the incorrect program name */
1844 if (f->f_program != NULL && buffer->prog != NULL) {
1845 switch (f->f_program[0]) {
1846 case '+':
1847 if (!matches_spec(buffer->prog,
1848 f->f_program + 1, strstr))
1849 continue;
1850 break;
1851 case '-':
1852 if (matches_spec(buffer->prog,
1853 f->f_program + 1, strstr))
1854 continue;
1855 break;
1856 default:
1857 if (!matches_spec(buffer->prog,
1858 f->f_program, strstr))
1859 continue;
1860 break;
1861 }
1862 }
1863
1864 if (f->f_type == F_CONSOLE && (buffer->flags & IGN_CONS))
1865 continue;
1866
1867 /* don't output marks to recently written files */
1868 if ((buffer->flags & MARK)
1869 && (now - f->f_time) < MarkInterval / 2)
1870 continue;
1871
1872 /*
1873 * suppress duplicate lines to this file unless NoRepeat
1874 */
1875 #define MSG_FIELD_EQ(x) ((!buffer->x && !f->f_prevmsg->x) || \
1876 (buffer->x && f->f_prevmsg->x && !strcmp(buffer->x, f->f_prevmsg->x)))
1877
1878 if ((buffer->flags & MARK) == 0 &&
1879 f->f_prevmsg &&
1880 buffer->msglen == f->f_prevmsg->msglen &&
1881 !NoRepeat &&
1882 MSG_FIELD_EQ(host) &&
1883 MSG_FIELD_EQ(sd) &&
1884 MSG_FIELD_EQ(msg)
1885 ) {
1886 f->f_prevcount++;
1887 DPRINTF(D_DATA, "Msg repeated %d times, %ld sec of %d\n",
1888 f->f_prevcount, (long)(now - f->f_time),
1889 repeatinterval[f->f_repeatcount]);
1890 /*
1891 * If domark would have logged this by now,
1892 * flush it now (so we don't hold isolated messages),
1893 * but back off so we'll flush less often
1894 * in the future.
1895 */
1896 if (now > REPEATTIME(f)) {
1897 fprintlog(f, NEWREF(buffer), NULL);
1898 DELREF(buffer);
1899 BACKOFF(f);
1900 }
1901 } else {
1902 /* new line, save it */
1903 if (f->f_prevcount)
1904 fprintlog(f, NULL, NULL);
1905 f->f_repeatcount = 0;
1906 DELREF(f->f_prevmsg);
1907 f->f_prevmsg = NEWREF(buffer);
1908 fprintlog(f, NEWREF(buffer), NULL);
1909 DELREF(buffer);
1910 }
1911 }
1912 (void)sigsetmask(omask);
1913 }
1914
1915 /*
1916 * format one buffer into output format given by flag BSDOutputFormat
1917 * line is allocated and has to be free()d by caller
1918 * size_t pointers are optional, if not NULL then they will return
1919 * different lenghts used for formatting and output
1920 */
1921 #define OUT(x) ((x)?(x):"-")
1922 bool
1923 format_buffer(struct buf_msg *buffer, char **line, size_t *ptr_linelen,
1924 size_t *ptr_msglen, size_t *ptr_tlsprefixlen, size_t *ptr_prilen)
1925 {
1926 #define FPBUFSIZE 30
1927 static char ascii_empty[] = "";
1928 char fp_buf[FPBUFSIZE] = "\0";
1929 char *hostname, *shorthostname = NULL;
1930 char *ascii_sd = ascii_empty;
1931 char *ascii_msg = ascii_empty;
1932 size_t linelen, msglen, tlsprefixlen, prilen, j;
1933
1934 DPRINTF(D_CALL, "format_buffer(%p)\n", buffer);
1935 if (!buffer) return false;
1936
1937 /* All buffer fields are set with strdup(). To avoid problems
1938 * on memory exhaustion we allow them to be empty and replace
1939 * the essential fields with already allocated generic values.
1940 */
1941 if (!buffer->timestamp)
1942 buffer->timestamp = timestamp;
1943 if (!buffer->host && !buffer->recvhost)
1944 buffer->host = LocalFQDN;
1945
1946 if (LogFacPri) {
1947 const char *f_s = NULL, *p_s = NULL;
1948 int fac = buffer->pri & LOG_FACMASK;
1949 int pri = LOG_PRI(buffer->pri);
1950 char f_n[5], p_n[5];
1951
1952 if (LogFacPri > 1) {
1953 CODE *c;
1954
1955 for (c = facilitynames; c->c_name != NULL; c++) {
1956 if (c->c_val == fac) {
1957 f_s = c->c_name;
1958 break;
1959 }
1960 }
1961 for (c = prioritynames; c->c_name != NULL; c++) {
1962 if (c->c_val == pri) {
1963 p_s = c->c_name;
1964 break;
1965 }
1966 }
1967 }
1968 if (f_s == NULL) {
1969 snprintf(f_n, sizeof(f_n), "%d", LOG_FAC(fac));
1970 f_s = f_n;
1971 }
1972 if (p_s == NULL) {
1973 snprintf(p_n, sizeof(p_n), "%d", pri);
1974 p_s = p_n;
1975 }
1976 snprintf(fp_buf, sizeof(fp_buf), "<%s.%s>", f_s, p_s);
1977 }
1978
1979 /* hostname or FQDN */
1980 hostname = (buffer->host ? buffer->host : buffer->recvhost);
1981 if (BSDOutputFormat
1982 && (shorthostname = strdup(hostname))) {
1983 /* if the previous BSD output format with "host [recvhost]:"
1984 * gets implemented, this is the right place to distinguish
1985 * between buffer->host and buffer->recvhost
1986 */
1987 trim_anydomain(shorthostname);
1988 hostname = shorthostname;
1989 }
1990
1991 /* new message formatting:
1992 * instead of using iov always assemble one complete TLS-ready line
1993 * with length and priority (depending on BSDOutputFormat either in
1994 * BSD Syslog or syslog-protocol format)
1995 *
1996 * additionally save the length of the prefixes,
1997 * so UDP destinations can skip the length prefix and
1998 * file/pipe/wall destinations can omit length and priority
1999 */
2000 /* first determine required space */
2001 if (BSDOutputFormat) {
2002 /* only output ASCII chars */
2003 if (buffer->sd)
2004 ascii_sd = copy_utf8_ascii(buffer->sd,
2005 strlen(buffer->sd));
2006 if (buffer->msg) {
2007 if (IS_BOM(buffer->msg))
2008 ascii_msg = copy_utf8_ascii(buffer->msg,
2009 buffer->msglen - 1);
2010 else /* assume already converted at input */
2011 ascii_msg = buffer->msg;
2012 }
2013 msglen = snprintf(NULL, 0, "<%d>%s%.15s %s %s%s%s%s: %s%s%s",
2014 buffer->pri, fp_buf, buffer->timestamp,
2015 hostname, OUT(buffer->prog),
2016 buffer->pid ? "[" : "",
2017 buffer->pid ? buffer->pid : "",
2018 buffer->pid ? "]" : "", ascii_sd,
2019 (buffer->sd && buffer->msg ? " ": ""), ascii_msg);
2020 } else
2021 msglen = snprintf(NULL, 0, "<%d>1 %s%s %s %s %s %s %s%s%s",
2022 buffer->pri, fp_buf, buffer->timestamp,
2023 hostname, OUT(buffer->prog), OUT(buffer->pid),
2024 OUT(buffer->msgid), OUT(buffer->sd),
2025 (buffer->msg ? " ": ""),
2026 (buffer->msg ? buffer->msg: ""));
2027 /* add space for length prefix */
2028 tlsprefixlen = 0;
2029 for (j = msglen; j; j /= 10)
2030 tlsprefixlen++;
2031 /* one more for the space */
2032 tlsprefixlen++;
2033
2034 prilen = snprintf(NULL, 0, "<%d>", buffer->pri);
2035 if (!BSDOutputFormat)
2036 prilen += 2; /* version char and space */
2037 MALLOC(*line, msglen + tlsprefixlen + 1);
2038 if (BSDOutputFormat)
2039 linelen = snprintf(*line,
2040 msglen + tlsprefixlen + 1,
2041 "%zu <%d>%s%.15s %s %s%s%s%s: %s%s%s",
2042 msglen, buffer->pri, fp_buf, buffer->timestamp,
2043 hostname, OUT(buffer->prog),
2044 (buffer->pid ? "[" : ""),
2045 (buffer->pid ? buffer->pid : ""),
2046 (buffer->pid ? "]" : ""), ascii_sd,
2047 (buffer->sd && buffer->msg ? " ": ""), ascii_msg);
2048 else
2049 linelen = snprintf(*line,
2050 msglen + tlsprefixlen + 1,
2051 "%zu <%d>1 %s%s %s %s %s %s %s%s%s",
2052 msglen, buffer->pri, fp_buf, buffer->timestamp,
2053 hostname, OUT(buffer->prog), OUT(buffer->pid),
2054 OUT(buffer->msgid), OUT(buffer->sd),
2055 (buffer->msg ? " ": ""),
2056 (buffer->msg ? buffer->msg: ""));
2057 DPRINTF(D_DATA, "formatted %zu octets to: '%.*s' (linelen %zu, "
2058 "msglen %zu, tlsprefixlen %zu, prilen %zu)\n", linelen,
2059 (int)linelen, *line, linelen, msglen, tlsprefixlen, prilen);
2060
2061 FREEPTR(shorthostname);
2062 if (ascii_sd != ascii_empty)
2063 FREEPTR(ascii_sd);
2064 if (ascii_msg != ascii_empty && ascii_msg != buffer->msg)
2065 FREEPTR(ascii_msg);
2066
2067 if (ptr_linelen) *ptr_linelen = linelen;
2068 if (ptr_msglen) *ptr_msglen = msglen;
2069 if (ptr_tlsprefixlen) *ptr_tlsprefixlen = tlsprefixlen;
2070 if (ptr_prilen) *ptr_prilen = prilen;
2071 return true;
2072 }
2073
2074 /*
2075 * if qentry == NULL: new message, if temporarily undeliverable it will be enqueued
2076 * if qentry != NULL: a temporarily undeliverable message will not be enqueued,
2077 * but after delivery be removed from the queue
2078 */
2079 void
2080 fprintlog(struct filed *f, struct buf_msg *passedbuffer, struct buf_queue *qentry)
2081 {
2082 static char crnl[] = "\r\n";
2083 struct buf_msg *buffer = passedbuffer;
2084 struct iovec iov[4];
2085 struct iovec *v = iov;
2086 bool error = false;
2087 int e = 0, len = 0;
2088 size_t msglen, linelen, tlsprefixlen, prilen;
2089 char *p, *line = NULL, *lineptr = NULL;
2090 #ifndef DISABLE_TLS
2091 bool newhash = false;
2092 #endif
2093 #define REPBUFSIZE 80
2094 char greetings[200];
2095 #define ADDEV() do { v++; assert(v - iov < A_CNT(iov)); } while(/*CONSTCOND*/0)
2096
2097 DPRINTF(D_CALL, "fprintlog(%p, %p, %p)\n", f, buffer, qentry);
2098
2099 f->f_time = now;
2100
2101 /* increase refcount here and lower again at return.
2102 * this enables the buffer in the else branch to be freed
2103 * --> every branch needs one NEWREF() or buf_msg_new()! */
2104 if (buffer) {
2105 NEWREF(buffer);
2106 } else {
2107 if (f->f_prevcount > 1) {
2108 /* possible syslog-sign incompatibility:
2109 * assume destinations f1 and f2 share one SG and
2110 * get the same message sequence.
2111 *
2112 * now both f1 and f2 generate "repeated" messages
2113 * "repeated" messages are different due to different
2114 * timestamps
2115 * the SG will get hashes for the two "repeated" messages
2116 *
2117 * now both f1 and f2 are just fine, but a verification
2118 * will report that each 'lost' a message, i.e. the
2119 * other's "repeated" message
2120 *
2121 * conditions for 'safe configurations':
2122 * - use NoRepeat option,
2123 * - use SG 3, or
2124 * - have exactly one destination for every PRI
2125 */
2126 buffer = buf_msg_new(REPBUFSIZE);
2127 buffer->msglen = snprintf(buffer->msg, REPBUFSIZE,
2128 "last message repeated %d times", f->f_prevcount);
2129 buffer->timestamp =
2130 strdup(make_timestamp(NULL, !BSDOutputFormat));
2131 buffer->pri = f->f_prevmsg->pri;
2132 buffer->host = LocalFQDN;
2133 buffer->prog = appname;
2134 buffer->pid = include_pid;
2135
2136 } else {
2137 buffer = NEWREF(f->f_prevmsg);
2138 }
2139 }
2140
2141 /* no syslog-sign messages to tty/console/... */
2142 if ((buffer->flags & SIGN_MSG)
2143 && ((f->f_type == F_UNUSED)
2144 || (f->f_type == F_TTY)
2145 || (f->f_type == F_CONSOLE)
2146 || (f->f_type == F_USERS)
2147 || (f->f_type == F_WALL))) {
2148 DELREF(buffer);
2149 return;
2150 }
2151
2152 /* buffering works only for few types */
2153 if (qentry
2154 && (f->f_type != F_TLS)
2155 && (f->f_type != F_PIPE)
2156 && (f->f_type != F_FILE)) {
2157 logerror("Warning: unexpected message in buffer");
2158 DELREF(buffer);
2159 return;
2160 }
2161
2162 if (!format_buffer(buffer, &line,
2163 &linelen, &msglen, &tlsprefixlen, &prilen)) {
2164 DPRINTF(D_CALL, "format_buffer() failed, skip message\n");
2165 DELREF(buffer);
2166 return;
2167 }
2168 /* assert maximum message length */
2169 if (TypeInfo[f->f_type].max_msg_length != -1
2170 && TypeInfo[f->f_type].max_msg_length
2171 < linelen - tlsprefixlen - prilen) {
2172 linelen = TypeInfo[f->f_type].max_msg_length
2173 + tlsprefixlen + prilen;
2174 DPRINTF(D_DATA, "truncating oversized message to %zu octets\n",
2175 linelen);
2176 }
2177
2178 #ifndef DISABLE_SIGN
2179 /* keep state between appending the hash (before buffer is sent)
2180 * and possibly sending a SB (after buffer is sent): */
2181 /* get hash */
2182 if (!(buffer->flags & SIGN_MSG) && !qentry) {
2183 char *hash = NULL;
2184 struct signature_group_t *sg;
2185
2186 if ((sg = sign_get_sg(buffer->pri, f)) != NULL) {
2187 if (sign_msg_hash(line + tlsprefixlen, &hash))
2188 newhash = sign_append_hash(hash, sg);
2189 else
2190 DPRINTF(D_SIGN,
2191 "Unable to hash line \"%s\"\n", line);
2192 }
2193 }
2194 #endif /* !DISABLE_SIGN */
2195
2196 /* set start and length of buffer and/or fill iovec */
2197 switch (f->f_type) {
2198 case F_UNUSED:
2199 /* nothing */
2200 break;
2201 case F_TLS:
2202 /* nothing, as TLS uses whole buffer to send */
2203 lineptr = line;
2204 len = linelen;
2205 break;
2206 case F_FORW:
2207 lineptr = line + tlsprefixlen;
2208 len = linelen - tlsprefixlen;
2209 break;
2210 case F_PIPE:
2211 case F_FILE: /* fallthrough */
2212 if (f->f_flags & FFLAG_FULL) {
2213 v->iov_base = line + tlsprefixlen;
2214 v->iov_len = linelen - tlsprefixlen;
2215 } else {
2216 v->iov_base = line + tlsprefixlen + prilen;
2217 v->iov_len = linelen - tlsprefixlen - prilen;
2218 }
2219 ADDEV();
2220 v->iov_base = &crnl[1];
2221 v->iov_len = 1;
2222 ADDEV();
2223 break;
2224 case F_CONSOLE:
2225 case F_TTY:
2226 /* filter non-ASCII */
2227 p = line;
2228 while (*p) {
2229 *p = FORCE2ASCII(*p);
2230 p++;
2231 }
2232 v->iov_base = line + tlsprefixlen + prilen;
2233 v->iov_len = linelen - tlsprefixlen - prilen;
2234 ADDEV();
2235 v->iov_base = crnl;
2236 v->iov_len = 2;
2237 ADDEV();
2238 break;
2239 case F_WALL:
2240 v->iov_base = greetings;
2241 v->iov_len = snprintf(greetings, sizeof(greetings),
2242 "\r\n\7Message from syslogd@%s at %s ...\r\n",
2243 (buffer->host ? buffer->host : buffer->recvhost),
2244 buffer->timestamp);
2245 ADDEV();
2246 case F_USERS: /* fallthrough */
2247 /* filter non-ASCII */
2248 p = line;
2249 while (*p) {
2250 *p = FORCE2ASCII(*p);
2251 p++;
2252 }
2253 v->iov_base = line + tlsprefixlen + prilen;
2254 v->iov_len = linelen - tlsprefixlen - prilen;
2255 ADDEV();
2256 v->iov_base = &crnl[1];
2257 v->iov_len = 1;
2258 ADDEV();
2259 break;
2260 }
2261
2262 /* send */
2263 switch (f->f_type) {
2264 case F_UNUSED:
2265 DPRINTF(D_MISC, "Logging to %s\n", TypeInfo[f->f_type].name);
2266 break;
2267
2268 case F_FORW:
2269 DPRINTF(D_MISC, "Logging to %s %s\n",
2270 TypeInfo[f->f_type].name, f->f_un.f_forw.f_hname);
2271 udp_send(f, lineptr, len);
2272 break;
2273
2274 #ifndef DISABLE_TLS
2275 case F_TLS:
2276 DPRINTF(D_MISC, "Logging to %s %s\n",
2277 TypeInfo[f->f_type].name,
2278 f->f_un.f_tls.tls_conn->hostname);
2279 /* make sure every message gets queued once
2280 * it will be removed when sendmsg is sent and free()d */
2281 if (!qentry)
2282 qentry = message_queue_add(f, NEWREF(buffer));
2283 (void)tls_send(f, lineptr, len, qentry);
2284 break;
2285 #endif /* !DISABLE_TLS */
2286
2287 case F_PIPE:
2288 DPRINTF(D_MISC, "Logging to %s %s\n",
2289 TypeInfo[f->f_type].name, f->f_un.f_pipe.f_pname);
2290 if (f->f_un.f_pipe.f_pid == 0) {
2291 /* (re-)open */
2292 if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
2293 &f->f_un.f_pipe.f_pid)) < 0) {
2294 f->f_type = F_UNUSED;
2295 message_queue_freeall(f);
2296 logerror(f->f_un.f_pipe.f_pname);
2297 break;
2298 } else if (!qentry) /* prevent recursion */
2299 SEND_QUEUE(f);
2300 }
2301 if (writev(f->f_file, iov, v - iov) < 0) {
2302 e = errno;
2303 if (f->f_un.f_pipe.f_pid > 0) {
2304 (void) close(f->f_file);
2305 deadq_enter(f->f_un.f_pipe.f_pid,
2306 f->f_un.f_pipe.f_pname);
2307 }
2308 f->f_un.f_pipe.f_pid = 0;
2309 /*
2310 * If the error was EPIPE, then what is likely
2311 * has happened is we have a command that is
2312 * designed to take a single message line and
2313 * then exit, but we tried to feed it another
2314 * one before we reaped the child and thus
2315 * reset our state.
2316 *
2317 * Well, now we've reset our state, so try opening
2318 * the pipe and sending the message again if EPIPE
2319 * was the error.
2320 */
2321 if (e == EPIPE) {
2322 if ((f->f_file = p_open(f->f_un.f_pipe.f_pname,
2323 &f->f_un.f_pipe.f_pid)) < 0) {
2324 f->f_type = F_UNUSED;
2325 message_queue_freeall(f);
2326 logerror(f->f_un.f_pipe.f_pname);
2327 break;
2328 }
2329 if (writev(f->f_file, iov, v - iov) < 0) {
2330 e = errno;
2331 if (f->f_un.f_pipe.f_pid > 0) {
2332 (void) close(f->f_file);
2333 deadq_enter(f->f_un.f_pipe.f_pid,
2334 f->f_un.f_pipe.f_pname);
2335 }
2336 f->f_un.f_pipe.f_pid = 0;
2337 error = true; /* enqueue on return */
2338 } else
2339 e = 0;
2340 }
2341 if (e != 0 && !error) {
2342 errno = e;
2343 logerror(f->f_un.f_pipe.f_pname);
2344 }
2345 }
2346 if (e == 0 && qentry) { /* sent buffered msg */
2347 message_queue_remove(f, qentry);
2348 }
2349 break;
2350
2351 case F_CONSOLE:
2352 if (buffer->flags & IGN_CONS) {
2353 DPRINTF(D_MISC, "Logging to %s (ignored)\n",
2354 TypeInfo[f->f_type].name);
2355 break;
2356 }
2357 /* FALLTHROUGH */
2358
2359 case F_TTY:
2360 case F_FILE:
2361 DPRINTF(D_MISC, "Logging to %s %s\n",
2362 TypeInfo[f->f_type].name, f->f_un.f_fname);
2363 again:
2364 if (writev(f->f_file, iov, v - iov) < 0) {
2365 e = errno;
2366 if (f->f_type == F_FILE && e == ENOSPC) {
2367 int lasterror = f->f_lasterror;
2368 f->f_lasterror = e;
2369 if (lasterror != e)
2370 logerror(f->f_un.f_fname);
2371 error = true; /* enqueue on return */
2372 }
2373 (void)close(f->f_file);
2374 /*
2375 * Check for errors on TTY's due to loss of tty
2376 */
2377 if ((e == EIO || e == EBADF) && f->f_type != F_FILE) {
2378 f->f_file = open(f->f_un.f_fname,
2379 O_WRONLY|O_APPEND, 0);
2380 if (f->f_file < 0) {
2381 f->f_type = F_UNUSED;
2382 logerror(f->f_un.f_fname);
2383 message_queue_freeall(f);
2384 } else
2385 goto again;
2386 } else {
2387 f->f_type = F_UNUSED;
2388 errno = e;
2389 f->f_lasterror = e;
2390 logerror(f->f_un.f_fname);
2391 message_queue_freeall(f);
2392 }
2393 } else {
2394 f->f_lasterror = 0;
2395 if ((buffer->flags & SYNC_FILE)
2396 && (f->f_flags & FFLAG_SYNC))
2397 (void)fsync(f->f_file);
2398 /* Problem with files: We cannot check beforehand if
2399 * they would be writeable and call send_queue() first.
2400 * So we call send_queue() after a successful write,
2401 * which means the first message will be out of order.
2402 */
2403 if (!qentry) /* prevent recursion */
2404 SEND_QUEUE(f);
2405 else if (qentry) /* sent buffered msg */
2406 message_queue_remove(f, qentry);
2407 }
2408 break;
2409
2410 case F_USERS:
2411 case F_WALL:
2412 DPRINTF(D_MISC, "Logging to %s\n", TypeInfo[f->f_type].name);
2413 wallmsg(f, iov, v - iov);
2414 break;
2415 }
2416 f->f_prevcount = 0;
2417
2418 if (error && !qentry)
2419 message_queue_add(f, NEWREF(buffer));
2420 #ifndef DISABLE_SIGN
2421 if (newhash) {
2422 struct signature_group_t *sg;
2423 sg = sign_get_sg(buffer->pri, f);
2424 (void)sign_send_signature_block(sg, false);
2425 }
2426 #endif /* !DISABLE_SIGN */
2427 /* this belongs to the ad-hoc buffer at the first if(buffer) */
2428 DELREF(buffer);
2429 /* TLS frees on its own */
2430 if (f->f_type != F_TLS)
2431 FREEPTR(line);
2432 }
2433
2434 /* send one line by UDP */
2435 void
2436 udp_send(struct filed *f, char *line, size_t len)
2437 {
2438 int lsent, fail, retry, j;
2439 struct addrinfo *r;
2440
2441 DPRINTF((D_NET|D_CALL), "udp_send(f=%p, line=\"%s\", "
2442 "len=%zu) to dest.\n", f, line, len);
2443
2444 if (!finet)
2445 return;
2446
2447 lsent = -1;
2448 fail = 0;
2449 assert(f->f_type == F_FORW);
2450 for (r = f->f_un.f_forw.f_addr; r; r = r->ai_next) {
2451 retry = 0;
2452 for (j = 0; j < finet->fd; j++) {
2453 sendagain:
2454 lsent = sendto(finet[j+1].fd, line, len, 0,
2455 r->ai_addr, r->ai_addrlen);
2456 if (lsent == -1) {
2457 switch (errno) {
2458 case ENOBUFS:
2459 /* wait/retry/drop */
2460 if (++retry < 5) {
2461 usleep(1000);
2462 goto sendagain;
2463 }
2464 break;
2465 case EHOSTDOWN:
2466 case EHOSTUNREACH:
2467 case ENETDOWN:
2468 /* drop */
2469 break;
2470 default:
2471 /* busted */
2472 fail++;
2473 break;
2474 }
2475 } else if (lsent == len)
2476 break;
2477 }
2478 if (lsent != len && fail) {
2479 f->f_type = F_UNUSED;
2480 logerror("sendto() failed");
2481 }
2482 }
2483 }
2484
2485 /*
2486 * WALLMSG -- Write a message to the world at large
2487 *
2488 * Write the specified message to either the entire
2489 * world, or a list of approved users.
2490 */
2491 void
2492 wallmsg(struct filed *f, struct iovec *iov, size_t iovcnt)
2493 {
2494 #ifdef __NetBSD_Version__
2495 static int reenter; /* avoid calling ourselves */
2496 int i;
2497 char *p;
2498 struct utmpentry *ep;
2499
2500 if (reenter++)
2501 return;
2502
2503 (void)getutentries(NULL, &ep);
2504 /* NOSTRICT */
2505 for (; ep; ep = ep->next) {
2506 if (f->f_type == F_WALL) {
2507 if ((p = ttymsg(iov, iovcnt, ep->line, TTYMSGTIME))
2508 != NULL) {
2509 errno = 0; /* already in msg */
2510 logerror(p);
2511 }
2512 continue;
2513 }
2514 /* should we send the message to this user? */
2515 for (i = 0; i < MAXUNAMES; i++) {
2516 if (!f->f_un.f_uname[i][0])
2517 break;
2518 if (strcmp(f->f_un.f_uname[i], ep->name) == 0) {
2519 if ((p = ttymsg(iov, iovcnt, ep->line,
2520 TTYMSGTIME)) != NULL) {
2521 errno = 0; /* already in msg */
2522 logerror(p);
2523 }
2524 break;
2525 }
2526 }
2527 }
2528 reenter = 0;
2529 #endif /* __NetBSD_Version__ */
2530 }
2531
2532 void
2533 /*ARGSUSED*/
2534 reapchild(int fd, short event, void *ev)
2535 {
2536 int status;
2537 pid_t pid;
2538 struct filed *f;
2539
2540 while ((pid = wait3(&status, WNOHANG, NULL)) > 0) {
2541 if (!Initialized || ShuttingDown) {
2542 /*
2543 * Be silent while we are initializing or
2544 * shutting down.
2545 */
2546 continue;
2547 }
2548
2549 if (deadq_remove(pid))
2550 continue;
2551
2552 /* Now, look in the list of active processes. */
2553 for (f = Files; f != NULL; f = f->f_next) {
2554 if (f->f_type == F_PIPE &&
2555 f->f_un.f_pipe.f_pid == pid) {
2556 (void) close(f->f_file);
2557 f->f_un.f_pipe.f_pid = 0;
2558 log_deadchild(pid, status,
2559 f->f_un.f_pipe.f_pname);
2560 break;
2561 }
2562 }
2563 }
2564 }
2565
2566 /*
2567 * Return a printable representation of a host address (FQDN if available)
2568 */
2569 const char *
2570 cvthname(struct sockaddr_storage *f)
2571 {
2572 int error;
2573 int niflag = NI_DGRAM;
2574 static char host[NI_MAXHOST], ip[NI_MAXHOST];
2575
2576 error = getnameinfo((struct sockaddr*)f, ((struct sockaddr*)f)->sa_len,
2577 ip, sizeof ip, NULL, 0, NI_NUMERICHOST|niflag);
2578
2579 DPRINTF(D_CALL, "cvthname(%s)\n", ip);
2580
2581 if (error) {
2582 DPRINTF(D_NET, "Malformed from address %s\n",
2583 gai_strerror(error));
2584 return "???";
2585 }
2586
2587 if (!UseNameService)
2588 return ip;
2589
2590 error = getnameinfo((struct sockaddr*)f, ((struct sockaddr*)f)->sa_len,
2591 host, sizeof host, NULL, 0, niflag);
2592 if (error) {
2593 DPRINTF(D_NET, "Host name for your address (%s) unknown\n", ip);
2594 return ip;
2595 }
2596
2597 return host;
2598 }
2599
2600 void
2601 trim_anydomain(char *host)
2602 {
2603 bool onlydigits = true;
2604 int i;
2605
2606 if (!BSDOutputFormat)
2607 return;
2608
2609 /* if non-digits found, then assume hostname and cut at first dot (this
2610 * case also covers IPv6 addresses which should not contain dots),
2611 * if only digits then assume IPv4 address and do not cut at all */
2612 for (i = 0; host[i]; i++) {
2613 if (host[i] == '.' && !onlydigits)
2614 host[i] = '\0';
2615 else if (!isdigit((unsigned char)host[i]) && host[i] != '.')
2616 onlydigits = false;
2617 }
2618 }
2619
2620 static void
2621 /*ARGSUSED*/
2622 domark(int fd, short event, void *ev)
2623 {
2624 struct event *ev_pass = (struct event *)ev;
2625 struct filed *f;
2626 dq_t q, nextq;
2627 sigset_t newmask, omask;
2628
2629 schedule_event(&ev_pass,
2630 &((struct timeval){TIMERINTVL, 0}),
2631 domark, ev_pass);
2632 DPRINTF((D_CALL|D_EVENT), "domark()\n");
2633
2634 BLOCK_SIGNALS(omask, newmask);
2635 now = time((time_t *)NULL);
2636 MarkSeq += TIMERINTVL;
2637 if (MarkSeq >= MarkInterval) {
2638 logmsg_async(LOG_INFO, NULL, "-- MARK --", ADDDATE|MARK);
2639 MarkSeq = 0;
2640 }
2641
2642 for (f = Files; f; f = f->f_next) {
2643 if (f->f_prevcount && now >= REPEATTIME(f)) {
2644 DPRINTF(D_DATA, "Flush %s: repeated %d times, %d sec.\n",
2645 TypeInfo[f->f_type].name, f->f_prevcount,
2646 repeatinterval[f->f_repeatcount]);
2647 fprintlog(f, NULL, NULL);
2648 BACKOFF(f);
2649 }
2650 }
2651 message_allqueues_check();
2652 RESTORE_SIGNALS(omask);
2653
2654 /* Walk the dead queue, and see if we should signal somebody. */
2655 for (q = TAILQ_FIRST(&deadq_head); q != NULL; q = nextq) {
2656 nextq = TAILQ_NEXT(q, dq_entries);
2657 switch (q->dq_timeout) {
2658 case 0:
2659 /* Already signalled once, try harder now. */
2660 if (kill(q->dq_pid, SIGKILL) != 0)
2661 (void) deadq_remove(q->dq_pid);
2662 break;
2663
2664 case 1:
2665 /*
2666 * Timed out on the dead queue, send terminate
2667 * signal. Note that we leave the removal from
2668 * the dead queue to reapchild(), which will
2669 * also log the event (unless the process
2670 * didn't even really exist, in case we simply
2671 * drop it from the dead queue).
2672 */
2673 if (kill(q->dq_pid, SIGTERM) != 0) {
2674 (void) deadq_remove(q->dq_pid);
2675 break;
2676 }
2677 /* FALLTHROUGH */
2678
2679 default:
2680 q->dq_timeout--;
2681 }
2682 }
2683 #ifndef DISABLE_SIGN
2684 if (GlobalSign.rsid) { /* check if initialized */
2685 struct signature_group_t *sg;
2686 STAILQ_FOREACH(sg, &GlobalSign.SigGroups, entries) {
2687 sign_send_certificate_block(sg);
2688 }
2689 }
2690 #endif /* !DISABLE_SIGN */
2691 }
2692
2693 /*
2694 * Print syslogd errors some place.
2695 */
2696 void
2697 logerror(const char *fmt, ...)
2698 {
2699 static int logerror_running;
2700 va_list ap;
2701 char tmpbuf[BUFSIZ];
2702 char buf[BUFSIZ];
2703 char *outbuf;
2704
2705 /* If there's an error while trying to log an error, give up. */
2706 if (logerror_running)
2707 return;
2708 logerror_running = 1;
2709
2710 va_start(ap, fmt);
2711 (void)vsnprintf(tmpbuf, sizeof(tmpbuf), fmt, ap);
2712 va_end(ap);
2713
2714 if (errno) {
2715 (void)snprintf(buf, sizeof(buf), "%s: %s",
2716 tmpbuf, strerror(errno));
2717 outbuf = buf;
2718 } else {
2719 (void)snprintf(buf, sizeof(buf), "%s", tmpbuf);
2720 outbuf = tmpbuf;
2721 }
2722
2723 if (daemonized)
2724 logmsg_async(LOG_SYSLOG|LOG_ERR, NULL, outbuf, ADDDATE);
2725 if (!daemonized && Debug)
2726 DPRINTF(D_MISC, "%s\n", outbuf);
2727 if (!daemonized && !Debug)
2728 printf("%s\n", outbuf);
2729
2730 logerror_running = 0;
2731 }
2732
2733 /*
2734 * Print syslogd info some place.
2735 */
2736 void
2737 loginfo(const char *fmt, ...)
2738 {
2739 va_list ap;
2740 char buf[BUFSIZ];
2741
2742 va_start(ap, fmt);
2743 (void)vsnprintf(buf, sizeof(buf), fmt, ap);
2744 va_end(ap);
2745
2746 DPRINTF(D_MISC, "%s\n", buf);
2747 logmsg_async(LOG_SYSLOG|LOG_INFO, NULL, buf, ADDDATE);
2748 }
2749
2750 #ifndef DISABLE_TLS
2751 static inline void
2752 free_incoming_tls_sockets(void)
2753 {
2754 struct TLS_Incoming_Conn *tls_in;
2755 int i;
2756
2757 /*
2758 * close all listening and connected TLS sockets
2759 */
2760 if (TLS_Listen_Set)
2761 for (i = 0; i < TLS_Listen_Set->fd; i++) {
2762 if (close(TLS_Listen_Set[i+1].fd) == -1)
2763 logerror("close() failed");
2764 DEL_EVENT(TLS_Listen_Set[i+1].ev);
2765 FREEPTR(TLS_Listen_Set[i+1].ev);
2766 }
2767 FREEPTR(TLS_Listen_Set);
2768 /* close/free incoming TLS connections */
2769 while (!SLIST_EMPTY(&TLS_Incoming_Head)) {
2770 tls_in = SLIST_FIRST(&TLS_Incoming_Head);
2771 SLIST_REMOVE_HEAD(&TLS_Incoming_Head, entries);
2772 FREEPTR(tls_in->inbuf);
2773 free_tls_conn(tls_in->tls_conn);
2774 free(tls_in);
2775 }
2776 }
2777 #endif /* !DISABLE_TLS */
2778
2779 void
2780 /*ARGSUSED*/
2781 die(int fd, short event, void *ev)
2782 {
2783 struct filed *f, *next;
2784 char **p;
2785 sigset_t newmask, omask;
2786 int i;
2787
2788 ShuttingDown = 1; /* Don't log SIGCHLDs. */
2789 /* prevent recursive signals */
2790 BLOCK_SIGNALS(omask, newmask);
2791
2792 /*
2793 * flush any pending output
2794 */
2795 for (f = Files; f != NULL; f = f->f_next) {
2796 /* flush any pending output */
2797 if (f->f_prevcount)
2798 fprintlog(f, NULL, NULL);
2799 SEND_QUEUE(f);
2800 }
2801
2802 #ifndef DISABLE_TLS
2803 free_incoming_tls_sockets();
2804 #endif /* !DISABLE_TLS */
2805 #ifndef DISABLE_SIGN
2806 sign_global_free();
2807 #endif /* !DISABLE_SIGN */
2808
2809 /*
2810 * Close all open log files.
2811 */
2812 for (f = Files; f != NULL; f = next) {
2813 message_queue_freeall(f);
2814
2815 switch (f->f_type) {
2816 case F_FILE:
2817 case F_TTY:
2818 case F_CONSOLE:
2819 (void)close(f->f_file);
2820 break;
2821 case F_PIPE:
2822 if (f->f_un.f_pipe.f_pid > 0) {
2823 (void)close(f->f_file);
2824 }
2825 f->f_un.f_pipe.f_pid = 0;
2826 break;
2827 case F_FORW:
2828 if (f->f_un.f_forw.f_addr)
2829 freeaddrinfo(f->f_un.f_forw.f_addr);
2830 break;
2831 #ifndef DISABLE_TLS
2832 case F_TLS:
2833 free_tls_conn(f->f_un.f_tls.tls_conn);
2834 break;
2835 #endif /* !DISABLE_TLS */
2836 }
2837 next = f->f_next;
2838 DELREF(f->f_prevmsg);
2839 FREEPTR(f->f_program);
2840 FREEPTR(f->f_host);
2841 DEL_EVENT(f->f_sq_event);
2842 free((char *)f);
2843 }
2844
2845 /*
2846 * Close all open UDP sockets
2847 */
2848 if (finet) {
2849 for (i = 0; i < finet->fd; i++) {
2850 if (close(finet[i+1].fd) < 0) {
2851 logerror("close() failed");
2852 die(0, 0, NULL);
2853 }
2854 DEL_EVENT(finet[i+1].ev);
2855 FREEPTR(finet[i+1].ev);
2856 }
2857 FREEPTR(finet);
2858 }
2859
2860 /* free config options */
2861 for (i = 0; i < A_CNT(TypeInfo); i++) {
2862 FREEPTR(TypeInfo[i].queue_length_string);
2863 FREEPTR(TypeInfo[i].queue_size_string);
2864 }
2865
2866 #ifndef DISABLE_TLS
2867 FREEPTR(tls_opt.CAdir);
2868 FREEPTR(tls_opt.CAfile);
2869 FREEPTR(tls_opt.keyfile);
2870 FREEPTR(tls_opt.certfile);
2871 FREEPTR(tls_opt.x509verify);
2872 FREEPTR(tls_opt.bindhost);
2873 FREEPTR(tls_opt.bindport);
2874 FREEPTR(tls_opt.server);
2875 FREEPTR(tls_opt.gen_cert);
2876 free_cred_SLIST(&tls_opt.cert_head);
2877 free_cred_SLIST(&tls_opt.fprint_head);
2878 FREE_SSL_CTX(tls_opt.global_TLS_CTX);
2879 #endif /* !DISABLE_TLS */
2880
2881 FREEPTR(funix);
2882 errno = 0;
2883 if (ev != NULL)
2884 logerror("Exiting on signal %d", fd);
2885 else
2886 logerror("Fatal error, exiting");
2887 for (p = LogPaths; p && *p; p++)
2888 unlink(*p);
2889 exit(0);
2890 }
2891
2892 #ifndef DISABLE_SIGN
2893 /*
2894 * get one "sign_delim_sg2" item, convert and store in ordered queue
2895 */
2896 void
2897 store_sign_delim_sg2(char *tmp_buf)
2898 {
2899 struct string_queue *sqentry, *sqe1, *sqe2;
2900
2901 if(!(sqentry = malloc(sizeof(*sqentry)))) {
2902 logerror("Unable to allocate memory");
2903 return;
2904 }
2905 /*LINTED constcond/null effect */
2906 assert(sizeof(int64_t) == sizeof(uint_fast64_t));
2907 if (dehumanize_number(tmp_buf, (int64_t*) &(sqentry->key)) == -1
2908 || sqentry->key > (LOG_NFACILITIES<<3)) {
2909 DPRINTF(D_PARSE, "invalid sign_delim_sg2: %s\n", tmp_buf);
2910 free(sqentry);
2911 FREEPTR(tmp_buf);
2912 return;
2913 }
2914 sqentry->data = tmp_buf;
2915
2916 if (STAILQ_EMPTY(&GlobalSign.sig2_delims)) {
2917 STAILQ_INSERT_HEAD(&GlobalSign.sig2_delims,
2918 sqentry, entries);
2919 return;
2920 }
2921
2922 /* keep delimiters sorted */
2923 sqe1 = sqe2 = STAILQ_FIRST(&GlobalSign.sig2_delims);
2924 if (sqe1->key > sqentry->key) {
2925 STAILQ_INSERT_HEAD(&GlobalSign.sig2_delims,
2926 sqentry, entries);
2927 return;
2928 }
2929
2930 while ((sqe1 = sqe2)
2931 && (sqe2 = STAILQ_NEXT(sqe1, entries))) {
2932 if (sqe2->key > sqentry->key) {
2933 break;
2934 } else if (sqe2->key == sqentry->key) {
2935 DPRINTF(D_PARSE, "duplicate sign_delim_sg2: %s\n",
2936 tmp_buf);
2937 FREEPTR(sqentry);
2938 FREEPTR(tmp_buf);
2939 return;
2940 }
2941 }
2942 STAILQ_INSERT_AFTER(&GlobalSign.sig2_delims, sqe1, sqentry, entries);
2943 }
2944 #endif /* !DISABLE_SIGN */
2945
2946 /*
2947 * read syslog.conf
2948 */
2949 void
2950 read_config_file(FILE *cf, struct filed **f_ptr)
2951 {
2952 size_t linenum = 0;
2953 size_t i;
2954 struct filed *f, **nextp;
2955 char cline[LINE_MAX];
2956 char prog[NAME_MAX + 1];
2957 char host[MAXHOSTNAMELEN];
2958 const char *p;
2959 char *q;
2960 bool found_keyword;
2961 #ifndef DISABLE_TLS
2962 struct peer_cred *cred = NULL;
2963 struct peer_cred_head *credhead = NULL;
2964 #endif /* !DISABLE_TLS */
2965 #ifndef DISABLE_SIGN
2966 char *sign_sg_str = NULL;
2967 #endif /* !DISABLE_SIGN */
2968 #if (!defined(DISABLE_TLS) || !defined(DISABLE_SIGN))
2969 char *tmp_buf = NULL;
2970 #endif /* (!defined(DISABLE_TLS) || !defined(DISABLE_SIGN)) */
2971 /* central list of recognized configuration keywords
2972 * and an address for their values as strings */
2973 const struct config_keywords {
2974 const char *keyword;
2975 char **variable;
2976 } config_keywords[] = {
2977 #ifndef DISABLE_TLS
2978 /* TLS settings */
2979 {"tls_ca", &tls_opt.CAfile},
2980 {"tls_cadir", &tls_opt.CAdir},
2981 {"tls_cert", &tls_opt.certfile},
2982 {"tls_key", &tls_opt.keyfile},
2983 {"tls_verify", &tls_opt.x509verify},
2984 {"tls_bindport", &tls_opt.bindport},
2985 {"tls_bindhost", &tls_opt.bindhost},
2986 {"tls_server", &tls_opt.server},
2987 {"tls_gen_cert", &tls_opt.gen_cert},
2988 /* special cases in parsing */
2989 {"tls_allow_fingerprints",&tmp_buf},
2990 {"tls_allow_clientcerts", &tmp_buf},
2991 /* buffer settings */
2992 {"tls_queue_length", &TypeInfo[F_TLS].queue_length_string},
2993 {"tls_queue_size", &TypeInfo[F_TLS].queue_size_string},
2994 #endif /* !DISABLE_TLS */
2995 {"file_queue_length", &TypeInfo[F_FILE].queue_length_string},
2996 {"pipe_queue_length", &TypeInfo[F_PIPE].queue_length_string},
2997 {"file_queue_size", &TypeInfo[F_FILE].queue_size_string},
2998 {"pipe_queue_size", &TypeInfo[F_PIPE].queue_size_string},
2999 #ifndef DISABLE_SIGN
3000 /* syslog-sign setting */
3001 {"sign_sg", &sign_sg_str},
3002 /* also special case in parsing */
3003 {"sign_delim_sg2", &tmp_buf},
3004 #endif /* !DISABLE_SIGN */
3005 };
3006
3007 DPRINTF(D_CALL, "read_config_file()\n");
3008
3009 /* free all previous config options */
3010 for (i = 0; i < A_CNT(TypeInfo); i++) {
3011 if (TypeInfo[i].queue_length_string
3012 && TypeInfo[i].queue_length_string
3013 != TypeInfo[i].default_length_string) {
3014 FREEPTR(TypeInfo[i].queue_length_string);
3015 TypeInfo[i].queue_length_string =
3016 strdup(TypeInfo[i].default_length_string);
3017 }
3018 if (TypeInfo[i].queue_size_string
3019 && TypeInfo[i].queue_size_string
3020 != TypeInfo[i].default_size_string) {
3021 FREEPTR(TypeInfo[i].queue_size_string);
3022 TypeInfo[i].queue_size_string =
3023 strdup(TypeInfo[i].default_size_string);
3024 }
3025 }
3026 for (i = 0; i < A_CNT(config_keywords); i++)
3027 FREEPTR(*config_keywords[i].variable);
3028 /*
3029 * global settings
3030 */
3031 while (fgets(cline, sizeof(cline), cf) != NULL) {
3032 linenum++;
3033 for (p = cline; isspace((unsigned char)*p); ++p)
3034 continue;
3035 if ((*p == '\0') || (*p == '#'))
3036 continue;
3037
3038 for (i = 0; i < A_CNT(config_keywords); i++) {
3039 if (copy_config_value(config_keywords[i].keyword,
3040 config_keywords[i].variable, &p, ConfFile,
3041 linenum)) {
3042 DPRINTF((D_PARSE|D_MEM),
3043 "found option %s, saved @%p\n",
3044 config_keywords[i].keyword,
3045 *config_keywords[i].variable);
3046 #ifndef DISABLE_SIGN
3047 if (!strcmp("sign_delim_sg2",
3048 config_keywords[i].keyword))
3049 do {
3050 store_sign_delim_sg2(tmp_buf);
3051 } while (copy_config_value_word(
3052 &tmp_buf, &p));
3053
3054 #endif /* !DISABLE_SIGN */
3055
3056 #ifndef DISABLE_TLS
3057 /* special cases with multiple parameters */
3058 if (!strcmp("tls_allow_fingerprints",
3059 config_keywords[i].keyword))
3060 credhead = &tls_opt.fprint_head;
3061 else if (!strcmp("tls_allow_clientcerts",
3062 config_keywords[i].keyword))
3063 credhead = &tls_opt.cert_head;
3064
3065 if (credhead) do {
3066 if(!(cred = malloc(sizeof(*cred)))) {
3067 logerror("Unable to "
3068 "allocate memory");
3069 break;
3070 }
3071 cred->data = tmp_buf;
3072 tmp_buf = NULL;
3073 SLIST_INSERT_HEAD(credhead,
3074 cred, entries);
3075 } while /* additional values? */
3076 (copy_config_value_word(&tmp_buf, &p));
3077 credhead = NULL;
3078 break;
3079 #endif /* !DISABLE_TLS */
3080 }
3081 }
3082 }
3083 /* convert strings to integer values */
3084 for (i = 0; i < A_CNT(TypeInfo); i++) {
3085 if (!TypeInfo[i].queue_length_string
3086 || dehumanize_number(TypeInfo[i].queue_length_string,
3087 &TypeInfo[i].queue_length) == -1)
3088 TypeInfo[i].queue_length = strtol(
3089 TypeInfo[i].default_length_string, NULL, 10);
3090 if (!TypeInfo[i].queue_size_string
3091 || dehumanize_number(TypeInfo[i].queue_size_string,
3092 &TypeInfo[i].queue_size) == -1)
3093 TypeInfo[i].queue_size = strtol(
3094 TypeInfo[i].default_size_string, NULL, 10);
3095 }
3096
3097 #ifndef DISABLE_SIGN
3098 if (sign_sg_str) {
3099 if (sign_sg_str[1] == '\0'
3100 && (sign_sg_str[0] == '0' || sign_sg_str[0] == '1'
3101 || sign_sg_str[0] == '2' || sign_sg_str[0] == '3'))
3102 GlobalSign.sg = sign_sg_str[0] - '0';
3103 else {
3104 GlobalSign.sg = SIGN_SG;
3105 DPRINTF(D_MISC, "Invalid sign_sg value `%s', "
3106 "use default value `%d'\n",
3107 sign_sg_str, GlobalSign.sg);
3108 }
3109 } else /* disable syslog-sign */
3110 GlobalSign.sg = -1;
3111 #endif /* !DISABLE_SIGN */
3112
3113 rewind(cf);
3114 linenum = 0;
3115 /*
3116 * Foreach line in the conf table, open that file.
3117 */
3118 f = NULL;
3119 nextp = &f;
3120
3121 strcpy(prog, "*");
3122 strcpy(host, "*");
3123 while (fgets(cline, sizeof(cline), cf) != NULL) {
3124 linenum++;
3125 found_keyword = false;
3126 /*
3127 * check for end-of-section, comments, strip off trailing
3128 * spaces and newline character. #!prog is treated specially:
3129 * following lines apply only to that program.
3130 */
3131 for (p = cline; isspace((unsigned char)*p); ++p)
3132 continue;
3133 if (*p == '\0')
3134 continue;
3135 if (*p == '#') {
3136 p++;
3137 if (*p != '!' && *p != '+' && *p != '-')
3138 continue;
3139 }
3140
3141 for (i = 0; i < A_CNT(config_keywords); i++) {
3142 if (!strncasecmp(p, config_keywords[i].keyword,
3143 strlen(config_keywords[i].keyword))) {
3144 DPRINTF(D_PARSE,
3145 "skip cline %zu with keyword %s\n",
3146 linenum, config_keywords[i].keyword);
3147 found_keyword = true;
3148 }
3149 }
3150 if (found_keyword)
3151 continue;
3152
3153 if (*p == '+' || *p == '-') {
3154 host[0] = *p++;
3155 while (isspace((unsigned char)*p))
3156 p++;
3157 if (*p == '\0' || *p == '*') {
3158 strcpy(host, "*");
3159 continue;
3160 }
3161 /* the +hostname expression will continue
3162 * to use the LocalHostName, not the FQDN */
3163 for (i = 1; i < MAXHOSTNAMELEN - 1; i++) {
3164 if (*p == '@') {
3165 (void)strncpy(&host[i], LocalHostName,
3166 sizeof(host) - 1 - i);
3167 host[sizeof(host) - 1] = '\0';
3168 i = strlen(host) - 1;
3169 p++;
3170 continue;
3171 }
3172 if (!isalnum((unsigned char)*p) &&
3173 *p != '.' && *p != '-' && *p != ',')
3174 break;
3175 host[i] = *p++;
3176 }
3177 host[i] = '\0';
3178 continue;
3179 }
3180 if (*p == '!') {
3181 p++;
3182 while (isspace((unsigned char)*p))
3183 p++;
3184 if (*p == '\0' || *p == '*') {
3185 strcpy(prog, "*");
3186 continue;
3187 }
3188 for (i = 0; i < NAME_MAX; i++) {
3189 if (!isprint((unsigned char)p[i]))
3190 break;
3191 prog[i] = p[i];
3192 }
3193 prog[i] = '\0';
3194 continue;
3195 }
3196 for (q = strchr(cline, '\0'); isspace((unsigned char)*--q);)
3197 continue;
3198 *++q = '\0';
3199 if ((f = calloc(1, sizeof(*f))) == NULL) {
3200 logerror("alloc failed");
3201 die(0, 0, NULL);
3202 }
3203 if (!*f_ptr) *f_ptr = f; /* return first node */
3204 *nextp = f;
3205 nextp = &f->f_next;
3206 cfline(linenum, cline, f, prog, host);
3207 }
3208 }
3209
3210 /*
3211 * INIT -- Initialize syslogd from configuration table
3212 */
3213 void
3214 /*ARGSUSED*/
3215 init(int fd, short event, void *ev)
3216 {
3217 FILE *cf;
3218 size_t i;
3219 struct filed *f, *newf, **nextp, *f2;
3220 char *p;
3221 sigset_t newmask, omask;
3222 char *tls_status_msg = NULL;
3223 #ifndef DISABLE_TLS
3224 struct peer_cred *cred = NULL;
3225 #endif /* !DISABLE_TLS */
3226
3227 /* prevent recursive signals */
3228 BLOCK_SIGNALS(omask, newmask);
3229
3230 DPRINTF((D_EVENT|D_CALL), "init\n");
3231
3232 /*
3233 * be careful about dependencies and order of actions:
3234 * 1. flush buffer queues
3235 * 2. flush -sign SBs
3236 * 3. flush/delete buffer queue again, in case an SB got there
3237 * 4. close files/connections
3238 */
3239
3240 /*
3241 * flush any pending output
3242 */
3243 for (f = Files; f != NULL; f = f->f_next) {
3244 /* flush any pending output */
3245 if (f->f_prevcount)
3246 fprintlog(f, NULL, NULL);
3247 SEND_QUEUE(f);
3248 }
3249 /* some actions only on SIGHUP and not on first start */
3250 if (Initialized) {
3251 #ifndef DISABLE_SIGN
3252 sign_global_free();
3253 #endif /* !DISABLE_SIGN */
3254 #ifndef DISABLE_TLS
3255 free_incoming_tls_sockets();
3256 #endif /* !DISABLE_TLS */
3257 Initialized = 0;
3258 }
3259 /*
3260 * Close all open log files.
3261 */
3262 for (f = Files; f != NULL; f = f->f_next) {
3263 switch (f->f_type) {
3264 case F_FILE:
3265 case F_TTY:
3266 case F_CONSOLE:
3267 (void)close(f->f_file);
3268 break;
3269 case F_PIPE:
3270 if (f->f_un.f_pipe.f_pid > 0) {
3271 (void)close(f->f_file);
3272 deadq_enter(f->f_un.f_pipe.f_pid,
3273 f->f_un.f_pipe.f_pname);
3274 }
3275 f->f_un.f_pipe.f_pid = 0;
3276 break;
3277 case F_FORW:
3278 if (f->f_un.f_forw.f_addr)
3279 freeaddrinfo(f->f_un.f_forw.f_addr);
3280 break;
3281 #ifndef DISABLE_TLS
3282 case F_TLS:
3283 free_tls_sslptr(f->f_un.f_tls.tls_conn);
3284 break;
3285 #endif /* !DISABLE_TLS */
3286 }
3287 }
3288
3289 /*
3290 * Close all open UDP sockets
3291 */
3292 if (finet) {
3293 for (i = 0; i < finet->fd; i++) {
3294 if (close(finet[i+1].fd) < 0) {
3295 logerror("close() failed");
3296 die(0, 0, NULL);
3297 }
3298 DEL_EVENT(finet[i+1].ev);
3299 FREEPTR(finet[i+1].ev);
3300 }
3301 FREEPTR(finet);
3302 }
3303
3304 /* get FQDN and hostname/domain */
3305 FREEPTR(oldLocalFQDN);
3306 oldLocalFQDN = LocalFQDN;
3307 LocalFQDN = getLocalFQDN();
3308 if ((p = strchr(LocalFQDN, '.')) != NULL)
3309 (void)strlcpy(LocalHostName, LocalFQDN, 1+p-LocalFQDN);
3310 else
3311 (void)strlcpy(LocalHostName, LocalFQDN, sizeof(LocalHostName));
3312
3313 /*
3314 * Reset counter of forwarding actions
3315 */
3316
3317 NumForwards=0;
3318
3319 /* new destination list to replace Files */
3320 newf = NULL;
3321 nextp = &newf;
3322
3323 /* open the configuration file */
3324 if ((cf = fopen(ConfFile, "r")) == NULL) {
3325 DPRINTF(D_FILE, "Cannot open `%s'\n", ConfFile);
3326 *nextp = (struct filed *)calloc(1, sizeof(*f));
3327 cfline(0, "*.ERR\t/dev/console", *nextp, "*", "*");
3328 (*nextp)->f_next = (struct filed *)calloc(1, sizeof(*f));
3329 cfline(0, "*.PANIC\t*", (*nextp)->f_next, "*", "*");
3330 Initialized = 1;
3331 RESTORE_SIGNALS(omask);
3332 return;
3333 }
3334
3335 #ifndef DISABLE_TLS
3336 /* init with new TLS_CTX
3337 * as far as I see one cannot change the cert/key of an existing CTX
3338 */
3339 FREE_SSL_CTX(tls_opt.global_TLS_CTX);
3340
3341 free_cred_SLIST(&tls_opt.cert_head);
3342 free_cred_SLIST(&tls_opt.fprint_head);
3343 #endif /* !DISABLE_TLS */
3344
3345 /* read and close configuration file */
3346 read_config_file(cf, &newf);
3347 newf = *nextp;
3348 (void)fclose(cf);
3349 DPRINTF(D_MISC, "read_config_file() returned newf=%p\n", newf);
3350
3351 #define MOVE_QUEUE(dst, src) do { \
3352 struct buf_queue *buf; \
3353 STAILQ_CONCAT(&dst->f_qhead, &src->f_qhead); \
3354 STAILQ_FOREACH(buf, &dst->f_qhead, entries) { \
3355 dst->f_qelements++; \
3356 dst->f_qsize += buf_queue_obj_size(buf); \
3357 } \
3358 src->f_qsize = 0; \
3359 src->f_qelements = 0; \
3360 } while (/*CONSTCOND*/0)
3361
3362 /*
3363 * Free old log files.
3364 */
3365 for (f = Files; f != NULL; f = f->f_next) {
3366 /* check if a new logfile is equal, if so pass the queue */
3367 for (f2 = newf; f2 != NULL; f2 = f2->f_next) {
3368 if (f->f_type == f2->f_type
3369 && ((f->f_type == F_PIPE
3370 && !strcmp(f->f_un.f_pipe.f_pname,
3371 f2->f_un.f_pipe.f_pname))
3372 #ifndef DISABLE_TLS
3373 || (f->f_type == F_TLS
3374 && !strcmp(f->f_un.f_tls.tls_conn->hostname,
3375 f2->f_un.f_tls.tls_conn->hostname)
3376 && !strcmp(f->f_un.f_tls.tls_conn->port,
3377 f2->f_un.f_tls.tls_conn->port))
3378 #endif /* !DISABLE_TLS */
3379 || (f->f_type == F_FORW
3380 && !strcmp(f->f_un.f_forw.f_hname,
3381 f2->f_un.f_forw.f_hname)))) {
3382 DPRINTF(D_BUFFER, "move queue from f@%p "
3383 "to f2@%p\n", f, f2);
3384 MOVE_QUEUE(f2, f);
3385 }
3386 }
3387 message_queue_freeall(f);
3388 DELREF(f->f_prevmsg);
3389 #ifndef DISABLE_TLS
3390 if (f->f_type == F_TLS)
3391 free_tls_conn(f->f_un.f_tls.tls_conn);
3392 #endif /* !DISABLE_TLS */
3393 FREEPTR(f->f_program);
3394 FREEPTR(f->f_host);
3395 DEL_EVENT(f->f_sq_event);
3396 free((char *)f);
3397 }
3398 Files = newf;
3399 Initialized = 1;
3400
3401 if (Debug) {
3402 for (f = Files; f; f = f->f_next) {
3403 for (i = 0; i <= LOG_NFACILITIES; i++)
3404 if (f->f_pmask[i] == INTERNAL_NOPRI)
3405 printf("X ");
3406 else
3407 printf("%d ", f->f_pmask[i]);
3408 printf("%s: ", TypeInfo[f->f_type].name);
3409 switch (f->f_type) {
3410 case F_FILE:
3411 case F_TTY:
3412 case F_CONSOLE:
3413 printf("%s", f->f_un.f_fname);
3414 break;
3415
3416 case F_FORW:
3417 printf("%s", f->f_un.f_forw.f_hname);
3418 break;
3419 #ifndef DISABLE_TLS
3420 case F_TLS:
3421 printf("[%s]", f->f_un.f_tls.tls_conn->hostname);
3422 break;
3423 #endif /* !DISABLE_TLS */
3424 case F_PIPE:
3425 printf("%s", f->f_un.f_pipe.f_pname);
3426 break;
3427
3428 case F_USERS:
3429 for (i = 0;
3430 i < MAXUNAMES && *f->f_un.f_uname[i]; i++)
3431 printf("%s, ", f->f_un.f_uname[i]);
3432 break;
3433 }
3434 if (f->f_program != NULL)
3435 printf(" (%s)", f->f_program);
3436 printf("\n");
3437 }
3438 }
3439
3440 finet = socksetup(PF_UNSPEC, bindhostname);
3441 if (finet) {
3442 if (SecureMode) {
3443 for (i = 0; i < finet->fd; i++) {
3444 if (shutdown(finet[i+1].fd, SHUT_RD) < 0) {
3445 logerror("shutdown() failed");
3446 die(0, 0, NULL);
3447 }
3448 }
3449 } else
3450 DPRINTF(D_NET, "Listening on inet and/or inet6 socket\n");
3451 DPRINTF(D_NET, "Sending on inet and/or inet6 socket\n");
3452 }
3453
3454 #ifndef DISABLE_TLS
3455 /* TLS setup -- after all local destinations opened */
3456 DPRINTF(D_PARSE, "Parsed options: tls_ca: %s, tls_cadir: %s, "
3457 "tls_cert: %s, tls_key: %s, tls_verify: %s, "
3458 "bind: %s:%s, max. queue_lengths: %"
3459 PRId64 ", %" PRId64 ", %" PRId64 ", "
3460 "max. queue_sizes: %"
3461 PRId64 ", %" PRId64 ", %" PRId64 "\n",
3462 tls_opt.CAfile, tls_opt.CAdir,
3463 tls_opt.certfile, tls_opt.keyfile, tls_opt.x509verify,
3464 tls_opt.bindhost, tls_opt.bindport,
3465 TypeInfo[F_TLS].queue_length, TypeInfo[F_FILE].queue_length,
3466 TypeInfo[F_PIPE].queue_length,
3467 TypeInfo[F_TLS].queue_size, TypeInfo[F_FILE].queue_size,
3468 TypeInfo[F_PIPE].queue_size);
3469 SLIST_FOREACH(cred, &tls_opt.cert_head, entries) {
3470 DPRINTF(D_PARSE, "Accepting peer certificate "
3471 "from file: \"%s\"\n", cred->data);
3472 }
3473 SLIST_FOREACH(cred, &tls_opt.fprint_head, entries) {
3474 DPRINTF(D_PARSE, "Accepting peer certificate with "
3475 "fingerprint: \"%s\"\n", cred->data);
3476 }
3477
3478 /* Note: The order of initialization is important because syslog-sign
3479 * should use the TLS cert for signing. -- So we check first if TLS
3480 * will be used and initialize it before starting -sign.
3481 *
3482 * This means that if we are a client without TLS destinations TLS
3483 * will not be initialized and syslog-sign will generate a new key.
3484 * -- Even if the user has set a usable tls_cert.
3485 * Is this the expected behaviour? The alternative would be to always
3486 * initialize the TLS structures, even if they will not be needed
3487 * (or only needed to read the DSA key for -sign).
3488 */
3489
3490 /* Initialize TLS only if used */
3491 if (tls_opt.server)
3492 tls_status_msg = init_global_TLS_CTX();
3493 else
3494 for (f = Files; f; f = f->f_next) {
3495 if (f->f_type != F_TLS)
3496 continue;
3497 tls_status_msg = init_global_TLS_CTX();
3498 break;
3499 }
3500
3501 #endif /* !DISABLE_TLS */
3502
3503 #ifndef DISABLE_SIGN
3504 /* only initialize -sign if actually used */
3505 if (GlobalSign.sg == 0 || GlobalSign.sg == 1 || GlobalSign.sg == 2)
3506 (void)sign_global_init(Files);
3507 else if (GlobalSign.sg == 3)
3508 for (f = Files; f; f = f->f_next)
3509 if (f->f_flags & FFLAG_SIGN) {
3510 (void)sign_global_init(Files);
3511 break;
3512 }
3513 #endif /* !DISABLE_SIGN */
3514
3515 #ifndef DISABLE_TLS
3516 if (tls_status_msg) {
3517 loginfo(tls_status_msg);
3518 free(tls_status_msg);
3519 }
3520 DPRINTF((D_NET|D_TLS), "Preparing sockets for TLS\n");
3521 TLS_Listen_Set =
3522 socksetup_tls(PF_UNSPEC, tls_opt.bindhost, tls_opt.bindport);
3523
3524 for (f = Files; f; f = f->f_next) {
3525 if (f->f_type != F_TLS)
3526 continue;
3527 if (!tls_connect(f->f_un.f_tls.tls_conn)) {
3528 logerror("Unable to connect to TLS server %s",
3529 f->f_un.f_tls.tls_conn->hostname);
3530 /* Reconnect after x seconds */
3531 schedule_event(&f->f_un.f_tls.tls_conn->event,
3532 &((struct timeval){TLS_RECONNECT_SEC, 0}),
3533 tls_reconnect, f->f_un.f_tls.tls_conn);
3534 }
3535 }
3536 #endif /* !DISABLE_TLS */
3537
3538 loginfo("restart");
3539 /*
3540 * Log a change in hostname, but only on a restart (we detect this
3541 * by checking to see if we're passed a kevent).
3542 */
3543 if (oldLocalFQDN && strcmp(oldLocalFQDN, LocalFQDN) != 0)
3544 loginfo("host name changed, \"%s\" to \"%s\"",
3545 oldLocalFQDN, LocalFQDN);
3546
3547 RESTORE_SIGNALS(omask);
3548 }
3549
3550 /*
3551 * Crack a configuration file line
3552 */
3553 void
3554 cfline(size_t linenum, const char *line, struct filed *f, const char *prog,
3555 const char *host)
3556 {
3557 struct addrinfo hints, *res;
3558 int error, i, pri, syncfile;
3559 const char *p, *q;
3560 char *bp;
3561 char buf[MAXLINE];
3562
3563 DPRINTF((D_CALL|D_PARSE),
3564 "cfline(%zu, \"%s\", f, \"%s\", \"%s\")\n",
3565 linenum, line, prog, host);
3566
3567 errno = 0; /* keep strerror() stuff out of logerror messages */
3568
3569 /* clear out file entry */
3570 memset(f, 0, sizeof(*f));
3571 for (i = 0; i <= LOG_NFACILITIES; i++)
3572 f->f_pmask[i] = INTERNAL_NOPRI;
3573 STAILQ_INIT(&f->f_qhead);
3574
3575 /*
3576 * There should not be any space before the log facility.
3577 * Check this is okay, complain and fix if it is not.
3578 */
3579 q = line;
3580 if (isblank((unsigned char)*line)) {
3581 errno = 0;
3582 logerror("Warning: `%s' space or tab before the log facility",
3583 line);
3584 /* Fix: strip all spaces/tabs before the log facility */
3585 while (*q++ && isblank((unsigned char)*q))
3586 /* skip blanks */;
3587 line = q;
3588 }
3589
3590 /*
3591 * q is now at the first char of the log facility
3592 * There should be at least one tab after the log facility
3593 * Check this is okay, and complain and fix if it is not.
3594 */
3595 q = line + strlen(line);
3596 while (!isblank((unsigned char)*q) && (q != line))
3597 q--;
3598 if ((q == line) && strlen(line)) {
3599 /* No tabs or space in a non empty line: complain */
3600 errno = 0;
3601 logerror(
3602 "Error: `%s' log facility or log target missing",
3603 line);
3604 return;
3605 }
3606
3607 /* save host name, if any */
3608 if (*host == '*')
3609 f->f_host = NULL;
3610 else {
3611 f->f_host = strdup(host);
3612 trim_anydomain(f->f_host);
3613 }
3614
3615 /* save program name, if any */
3616 if (*prog == '*')
3617 f->f_program = NULL;
3618 else
3619 f->f_program = strdup(prog);
3620
3621 /* scan through the list of selectors */
3622 for (p = line; *p && !isblank((unsigned char)*p);) {
3623 int pri_done, pri_cmp, pri_invert;
3624
3625 /* find the end of this facility name list */
3626 for (q = p; *q && !isblank((unsigned char)*q) && *q++ != '.'; )
3627 continue;
3628
3629 /* get the priority comparison */
3630 pri_cmp = 0;
3631 pri_done = 0;
3632 pri_invert = 0;
3633 if (*q == '!') {
3634 pri_invert = 1;
3635 q++;
3636 }
3637 while (! pri_done) {
3638 switch (*q) {
3639 case '<':
3640 pri_cmp = PRI_LT;
3641 q++;
3642 break;
3643 case '=':
3644 pri_cmp = PRI_EQ;
3645 q++;
3646 break;
3647 case '>':
3648 pri_cmp = PRI_GT;
3649 q++;
3650 break;
3651 default:
3652 pri_done = 1;
3653 break;
3654 }
3655 }
3656
3657 /* collect priority name */
3658 for (bp = buf; *q && !strchr("\t ,;", *q); )
3659 *bp++ = *q++;
3660 *bp = '\0';
3661
3662 /* skip cruft */
3663 while (strchr(",;", *q))
3664 q++;
3665
3666 /* decode priority name */
3667 if (*buf == '*') {
3668 pri = LOG_PRIMASK + 1;
3669 pri_cmp = PRI_LT | PRI_EQ | PRI_GT;
3670 } else {
3671 pri = decode(buf, prioritynames);
3672 if (pri < 0) {
3673 errno = 0;
3674 logerror("Unknown priority name `%s'", buf);
3675 return;
3676 }
3677 }
3678 if (pri_cmp == 0)
3679 pri_cmp = UniquePriority ? PRI_EQ
3680 : PRI_EQ | PRI_GT;
3681 if (pri_invert)
3682 pri_cmp ^= PRI_LT | PRI_EQ | PRI_GT;
3683
3684 /* scan facilities */
3685 while (*p && !strchr("\t .;", *p)) {
3686 for (bp = buf; *p && !strchr("\t ,;.", *p); )
3687 *bp++ = *p++;
3688 *bp = '\0';
3689 if (*buf == '*')
3690 for (i = 0; i < LOG_NFACILITIES; i++) {
3691 f->f_pmask[i] = pri;
3692 f->f_pcmp[i] = pri_cmp;
3693 }
3694 else {
3695 i = decode(buf, facilitynames);
3696 if (i < 0) {
3697 errno = 0;
3698 logerror("Unknown facility name `%s'",
3699 buf);
3700 return;
3701 }
3702 f->f_pmask[i >> 3] = pri;
3703 f->f_pcmp[i >> 3] = pri_cmp;
3704 }
3705 while (*p == ',' || *p == ' ')
3706 p++;
3707 }
3708
3709 p = q;
3710 }
3711
3712 /* skip to action part */
3713 while (isblank((unsigned char)*p))
3714 p++;
3715
3716 /*
3717 * should this be "#ifndef DISABLE_SIGN" or is it a general option?
3718 * '+' before file destination: write with PRI field for later
3719 * verification
3720 */
3721 if (*p == '+') {
3722 f->f_flags |= FFLAG_FULL;
3723 p++;
3724 }
3725 if (*p == '-') {
3726 syncfile = 0;
3727 p++;
3728 } else
3729 syncfile = 1;
3730
3731 switch (*p) {
3732 case '@':
3733 #ifndef DISABLE_SIGN
3734 if (GlobalSign.sg == 3)
3735 f->f_flags |= FFLAG_SIGN;
3736 #endif /* !DISABLE_SIGN */
3737 #ifndef DISABLE_TLS
3738 if (*(p+1) == '[') {
3739 /* TLS destination */
3740 if (!parse_tls_destination(p, f, linenum)) {
3741 logerror("Unable to parse action %s", p);
3742 break;
3743 }
3744 f->f_type = F_TLS;
3745 break;
3746 }
3747 #endif /* !DISABLE_TLS */
3748 (void)strlcpy(f->f_un.f_forw.f_hname, ++p,
3749 sizeof(f->f_un.f_forw.f_hname));
3750 memset(&hints, 0, sizeof(hints));
3751 hints.ai_family = AF_UNSPEC;
3752 hints.ai_socktype = SOCK_DGRAM;
3753 hints.ai_protocol = 0;
3754 error = getaddrinfo(f->f_un.f_forw.f_hname, "syslog", &hints,
3755 &res);
3756 if (error) {
3757 logerror(gai_strerror(error));
3758 break;
3759 }
3760 f->f_un.f_forw.f_addr = res;
3761 f->f_type = F_FORW;
3762 NumForwards++;
3763 break;
3764
3765 case '/':
3766 #ifndef DISABLE_SIGN
3767 if (GlobalSign.sg == 3)
3768 f->f_flags |= FFLAG_SIGN;
3769 #endif /* !DISABLE_SIGN */
3770 (void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname));
3771 if ((f->f_file = open(p, O_WRONLY|O_APPEND, 0)) < 0) {
3772 f->f_type = F_UNUSED;
3773 logerror(p);
3774 break;
3775 }
3776 if (syncfile)
3777 f->f_flags |= FFLAG_SYNC;
3778 if (isatty(f->f_file))
3779 f->f_type = F_TTY;
3780 else
3781 f->f_type = F_FILE;
3782 if (strcmp(p, ctty) == 0)
3783 f->f_type = F_CONSOLE;
3784 break;
3785
3786 case '|':
3787 if (GlobalSign.sg == 3)
3788 f->f_flags |= FFLAG_SIGN;
3789 f->f_un.f_pipe.f_pid = 0;
3790 (void) strlcpy(f->f_un.f_pipe.f_pname, p + 1,
3791 sizeof(f->f_un.f_pipe.f_pname));
3792 f->f_type = F_PIPE;
3793 break;
3794
3795 case '*':
3796 f->f_type = F_WALL;
3797 break;
3798
3799 default:
3800 for (i = 0; i < MAXUNAMES && *p; i++) {
3801 for (q = p; *q && *q != ','; )
3802 q++;
3803 (void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE);
3804 if ((q - p) > UT_NAMESIZE)
3805 f->f_un.f_uname[i][UT_NAMESIZE] = '\0';
3806 else
3807 f->f_un.f_uname[i][q - p] = '\0';
3808 while (*q == ',' || *q == ' ')
3809 q++;
3810 p = q;
3811 }
3812 f->f_type = F_USERS;
3813 break;
3814 }
3815 }
3816
3817
3818 /*
3819 * Decode a symbolic name to a numeric value
3820 */
3821 int
3822 decode(const char *name, CODE *codetab)
3823 {
3824 CODE *c;
3825 char *p, buf[40];
3826
3827 if (isdigit((unsigned char)*name))
3828 return atoi(name);
3829
3830 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) {
3831 if (isupper((unsigned char)*name))
3832 *p = tolower((unsigned char)*name);
3833 else
3834 *p = *name;
3835 }
3836 *p = '\0';
3837 for (c = codetab; c->c_name; c++)
3838 if (!strcmp(buf, c->c_name))
3839 return c->c_val;
3840
3841 return -1;
3842 }
3843
3844 /*
3845 * Retrieve the size of the kernel message buffer, via sysctl.
3846 */
3847 int
3848 getmsgbufsize(void)
3849 {
3850 #ifdef __NetBSD_Version__
3851 int msgbufsize, mib[2];
3852 size_t size;
3853
3854 mib[0] = CTL_KERN;
3855 mib[1] = KERN_MSGBUFSIZE;
3856 size = sizeof msgbufsize;
3857 if (sysctl(mib, 2, &msgbufsize, &size, NULL, 0) == -1) {
3858 DPRINTF(D_MISC, "Couldn't get kern.msgbufsize\n");
3859 return 0;
3860 }
3861 return msgbufsize;
3862 #else
3863 return MAXLINE;
3864 #endif /* __NetBSD_Version__ */
3865 }
3866
3867 /*
3868 * Retrieve the hostname, via sysctl.
3869 */
3870 char *
3871 getLocalFQDN(void)
3872 {
3873 int mib[2];
3874 char *hostname;
3875 size_t len;
3876
3877 mib[0] = CTL_KERN;
3878 mib[1] = KERN_HOSTNAME;
3879 sysctl(mib, 2, NULL, &len, NULL, 0);
3880
3881 if (!(hostname = malloc(len))) {
3882 logerror("Unable to allocate memory");
3883 die(0,0,NULL);
3884 } else if (sysctl(mib, 2, hostname, &len, NULL, 0) == -1) {
3885 DPRINTF(D_MISC, "Couldn't get kern.hostname\n");
3886 (void)gethostname(hostname, sizeof(len));
3887 }
3888 return hostname;
3889 }
3890
3891 struct socketEvent *
3892 socksetup(int af, const char *hostname)
3893 {
3894 struct addrinfo hints, *res, *r;
3895 int error, maxs;
3896 int on = 1;
3897 struct socketEvent *s, *socks;
3898
3899 if(SecureMode && !NumForwards)
3900 return NULL;
3901
3902 memset(&hints, 0, sizeof(hints));
3903 hints.ai_flags = AI_PASSIVE;
3904 hints.ai_family = af;
3905 hints.ai_socktype = SOCK_DGRAM;
3906 error = getaddrinfo(hostname, "syslog", &hints, &res);
3907 if (error) {
3908 logerror(gai_strerror(error));
3909 errno = 0;
3910 die(0, 0, NULL);
3911 }
3912
3913 /* Count max number of sockets we may open */
3914 for (maxs = 0, r = res; r; r = r->ai_next, maxs++)
3915 continue;
3916 socks = calloc(maxs+1, sizeof(*socks));
3917 if (!socks) {
3918 logerror("Couldn't allocate memory for sockets");
3919 die(0, 0, NULL);
3920 }
3921
3922 socks->fd = 0; /* num of sockets counter at start of array */
3923 s = socks + 1;
3924 for (r = res; r; r = r->ai_next) {
3925 s->fd = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
3926 if (s->fd < 0) {
3927 logerror("socket() failed");
3928 continue;
3929 }
3930 if (r->ai_family == AF_INET6 && setsockopt(s->fd, IPPROTO_IPV6,
3931 IPV6_V6ONLY, &on, sizeof(on)) < 0) {
3932 logerror("setsockopt(IPV6_V6ONLY) failed");
3933 close(s->fd);
3934 continue;
3935 }
3936
3937 if (!SecureMode) {
3938 if (bind(s->fd, r->ai_addr, r->ai_addrlen) < 0) {
3939 logerror("bind() failed");
3940 close(s->fd);
3941 continue;
3942 }
3943 s->ev = allocev();
3944 event_set(s->ev, s->fd, EV_READ | EV_PERSIST,
3945 dispatch_read_finet, s->ev);
3946 if (event_add(s->ev, NULL) == -1) {
3947 DPRINTF((D_EVENT|D_NET),
3948 "Failure in event_add()\n");
3949 } else {
3950 DPRINTF((D_EVENT|D_NET),
3951 "Listen on UDP port "
3952 "(event@%p)\n", s->ev);
3953 }
3954 }
3955
3956 socks->fd++; /* num counter */
3957 s++;
3958 }
3959
3960 if (res)
3961 freeaddrinfo(res);
3962 if (socks->fd == 0) {
3963 free (socks);
3964 if(Debug)
3965 return NULL;
3966 else
3967 die(0, 0, NULL);
3968 }
3969 return socks;
3970 }
3971
3972 /*
3973 * Fairly similar to popen(3), but returns an open descriptor, as opposed
3974 * to a FILE *.
3975 */
3976 int
3977 p_open(char *prog, pid_t *rpid)
3978 {
3979 static char sh[] = "sh", mc[] = "-c";
3980 int pfd[2], nulldesc, i;
3981 pid_t pid;
3982 char *argv[4]; /* sh -c cmd NULL */
3983 char errmsg[200];
3984
3985 if (pipe(pfd) == -1)
3986 return -1;
3987 if ((nulldesc = open(_PATH_DEVNULL, O_RDWR)) == -1) {
3988 /* We are royally screwed anyway. */
3989 return -1;
3990 }
3991
3992 switch ((pid = fork())) {
3993 case -1:
3994 (void) close(nulldesc);
3995 return -1;
3996
3997 case 0:
3998 argv[0] = sh;
3999 argv[1] = mc;
4000 argv[2] = prog;
4001 argv[3] = NULL;
4002
4003 (void) setsid(); /* avoid catching SIGHUPs. */
4004
4005 /*
4006 * Reset ignored signals to their default behavior.
4007 */
4008 (void)signal(SIGTERM, SIG_DFL);
4009 (void)signal(SIGINT, SIG_DFL);
4010 (void)signal(SIGQUIT, SIG_DFL);
4011 (void)signal(SIGPIPE, SIG_DFL);
4012 (void)signal(SIGHUP, SIG_DFL);
4013
4014 dup2(pfd[0], STDIN_FILENO);
4015 dup2(nulldesc, STDOUT_FILENO);
4016 dup2(nulldesc, STDERR_FILENO);
4017 for (i = getdtablesize(); i > 2; i--)
4018 (void) close(i);
4019
4020 (void) execvp(_PATH_BSHELL, argv);
4021 _exit(255);
4022 }
4023
4024 (void) close(nulldesc);
4025 (void) close(pfd[0]);
4026
4027 /*
4028 * Avoid blocking on a hung pipe. With O_NONBLOCK, we are
4029 * supposed to get an EWOULDBLOCK on writev(2), which is
4030 * caught by the logic above anyway, which will in turn
4031 * close the pipe, and fork a new logging subprocess if
4032 * necessary. The stale subprocess will be killed some
4033 * time later unless it terminated itself due to closing
4034 * its input pipe.
4035 */
4036 if (fcntl(pfd[1], F_SETFL, O_NONBLOCK) == -1) {
4037 /* This is bad. */
4038 (void) snprintf(errmsg, sizeof(errmsg),
4039 "Warning: cannot change pipe to pid %d to "
4040 "non-blocking.", (int) pid);
4041 logerror(errmsg);
4042 }
4043 *rpid = pid;
4044 return pfd[1];
4045 }
4046
4047 void
4048 deadq_enter(pid_t pid, const char *name)
4049 {
4050 dq_t p;
4051 int status;
4052
4053 /*
4054 * Be paranoid: if we can't signal the process, don't enter it
4055 * into the dead queue (perhaps it's already dead). If possible,
4056 * we try to fetch and log the child's status.
4057 */
4058 if (kill(pid, 0) != 0) {
4059 if (waitpid(pid, &status, WNOHANG) > 0)
4060 log_deadchild(pid, status, name);
4061 return;
4062 }
4063
4064 p = malloc(sizeof(*p));
4065 if (p == NULL) {
4066 errno = 0;
4067 logerror("panic: out of memory!");
4068 exit(1);
4069 }
4070
4071 p->dq_pid = pid;
4072 p->dq_timeout = DQ_TIMO_INIT;
4073 TAILQ_INSERT_TAIL(&deadq_head, p, dq_entries);
4074 }
4075
4076 int
4077 deadq_remove(pid_t pid)
4078 {
4079 dq_t q;
4080
4081 for (q = TAILQ_FIRST(&deadq_head); q != NULL;
4082 q = TAILQ_NEXT(q, dq_entries)) {
4083 if (q->dq_pid == pid) {
4084 TAILQ_REMOVE(&deadq_head, q, dq_entries);
4085 free(q);
4086 return 1;
4087 }
4088 }
4089 return 0;
4090 }
4091
4092 void
4093 log_deadchild(pid_t pid, int status, const char *name)
4094 {
4095 int code;
4096 char buf[256];
4097 const char *reason;
4098
4099 /* Keep strerror() struff out of logerror messages. */
4100 errno = 0;
4101 if (WIFSIGNALED(status)) {
4102 reason = "due to signal";
4103 code = WTERMSIG(status);
4104 } else {
4105 reason = "with status";
4106 code = WEXITSTATUS(status);
4107 if (code == 0)
4108 return;
4109 }
4110 (void) snprintf(buf, sizeof(buf),
4111 "Logging subprocess %d (%s) exited %s %d.",
4112 pid, name, reason, code);
4113 logerror(buf);
4114 }
4115
4116 struct event *
4117 allocev(void)
4118 {
4119 struct event *ev;
4120
4121 if (!(ev = calloc(1, sizeof(*ev))))
4122 logerror("Unable to allocate memory");
4123 return ev;
4124 }
4125
4126 /* *ev is allocated if necessary */
4127 void
4128 schedule_event(struct event **ev, struct timeval *tv,
4129 void (*cb)(int, short, void *), void *arg)
4130 {
4131 if (!*ev && !(*ev = allocev())) {
4132 return;
4133 }
4134 event_set(*ev, 0, 0, cb, arg);
4135 DPRINTF(D_EVENT, "event_add(%s@%p)\n", "schedule_ev", *ev); \
4136 if (event_add(*ev, tv) == -1) {
4137 DPRINTF(D_EVENT, "Failure in event_add()\n");
4138 }
4139 }
4140
4141 #ifndef DISABLE_TLS
4142 /* abbreviation for freeing credential lists */
4143 void
4144 free_cred_SLIST(struct peer_cred_head *head)
4145 {
4146 struct peer_cred *cred;
4147
4148 while (!SLIST_EMPTY(head)) {
4149 cred = SLIST_FIRST(head);
4150 SLIST_REMOVE_HEAD(head, entries);
4151 FREEPTR(cred->data);
4152 free(cred);
4153 }
4154 }
4155 #endif /* !DISABLE_TLS */
4156
4157 /*
4158 * send message queue after reconnect
4159 */
4160 /*ARGSUSED*/
4161 void
4162 send_queue(int fd, short event, void *arg)
4163 {
4164 struct filed *f = (struct filed *) arg;
4165 struct buf_queue *qentry;
4166 #define SQ_CHUNK_SIZE 250
4167 size_t cnt = 0;
4168
4169 if (f->f_type == F_TLS) {
4170 /* use a flag to prevent recursive calls to send_queue() */
4171 if (f->f_un.f_tls.tls_conn->send_queue)
4172 return;
4173 else
4174 f->f_un.f_tls.tls_conn->send_queue = true;
4175 }
4176 DPRINTF((D_DATA|D_CALL), "send_queue(f@%p with %zu msgs, "
4177 "cnt@%p = %zu)\n", f, f->f_qelements, &cnt, cnt);
4178
4179 while ((qentry = STAILQ_FIRST(&f->f_qhead))) {
4180 #ifndef DISABLE_TLS
4181 /* send_queue() might be called with an unconnected destination
4182 * from init() or die() or one message might take longer,
4183 * leaving the connection in state ST_WAITING and thus not
4184 * ready for the next message.
4185 * this check is a shortcut to skip these unnecessary calls */
4186 if (f->f_type == F_TLS
4187 && f->f_un.f_tls.tls_conn->state != ST_TLS_EST) {
4188 DPRINTF(D_TLS, "abort send_queue(cnt@%p = %zu) "
4189 "on TLS connection in state %d\n",
4190 &cnt, cnt, f->f_un.f_tls.tls_conn->state);
4191 return;
4192 }
4193 #endif /* !DISABLE_TLS */
4194 fprintlog(f, qentry->msg, qentry);
4195
4196 /* Sending a long queue can take some time during which
4197 * SIGHUP and SIGALRM are blocked and no events are handled.
4198 * To avoid that we only send SQ_CHUNK_SIZE messages at once
4199 * and then reschedule ourselves to continue. Thus the control
4200 * will return first from all signal-protected functions so a
4201 * possible SIGHUP/SIGALRM is handled and then back to the
4202 * main loop which can handle possible input.
4203 */
4204 if (++cnt >= SQ_CHUNK_SIZE) {
4205 if (!f->f_sq_event) { /* alloc on demand */
4206 f->f_sq_event = allocev();
4207 event_set(f->f_sq_event, 0, 0, send_queue, f);
4208 }
4209 if (event_add(f->f_sq_event, &((struct timeval){0, 1})) == -1) {
4210 DPRINTF(D_EVENT, "Failure in event_add()\n");
4211 }
4212 break;
4213 }
4214 }
4215 if (f->f_type == F_TLS)
4216 f->f_un.f_tls.tls_conn->send_queue = false;
4217 }
4218
4219 /*
4220 * finds the next queue element to delete
4221 *
4222 * has stateful behaviour, before using it call once with reset = true
4223 * after that every call will return one next queue elemen to delete,
4224 * depending on strategy either the oldest or the one with the lowest priority
4225 */
4226 static struct buf_queue *
4227 find_qentry_to_delete(const struct buf_queue_head *head, int strategy,
4228 bool reset)
4229 {
4230 static int pri;
4231 static struct buf_queue *qentry_static;
4232
4233 struct buf_queue *qentry_tmp;
4234
4235 if (reset || STAILQ_EMPTY(head)) {
4236 pri = LOG_DEBUG;
4237 qentry_static = STAILQ_FIRST(head);
4238 return NULL;
4239 }
4240
4241 /* find elements to delete */
4242 if (strategy == PURGE_BY_PRIORITY) {
4243 qentry_tmp = qentry_static;
4244 while ((qentry_tmp = STAILQ_NEXT(qentry_tmp, entries)) != NULL)
4245 {
4246 if (LOG_PRI(qentry_tmp->msg->pri) == pri) {
4247 /* save the successor, because qentry_tmp
4248 * is probably deleted by the caller */
4249 qentry_static = STAILQ_NEXT(qentry_tmp, entries);
4250 return qentry_tmp;
4251 }
4252 }
4253 /* nothing found in while loop --> next pri */
4254 if (--pri)
4255 return find_qentry_to_delete(head, strategy, false);
4256 else
4257 return NULL;
4258 } else /* strategy == PURGE_OLDEST or other value */ {
4259 qentry_tmp = qentry_static;
4260 qentry_static = STAILQ_NEXT(qentry_tmp, entries);
4261 return qentry_tmp; /* is NULL on empty queue */
4262 }
4263 }
4264
4265 /* note on TAILQ: newest message added at TAIL,
4266 * oldest to be removed is FIRST
4267 */
4268 /*
4269 * checks length of a destination's message queue
4270 * if del_entries == 0 then assert queue length is
4271 * less or equal to configured number of queue elements
4272 * otherwise del_entries tells how many entries to delete
4273 *
4274 * returns the number of removed queue elements
4275 * (which not necessarily means free'd messages)
4276 *
4277 * strategy PURGE_OLDEST to delete oldest entry, e.g. after it was resent
4278 * strategy PURGE_BY_PRIORITY to delete messages with lowest priority first,
4279 * this is much slower but might be desirable when unsent messages have
4280 * to be deleted, e.g. in call from domark()
4281 */
4282 size_t
4283 message_queue_purge(struct filed *f, size_t del_entries, int strategy)
4284 {
4285 int removed = 0;
4286 struct buf_queue *qentry = NULL;
4287
4288 DPRINTF((D_CALL|D_BUFFER), "purge_message_queue(%p, %zu, %d) with "
4289 "f_qelements=%zu and f_qsize=%zu\n",
4290 f, del_entries, strategy,
4291 f->f_qelements, f->f_qsize);
4292
4293 /* reset state */
4294 (void)find_qentry_to_delete(&f->f_qhead, strategy, true);
4295
4296 while (removed < del_entries
4297 || (TypeInfo[f->f_type].queue_length != -1
4298 && TypeInfo[f->f_type].queue_length > f->f_qelements)
4299 || (TypeInfo[f->f_type].queue_size != -1
4300 && TypeInfo[f->f_type].queue_size > f->f_qsize)) {
4301 qentry = find_qentry_to_delete(&f->f_qhead, strategy, 0);
4302 if (message_queue_remove(f, qentry))
4303 removed++;
4304 else
4305 break;
4306 }
4307 return removed;
4308 }
4309
4310 /* run message_queue_purge() for all destinations to free memory */
4311 size_t
4312 message_allqueues_purge(void)
4313 {
4314 size_t sum = 0;
4315 struct filed *f;
4316
4317 for (f = Files; f; f = f->f_next)
4318 sum += message_queue_purge(f,
4319 f->f_qelements/10, PURGE_BY_PRIORITY);
4320
4321 DPRINTF(D_BUFFER,
4322 "message_allqueues_purge(): removed %zu buffer entries\n", sum);
4323 return sum;
4324 }
4325
4326 /* run message_queue_purge() for all destinations to check limits */
4327 size_t
4328 message_allqueues_check(void)
4329 {
4330 size_t sum = 0;
4331 struct filed *f;
4332
4333 for (f = Files; f; f = f->f_next)
4334 sum += message_queue_purge(f, 0, PURGE_BY_PRIORITY);
4335 DPRINTF(D_BUFFER,
4336 "message_allqueues_check(): removed %zu buffer entries\n", sum);
4337 return sum;
4338 }
4339
4340 struct buf_msg *
4341 buf_msg_new(const size_t len)
4342 {
4343 struct buf_msg *newbuf;
4344
4345 CALLOC(newbuf, sizeof(*newbuf));
4346
4347 if (len) { /* len = 0 is valid */
4348 MALLOC(newbuf->msg, len);
4349 newbuf->msgorig = newbuf->msg;
4350 newbuf->msgsize = len;
4351 }
4352 return NEWREF(newbuf);
4353 }
4354
4355 void
4356 buf_msg_free(struct buf_msg *buf)
4357 {
4358 if (!buf)
4359 return;
4360
4361 buf->refcount--;
4362 if (buf->refcount == 0) {
4363 FREEPTR(buf->timestamp);
4364 /* small optimizations: the host/recvhost may point to the
4365 * global HostName/FQDN. of course this must not be free()d
4366 * same goes for appname and include_pid
4367 */
4368 if (buf->recvhost != buf->host
4369 && buf->recvhost != LocalHostName
4370 && buf->recvhost != LocalFQDN
4371 && buf->recvhost != oldLocalFQDN)
4372 FREEPTR(buf->recvhost);
4373 if (buf->host != LocalHostName
4374 && buf->host != LocalFQDN
4375 && buf->host != oldLocalFQDN)
4376 FREEPTR(buf->host);
4377 if (buf->prog != appname)
4378 FREEPTR(buf->prog);
4379 if (buf->pid != include_pid)
4380 FREEPTR(buf->pid);
4381 FREEPTR(buf->msgid);
4382 FREEPTR(buf->sd);
4383 FREEPTR(buf->msgorig); /* instead of msg */
4384 FREEPTR(buf);
4385 }
4386 }
4387
4388 size_t
4389 buf_queue_obj_size(struct buf_queue *qentry)
4390 {
4391 size_t sum = 0;
4392
4393 if (!qentry)
4394 return 0;
4395 sum += sizeof(*qentry)
4396 + sizeof(*qentry->msg)
4397 + qentry->msg->msgsize
4398 + SAFEstrlen(qentry->msg->timestamp)+1
4399 + SAFEstrlen(qentry->msg->msgid)+1;
4400 if (qentry->msg->prog
4401 && qentry->msg->prog != include_pid)
4402 sum += strlen(qentry->msg->prog)+1;
4403 if (qentry->msg->pid
4404 && qentry->msg->pid != appname)
4405 sum += strlen(qentry->msg->pid)+1;
4406 if (qentry->msg->recvhost
4407 && qentry->msg->recvhost != LocalHostName
4408 && qentry->msg->recvhost != LocalFQDN
4409 && qentry->msg->recvhost != oldLocalFQDN)
4410 sum += strlen(qentry->msg->recvhost)+1;
4411 if (qentry->msg->host
4412 && qentry->msg->host != LocalHostName
4413 && qentry->msg->host != LocalFQDN
4414 && qentry->msg->host != oldLocalFQDN)
4415 sum += strlen(qentry->msg->host)+1;
4416
4417 return sum;
4418 }
4419
4420 bool
4421 message_queue_remove(struct filed *f, struct buf_queue *qentry)
4422 {
4423 if (!f || !qentry || !qentry->msg)
4424 return false;
4425
4426 assert(!STAILQ_EMPTY(&f->f_qhead));
4427 STAILQ_REMOVE(&f->f_qhead, qentry, buf_queue, entries);
4428 f->f_qelements--;
4429 f->f_qsize -= buf_queue_obj_size(qentry);
4430
4431 DPRINTF(D_BUFFER, "msg @%p removed from queue @%p, new qlen = %zu\n",
4432 qentry->msg, f, f->f_qelements);
4433 DELREF(qentry->msg);
4434 FREEPTR(qentry);
4435 return true;
4436 }
4437
4438 /*
4439 * returns *qentry on success and NULL on error
4440 */
4441 struct buf_queue *
4442 message_queue_add(struct filed *f, struct buf_msg *buffer)
4443 {
4444 struct buf_queue *qentry;
4445
4446 /* check on every call or only every n-th time? */
4447 message_queue_purge(f, 0, PURGE_BY_PRIORITY);
4448
4449 while (!(qentry = malloc(sizeof(*qentry)))
4450 && message_queue_purge(f, 1, PURGE_OLDEST))
4451 continue;
4452 if (!qentry) {
4453 logerror("Unable to allocate memory");
4454 DPRINTF(D_BUFFER, "queue empty, no memory, msg dropped\n");
4455 return NULL;
4456 } else {
4457 qentry->msg = buffer;
4458 f->f_qelements++;
4459 f->f_qsize += buf_queue_obj_size(qentry);
4460 STAILQ_INSERT_TAIL(&f->f_qhead, qentry, entries);
4461
4462 DPRINTF(D_BUFFER, "msg @%p queued @%p, qlen = %zu\n",
4463 buffer, f, f->f_qelements);
4464 return qentry;
4465 }
4466 }
4467
4468 void
4469 message_queue_freeall(struct filed *f)
4470 {
4471 struct buf_queue *qentry;
4472
4473 if (!f) return;
4474 DPRINTF(D_MEM, "message_queue_freeall(f@%p) with f_qhead@%p\n", f,
4475 &f->f_qhead);
4476
4477 while (!STAILQ_EMPTY(&f->f_qhead)) {
4478 qentry = STAILQ_FIRST(&f->f_qhead);
4479 STAILQ_REMOVE(&f->f_qhead, qentry, buf_queue, entries);
4480 DELREF(qentry->msg);
4481 FREEPTR(qentry);
4482 }
4483
4484 f->f_qelements = 0;
4485 f->f_qsize = 0;
4486 }
4487
4488 #ifndef DISABLE_TLS
4489 /* utility function for tls_reconnect() */
4490 struct filed *
4491 get_f_by_conninfo(struct tls_conn_settings *conn_info)
4492 {
4493 struct filed *f;
4494
4495 for (f = Files; f; f = f->f_next) {
4496 if ((f->f_type == F_TLS) && f->f_un.f_tls.tls_conn == conn_info)
4497 return f;
4498 }
4499 DPRINTF(D_TLS, "get_f_by_conninfo() called on invalid conn_info\n");
4500 return NULL;
4501 }
4502
4503 /*
4504 * Called on signal.
4505 * Lets the admin reconnect without waiting for the reconnect timer expires.
4506 */
4507 /*ARGSUSED*/
4508 void
4509 dispatch_force_tls_reconnect(int fd, short event, void *ev)
4510 {
4511 struct filed *f;
4512 DPRINTF((D_TLS|D_CALL|D_EVENT), "dispatch_force_tls_reconnect()\n");
4513 for (f = Files; f; f = f->f_next) {
4514 if (f->f_type == F_TLS &&
4515 f->f_un.f_tls.tls_conn->state == ST_NONE)
4516 tls_reconnect(fd, event, f->f_un.f_tls.tls_conn);
4517 }
4518 }
4519 #endif /* !DISABLE_TLS */
4520
4521 /*
4522 * return a timestamp in a static buffer,
4523 * either format the timestamp given by parameter in_now
4524 * or use the current time if in_now is NULL.
4525 */
4526 char *
4527 make_timestamp(time_t *in_now, bool iso)
4528 {
4529 int frac_digits = 6;
4530 struct timeval tv;
4531 time_t mytime;
4532 struct tm *ltime;
4533 int len = 0;
4534 int tzlen = 0;
4535 /* uses global var: time_t now; */
4536
4537 if (in_now) {
4538 mytime = *in_now;
4539 } else {
4540 gettimeofday(&tv, NULL);
4541 mytime = now = (time_t) tv.tv_sec;
4542 }
4543
4544 if (!iso) {
4545 strlcpy(timestamp, ctime(&mytime) + 4, TIMESTAMPBUFSIZE);
4546 timestamp[BSD_TIMESTAMPLEN] = '\0';
4547 return timestamp;
4548 }
4549
4550 ltime = localtime(&mytime);
4551 len += strftime(timestamp, TIMESTAMPBUFSIZE, "%FT%T", ltime);
4552 snprintf(&(timestamp[len]), frac_digits+2, ".%.*ld",
4553 frac_digits, tv.tv_usec);
4554 len += frac_digits+1;
4555 tzlen = strftime(&(timestamp[len]), TIMESTAMPBUFSIZE-len, "%z", ltime);
4556 len += tzlen;
4557
4558 if (tzlen == 5) {
4559 /* strftime gives "+0200", but we need "+02:00" */
4560 timestamp[len+1] = timestamp[len];
4561 timestamp[len] = timestamp[len-1];
4562 timestamp[len-1] = timestamp[len-2];
4563 timestamp[len-2] = ':';
4564 }
4565 return timestamp;
4566 }
4567
4568 /* auxillary code to allocate memory and copy a string */
4569 bool
4570 copy_string(char **mem, const char *p, const char *q)
4571 {
4572 const size_t len = 1 + q - p;
4573 if (!(*mem = malloc(len))) {
4574 logerror("Unable to allocate memory for config");
4575 return false;
4576 }
4577 strlcpy(*mem, p, len);
4578 return true;
4579 }
4580
4581 /* keyword has to end with ", everything until next " is copied */
4582 bool
4583 copy_config_value_quoted(const char *keyword, char **mem, const char **p)
4584 {
4585 const char *q;
4586 if (strncasecmp(*p, keyword, strlen(keyword)))
4587 return false;
4588 q = *p += strlen(keyword);
4589 if (!(q = strchr(*p, '"'))) {
4590 logerror("unterminated \"\n");
4591 return false;
4592 }
4593 if (!(copy_string(mem, *p, q)))
4594 return false;
4595 *p = ++q;
4596 return true;
4597 }
4598
4599 /* for config file:
4600 * following = required but whitespace allowed, quotes optional
4601 * if numeric, then conversion to integer and no memory allocation
4602 */
4603 bool
4604 copy_config_value(const char *keyword, char **mem,
4605 const char **p, const char *file, int line)
4606 {
4607 if (strncasecmp(*p, keyword, strlen(keyword)))
4608 return false;
4609 *p += strlen(keyword);
4610
4611 while (isspace((unsigned char)**p))
4612 *p += 1;
4613 if (**p != '=') {
4614 logerror("expected \"=\" in file %s, line %d", file, line);
4615 return false;
4616 }
4617 *p += 1;
4618
4619 return copy_config_value_word(mem, p);
4620 }
4621
4622 /* copy next parameter from a config line */
4623 bool
4624 copy_config_value_word(char **mem, const char **p)
4625 {
4626 const char *q;
4627 while (isspace((unsigned char)**p))
4628 *p += 1;
4629 if (**p == '"')
4630 return copy_config_value_quoted("\"", mem, p);
4631
4632 /* without quotes: find next whitespace or end of line */
4633 (void)((q = strchr(*p, ' ')) || (q = strchr(*p, '\t'))
4634 || (q = strchr(*p, '\n')) || (q = strchr(*p, '\0')));
4635
4636 if (q-*p == 0 || !(copy_string(mem, *p, q)))
4637 return false;
4638
4639 *p = ++q;
4640 return true;
4641 }
4642