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