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