1 /* $OpenBSD: syslogd.c,v 1.270 2021/09/19 10:17:36 bluhm Exp $ */ 2 3 /* 4 * Copyright (c) 2014-2021 Alexander Bluhm <bluhm@genua.de> 5 * 6 * Permission to use, copy, modify, and distribute this software for any 7 * purpose with or without fee is hereby granted, provided that the above 8 * copyright notice and this permission notice appear in all copies. 9 * 10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 17 */ 18 19 /* 20 * Copyright (c) 1983, 1988, 1993, 1994 21 * The Regents of the University of California. All rights reserved. 22 * 23 * Redistribution and use in source and binary forms, with or without 24 * modification, are permitted provided that the following conditions 25 * are met: 26 * 1. Redistributions of source code must retain the above copyright 27 * notice, this list of conditions and the following disclaimer. 28 * 2. Redistributions in binary form must reproduce the above copyright 29 * notice, this list of conditions and the following disclaimer in the 30 * documentation and/or other materials provided with the distribution. 31 * 3. Neither the name of the University nor the names of its contributors 32 * may be used to endorse or promote products derived from this software 33 * without specific prior written permission. 34 * 35 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 36 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 37 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 38 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 39 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 40 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 41 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 42 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 43 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 44 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 45 * SUCH DAMAGE. 46 */ 47 48 /* 49 * syslogd -- log system messages 50 * 51 * This program implements a system log. It takes a series of lines. 52 * Each line may have a priority, signified as "<n>" as 53 * the first characters of the line. If this is 54 * not present, a default priority is used. 55 * 56 * To kill syslogd, send a signal 15 (terminate). A signal 1 (hup) will 57 * cause it to reread its configuration file. 58 * 59 * Defined Constants: 60 * 61 * MAXLINE -- the maximum line length that can be handled. 62 * DEFUPRI -- the default priority for user messages 63 * DEFSPRI -- the default priority for kernel messages 64 * 65 * Author: Eric Allman 66 * extensive changes by Ralph Campbell 67 * more extensive changes by Eric Allman (again) 68 * memory buffer logging by Damien Miller 69 * IPv6, libevent, syslog over TCP and TLS by Alexander Bluhm 70 */ 71 72 #define MAX_UDPMSG 1180 /* maximum UDP send size */ 73 #define MIN_MEMBUF (LOG_MAXLINE * 4) /* Minimum memory buffer size */ 74 #define MAX_MEMBUF (256 * 1024) /* Maximum memory buffer size */ 75 #define MAX_MEMBUF_NAME 64 /* Max length of membuf log name */ 76 #define MAX_TCPBUF (256 * 1024) /* Maximum tcp event buffer size */ 77 #define MAXSVLINE 120 /* maximum saved line length */ 78 #define FD_RESERVE 5 /* file descriptors not accepted */ 79 #define DEFUPRI (LOG_USER|LOG_NOTICE) 80 #define DEFSPRI (LOG_KERN|LOG_CRIT) 81 #define TIMERINTVL 30 /* interval for checking flush, mark */ 82 83 #include <sys/ioctl.h> 84 #include <sys/stat.h> 85 #include <sys/msgbuf.h> 86 #include <sys/queue.h> 87 #include <sys/sysctl.h> 88 #include <sys/un.h> 89 #include <sys/time.h> 90 #include <sys/resource.h> 91 92 #include <netinet/in.h> 93 #include <netdb.h> 94 #include <arpa/inet.h> 95 96 #include <ctype.h> 97 #include <err.h> 98 #include <errno.h> 99 #include <event.h> 100 #include <fcntl.h> 101 #include <fnmatch.h> 102 #include <limits.h> 103 #include <paths.h> 104 #include <signal.h> 105 #include <stdio.h> 106 #include <stdlib.h> 107 #include <string.h> 108 #include <tls.h> 109 #include <unistd.h> 110 #include <utmp.h> 111 #include <vis.h> 112 113 #define MAXIMUM(a, b) (((a) > (b)) ? (a) : (b)) 114 #define MINIMUM(a, b) (((a) < (b)) ? (a) : (b)) 115 116 #define SYSLOG_NAMES 117 #include <sys/syslog.h> 118 119 #include "log.h" 120 #include "syslogd.h" 121 #include "evbuffer_tls.h" 122 123 char *ConfFile = _PATH_LOGCONF; 124 const char ctty[] = _PATH_CONSOLE; 125 126 #define MAXUNAMES 20 /* maximum number of user names */ 127 128 129 /* 130 * Flags to logline(). 131 */ 132 133 #define IGN_CONS 0x001 /* don't print on console */ 134 #define SYNC_FILE 0x002 /* do fsync on file after printing */ 135 #define ADDDATE 0x004 /* add a date to the message */ 136 #define MARK 0x008 /* this message is a mark */ 137 138 /* 139 * This structure represents the files that will have log 140 * copies printed. 141 */ 142 143 struct filed { 144 SIMPLEQ_ENTRY(filed) f_next; /* next in linked list */ 145 int f_type; /* entry type, see below */ 146 int f_file; /* file descriptor */ 147 time_t f_time; /* time this was last written */ 148 u_char f_pmask[LOG_NFACILITIES+1]; /* priority mask */ 149 char *f_program; /* program this applies to */ 150 char *f_hostname; /* host this applies to */ 151 union { 152 char f_uname[MAXUNAMES][UT_NAMESIZE+1]; 153 struct { 154 char f_loghost[1+4+3+1+NI_MAXHOST+1+NI_MAXSERV]; 155 /* @proto46://[hostname]:servname\0 */ 156 struct sockaddr_storage f_addr; 157 struct buffertls f_buftls; 158 struct bufferevent *f_bufev; 159 struct tls *f_ctx; 160 char *f_host; 161 int f_reconnectwait; 162 } f_forw; /* forwarding address */ 163 char f_fname[PATH_MAX]; 164 struct { 165 char f_mname[MAX_MEMBUF_NAME]; 166 struct ringbuf *f_rb; 167 int f_overflow; 168 int f_attached; 169 size_t f_len; 170 } f_mb; /* Memory buffer */ 171 } f_un; 172 char f_prevline[MAXSVLINE]; /* last message logged */ 173 char f_lasttime[33]; /* time of last occurrence */ 174 char f_prevhost[HOST_NAME_MAX+1]; /* host from which recd. */ 175 int f_prevpri; /* pri of f_prevline */ 176 int f_prevlen; /* length of f_prevline */ 177 int f_prevcount; /* repetition cnt of prevline */ 178 unsigned int f_repeatcount; /* number of "repeated" msgs */ 179 int f_quick; /* abort when matched */ 180 int f_dropped; /* warn, dropped message */ 181 time_t f_lasterrtime; /* last error was reported */ 182 }; 183 184 /* 185 * Intervals at which we flush out "message repeated" messages, 186 * in seconds after previous message is logged. After each flush, 187 * we move to the next interval until we reach the largest. 188 */ 189 int repeatinterval[] = { 30, 120, 600 }; /* # of secs before flush */ 190 #define MAXREPEAT ((sizeof(repeatinterval) / sizeof(repeatinterval[0])) - 1) 191 #define REPEATTIME(f) ((f)->f_time + repeatinterval[(f)->f_repeatcount]) 192 #define BACKOFF(f) { if (++(f)->f_repeatcount > MAXREPEAT) \ 193 (f)->f_repeatcount = MAXREPEAT; \ 194 } 195 196 /* values for f_type */ 197 #define F_UNUSED 0 /* unused entry */ 198 #define F_FILE 1 /* regular file */ 199 #define F_TTY 2 /* terminal */ 200 #define F_CONSOLE 3 /* console terminal */ 201 #define F_FORWUDP 4 /* remote machine via UDP */ 202 #define F_USERS 5 /* list of users */ 203 #define F_WALL 6 /* everyone logged on */ 204 #define F_MEMBUF 7 /* memory buffer */ 205 #define F_PIPE 8 /* pipe to external program */ 206 #define F_FORWTCP 9 /* remote machine via TCP */ 207 #define F_FORWTLS 10 /* remote machine via TLS */ 208 209 char *TypeNames[] = { 210 "UNUSED", "FILE", "TTY", "CONSOLE", 211 "FORWUDP", "USERS", "WALL", "MEMBUF", 212 "PIPE", "FORWTCP", "FORWTLS", 213 }; 214 215 SIMPLEQ_HEAD(filed_list, filed) Files; 216 struct filed consfile; 217 218 int Debug; /* debug flag */ 219 int Foreground; /* run in foreground, instead of daemonizing */ 220 char LocalHostName[HOST_NAME_MAX+1]; /* our hostname */ 221 int Started = 0; /* set after privsep */ 222 int Initialized = 0; /* set when we have initialized ourselves */ 223 224 int MarkInterval = 20 * 60; /* interval between marks in seconds */ 225 int MarkSeq = 0; /* mark sequence number */ 226 int PrivChild = 0; /* Exec the privileged parent process */ 227 int Repeat = 0; /* 0 msg repeated, 1 in files only, 2 never */ 228 int SecureMode = 1; /* when true, speak only unix domain socks */ 229 int NoDNS = 0; /* when true, refrain from doing DNS lookups */ 230 int ZuluTime = 0; /* display date and time in UTC ISO format */ 231 int IncludeHostname = 0; /* include RFC 3164 hostnames when forwarding */ 232 int Family = PF_UNSPEC; /* protocol family, may disable IPv4 or IPv6 */ 233 234 struct tls *server_ctx; 235 struct tls_config *client_config, *server_config; 236 const char *CAfile = "/etc/ssl/cert.pem"; /* file containing CA certificates */ 237 int NoVerify = 0; /* do not verify TLS server x509 certificate */ 238 const char *ClientCertfile = NULL; 239 const char *ClientKeyfile = NULL; 240 const char *ServerCAfile = NULL; 241 int tcpbuf_dropped = 0; /* count messages dropped from TCP or TLS */ 242 int file_dropped = 0; /* messages dropped due to file system full */ 243 int init_dropped = 0; /* messages dropped during initialization */ 244 245 #define CTL_READING_CMD 1 246 #define CTL_WRITING_REPLY 2 247 #define CTL_WRITING_CONT_REPLY 3 248 int ctl_state = 0; /* What the control socket is up to */ 249 int membuf_drop = 0; /* logs dropped in continuous membuf read */ 250 251 /* 252 * Client protocol NB. all numeric fields in network byte order 253 */ 254 #define CTL_VERSION 2 255 256 /* Request */ 257 struct { 258 u_int32_t version; 259 #define CMD_READ 1 /* Read out log */ 260 #define CMD_READ_CLEAR 2 /* Read and clear log */ 261 #define CMD_CLEAR 3 /* Clear log */ 262 #define CMD_LIST 4 /* List available logs */ 263 #define CMD_FLAGS 5 /* Query flags only */ 264 #define CMD_READ_CONT 6 /* Read out log continuously */ 265 u_int32_t cmd; 266 u_int32_t lines; 267 char logname[MAX_MEMBUF_NAME]; 268 } ctl_cmd; 269 270 size_t ctl_cmd_bytes = 0; /* number of bytes of ctl_cmd read */ 271 272 /* Reply */ 273 struct ctl_reply_hdr { 274 u_int32_t version; 275 #define CTL_HDR_FLAG_OVERFLOW 0x01 276 u_int32_t flags; 277 /* Reply text follows, up to MAX_MEMBUF long */ 278 }; 279 280 #define CTL_HDR_LEN (sizeof(struct ctl_reply_hdr)) 281 #define CTL_REPLY_MAXSIZE (CTL_HDR_LEN + MAX_MEMBUF) 282 #define CTL_REPLY_SIZE (strlen(reply_text) + CTL_HDR_LEN) 283 284 char *ctl_reply = NULL; /* Buffer for control connection reply */ 285 char *reply_text; /* Start of reply text in buffer */ 286 size_t ctl_reply_size = 0; /* Number of bytes used in reply */ 287 size_t ctl_reply_offset = 0; /* Number of bytes of reply written so far */ 288 289 char *linebuf; 290 int linesize; 291 292 int fd_ctlconn, fd_udp, fd_udp6, send_udp, send_udp6; 293 struct event *ev_ctlaccept, *ev_ctlread, *ev_ctlwrite; 294 295 struct peer { 296 struct buffertls p_buftls; 297 struct bufferevent *p_bufev; 298 struct tls *p_ctx; 299 char *p_peername; 300 char *p_hostname; 301 int p_fd; 302 }; 303 char hostname_unknown[] = "???"; 304 305 void klog_readcb(int, short, void *); 306 void udp_readcb(int, short, void *); 307 void unix_readcb(int, short, void *); 308 int reserve_accept4(int, int, struct event *, 309 void (*)(int, short, void *), struct sockaddr *, socklen_t *, int); 310 void tcp_acceptcb(int, short, void *); 311 void tls_acceptcb(int, short, void *); 312 void acceptcb(int, short, void *, int); 313 int octet_counting(struct evbuffer *, char **, int); 314 int non_transparent_framing(struct evbuffer *, char **); 315 void tcp_readcb(struct bufferevent *, void *); 316 void tcp_closecb(struct bufferevent *, short, void *); 317 int tcp_socket(struct filed *); 318 void tcp_dropcb(struct bufferevent *, void *); 319 void tcp_writecb(struct bufferevent *, void *); 320 void tcp_errorcb(struct bufferevent *, short, void *); 321 void tcp_connectcb(int, short, void *); 322 void tcp_connect_retry(struct bufferevent *, struct filed *); 323 int tcpbuf_countmsg(struct bufferevent *bufev); 324 void die_signalcb(int, short, void *); 325 void mark_timercb(int, short, void *); 326 void init_signalcb(int, short, void *); 327 void ctlsock_acceptcb(int, short, void *); 328 void ctlconn_readcb(int, short, void *); 329 void ctlconn_writecb(int, short, void *); 330 void ctlconn_logto(char *); 331 void ctlconn_cleanup(void); 332 333 struct filed *cfline(char *, char *, char *); 334 void cvthname(struct sockaddr *, char *, size_t); 335 int decode(const char *, const CODE *); 336 void markit(void); 337 void fprintlog(struct filed *, int, char *); 338 void dropped_warn(int *, const char *); 339 void init(void); 340 void logevent(int, const char *); 341 void logline(int, int, char *, char *); 342 struct filed *find_dup(struct filed *); 343 size_t parsepriority(const char *, int *); 344 void printline(char *, char *); 345 void printsys(char *); 346 void usage(void); 347 void wallmsg(struct filed *, struct iovec *); 348 int loghost_parse(char *, char **, char **, char **); 349 int getmsgbufsize(void); 350 void address_alloc(const char *, const char *, char ***, char ***, int *); 351 int socket_bind(const char *, const char *, const char *, int, 352 int *, int *); 353 int unix_socket(char *, int, mode_t); 354 void double_sockbuf(int, int, int); 355 void set_sockbuf(int); 356 void set_keepalive(int); 357 void tailify_replytext(char *, int); 358 359 int 360 main(int argc, char *argv[]) 361 { 362 struct timeval to; 363 struct event *ev_klog, *ev_sendsys, *ev_udp, *ev_udp6, 364 *ev_bind, *ev_listen, *ev_tls, *ev_unix, 365 *ev_hup, *ev_int, *ev_quit, *ev_term, *ev_mark; 366 sigset_t sigmask; 367 const char *errstr; 368 char *p; 369 int ch, i; 370 int lockpipe[2] = { -1, -1}, pair[2], nullfd, fd; 371 int fd_ctlsock, fd_klog, fd_sendsys, *fd_bind, *fd_listen; 372 int *fd_tls, *fd_unix, nunix, nbind, nlisten, ntls; 373 char **path_unix, *path_ctlsock; 374 char **bind_host, **bind_port, **listen_host, **listen_port; 375 char *tls_hostport, **tls_host, **tls_port; 376 377 /* block signal until handler is set up */ 378 sigemptyset(&sigmask); 379 sigaddset(&sigmask, SIGHUP); 380 if (sigprocmask(SIG_SETMASK, &sigmask, NULL) == -1) 381 err(1, "sigprocmask block"); 382 383 if ((path_unix = malloc(sizeof(*path_unix))) == NULL) 384 err(1, "malloc %s", _PATH_LOG); 385 path_unix[0] = _PATH_LOG; 386 nunix = 1; 387 path_ctlsock = NULL; 388 389 bind_host = listen_host = tls_host = NULL; 390 bind_port = listen_port = tls_port = NULL; 391 tls_hostport = NULL; 392 nbind = nlisten = ntls = 0; 393 394 while ((ch = getopt(argc, argv, 395 "46a:C:c:dFf:hK:k:m:nP:p:rS:s:T:U:uVZ")) != -1) { 396 switch (ch) { 397 case '4': /* disable IPv6 */ 398 Family = PF_INET; 399 break; 400 case '6': /* disable IPv4 */ 401 Family = PF_INET6; 402 break; 403 case 'a': 404 if ((path_unix = reallocarray(path_unix, nunix + 1, 405 sizeof(*path_unix))) == NULL) 406 err(1, "unix path %s", optarg); 407 path_unix[nunix++] = optarg; 408 break; 409 case 'C': /* file containing CA certificates */ 410 CAfile = optarg; 411 break; 412 case 'c': /* file containing client certificate */ 413 ClientCertfile = optarg; 414 break; 415 case 'd': /* debug */ 416 Debug++; 417 break; 418 case 'F': /* foreground */ 419 Foreground = 1; 420 break; 421 case 'f': /* configuration file */ 422 ConfFile = optarg; 423 break; 424 case 'h': /* RFC 3164 hostnames */ 425 IncludeHostname = 1; 426 break; 427 case 'K': /* verify client with CA file */ 428 ServerCAfile = optarg; 429 break; 430 case 'k': /* file containing client key */ 431 ClientKeyfile = optarg; 432 break; 433 case 'm': /* mark interval */ 434 MarkInterval = strtonum(optarg, 0, 365*24*60, &errstr); 435 if (errstr) 436 errx(1, "mark_interval %s: %s", errstr, optarg); 437 MarkInterval *= 60; 438 break; 439 case 'n': /* don't do DNS lookups */ 440 NoDNS = 1; 441 break; 442 case 'P': /* used internally, exec the parent */ 443 PrivChild = strtonum(optarg, 2, INT_MAX, &errstr); 444 if (errstr) 445 errx(1, "priv child %s: %s", errstr, optarg); 446 break; 447 case 'p': /* path */ 448 path_unix[0] = optarg; 449 break; 450 case 'r': 451 Repeat++; 452 break; 453 case 'S': /* allow tls and listen on address */ 454 if (tls_hostport == NULL) 455 tls_hostport = optarg; 456 address_alloc("tls", optarg, &tls_host, &tls_port, 457 &ntls); 458 break; 459 case 's': 460 path_ctlsock = optarg; 461 break; 462 case 'T': /* allow tcp and listen on address */ 463 address_alloc("listen", optarg, &listen_host, 464 &listen_port, &nlisten); 465 break; 466 case 'U': /* allow udp only from address */ 467 address_alloc("bind", optarg, &bind_host, &bind_port, 468 &nbind); 469 break; 470 case 'u': /* allow udp input port */ 471 SecureMode = 0; 472 break; 473 case 'V': /* do not verify certificates */ 474 NoVerify = 1; 475 break; 476 case 'Z': /* time stamps in UTC ISO format */ 477 ZuluTime = 1; 478 break; 479 default: 480 usage(); 481 } 482 } 483 if (argc != optind) 484 usage(); 485 486 log_init(Debug, LOG_SYSLOG); 487 log_procinit("syslogd"); 488 if (Debug) 489 setvbuf(stdout, NULL, _IOLBF, 0); 490 491 if ((nullfd = open(_PATH_DEVNULL, O_RDWR)) == -1) 492 fatal("open %s", _PATH_DEVNULL); 493 for (fd = nullfd + 1; fd <= STDERR_FILENO; fd++) { 494 if (fcntl(fd, F_GETFL) == -1 && errno == EBADF) 495 if (dup2(nullfd, fd) == -1) 496 fatal("dup2 null"); 497 } 498 499 if (PrivChild > 1) 500 priv_exec(ConfFile, NoDNS, PrivChild, argc, argv); 501 502 consfile.f_type = F_CONSOLE; 503 (void)strlcpy(consfile.f_un.f_fname, ctty, 504 sizeof(consfile.f_un.f_fname)); 505 consfile.f_file = open(consfile.f_un.f_fname, O_WRONLY|O_NONBLOCK, 0); 506 if (consfile.f_file == -1) 507 log_warn("open %s", consfile.f_un.f_fname); 508 509 if (gethostname(LocalHostName, sizeof(LocalHostName)) == -1 || 510 LocalHostName[0] == '\0') 511 strlcpy(LocalHostName, "-", sizeof(LocalHostName)); 512 else if ((p = strchr(LocalHostName, '.')) != NULL) 513 *p = '\0'; 514 515 /* Reserve space for kernel message buffer plus buffer full message. */ 516 linesize = getmsgbufsize() + 64; 517 if (linesize < LOG_MAXLINE) 518 linesize = LOG_MAXLINE; 519 linesize++; 520 if ((linebuf = malloc(linesize)) == NULL) 521 fatal("allocate line buffer"); 522 523 if (socket_bind("udp", NULL, "syslog", SecureMode, 524 &fd_udp, &fd_udp6) == -1) 525 log_warnx("socket bind * failed"); 526 if ((fd_bind = reallocarray(NULL, nbind, sizeof(*fd_bind))) == NULL) 527 fatal("allocate bind fd"); 528 for (i = 0; i < nbind; i++) { 529 if (socket_bind("udp", bind_host[i], bind_port[i], 0, 530 &fd_bind[i], &fd_bind[i]) == -1) 531 log_warnx("socket bind udp failed"); 532 } 533 if ((fd_listen = reallocarray(NULL, nlisten, sizeof(*fd_listen))) 534 == NULL) 535 fatal("allocate listen fd"); 536 for (i = 0; i < nlisten; i++) { 537 if (socket_bind("tcp", listen_host[i], listen_port[i], 0, 538 &fd_listen[i], &fd_listen[i]) == -1) 539 log_warnx("socket listen tcp failed"); 540 } 541 if ((fd_tls = reallocarray(NULL, ntls, sizeof(*fd_tls))) == NULL) 542 fatal("allocate tls fd"); 543 for (i = 0; i < ntls; i++) { 544 if (socket_bind("tls", tls_host[i], tls_port[i], 0, 545 &fd_tls[i], &fd_tls[i]) == -1) 546 log_warnx("socket listen tls failed"); 547 } 548 549 if ((fd_unix = reallocarray(NULL, nunix, sizeof(*fd_unix))) == NULL) 550 fatal("allocate unix fd"); 551 for (i = 0; i < nunix; i++) { 552 fd_unix[i] = unix_socket(path_unix[i], SOCK_DGRAM, 0666); 553 if (fd_unix[i] == -1) { 554 if (i == 0) 555 log_warnx("log socket %s failed", path_unix[i]); 556 continue; 557 } 558 double_sockbuf(fd_unix[i], SO_RCVBUF, 0); 559 } 560 561 if (socketpair(AF_UNIX, SOCK_DGRAM, PF_UNSPEC, pair) == -1) { 562 log_warn("socketpair sendsyslog"); 563 fd_sendsys = -1; 564 } else { 565 /* 566 * Avoid to lose messages from sendsyslog(2). A larger 567 * 1 MB socket buffer compensates bursts. 568 */ 569 double_sockbuf(pair[0], SO_RCVBUF, 1<<20); 570 double_sockbuf(pair[1], SO_SNDBUF, 1<<20); 571 fd_sendsys = pair[0]; 572 } 573 574 fd_ctlsock = fd_ctlconn = -1; 575 if (path_ctlsock != NULL) { 576 fd_ctlsock = unix_socket(path_ctlsock, SOCK_STREAM, 0600); 577 if (fd_ctlsock == -1) { 578 log_warnx("control socket %s failed", path_ctlsock); 579 } else { 580 if (listen(fd_ctlsock, 5) == -1) { 581 log_warn("listen control socket"); 582 close(fd_ctlsock); 583 fd_ctlsock = -1; 584 } 585 } 586 } 587 588 if ((fd_klog = open(_PATH_KLOG, O_RDONLY, 0)) == -1) { 589 log_warn("open %s", _PATH_KLOG); 590 } else if (fd_sendsys != -1) { 591 /* Use /dev/klog to register sendsyslog(2) receiver. */ 592 if (ioctl(fd_klog, LIOCSFD, &pair[1]) == -1) 593 log_warn("ioctl klog LIOCSFD sendsyslog"); 594 } 595 if (fd_sendsys != -1) 596 close(pair[1]); 597 598 if ((client_config = tls_config_new()) == NULL) 599 log_warn("tls_config_new client"); 600 if (tls_hostport) { 601 if ((server_config = tls_config_new()) == NULL) 602 log_warn("tls_config_new server"); 603 if ((server_ctx = tls_server()) == NULL) { 604 log_warn("tls_server"); 605 for (i = 0; i < ntls; i++) 606 close(fd_tls[i]); 607 free(fd_tls); 608 fd_tls = NULL; 609 free(tls_host); 610 free(tls_port); 611 tls_host = tls_port = NULL; 612 ntls = 0; 613 } 614 } 615 616 if (client_config) { 617 if (NoVerify) { 618 tls_config_insecure_noverifycert(client_config); 619 tls_config_insecure_noverifyname(client_config); 620 } else { 621 if (tls_config_set_ca_file(client_config, 622 CAfile) == -1) { 623 log_warnx("load client TLS CA: %s", 624 tls_config_error(client_config)); 625 /* avoid reading default certs in chroot */ 626 tls_config_set_ca_mem(client_config, "", 0); 627 } else 628 log_debug("CAfile %s", CAfile); 629 } 630 if (ClientCertfile && ClientKeyfile) { 631 if (tls_config_set_cert_file(client_config, 632 ClientCertfile) == -1) 633 log_warnx("load client TLS cert: %s", 634 tls_config_error(client_config)); 635 else 636 log_debug("ClientCertfile %s", ClientCertfile); 637 638 if (tls_config_set_key_file(client_config, 639 ClientKeyfile) == -1) 640 log_warnx("load client TLS key: %s", 641 tls_config_error(client_config)); 642 else 643 log_debug("ClientKeyfile %s", ClientKeyfile); 644 } else if (ClientCertfile || ClientKeyfile) { 645 log_warnx("options -c and -k must be used together"); 646 } 647 if (tls_config_set_protocols(client_config, 648 TLS_PROTOCOLS_ALL) != 0) 649 log_warnx("set client TLS protocols: %s", 650 tls_config_error(client_config)); 651 if (tls_config_set_ciphers(client_config, "all") != 0) 652 log_warnx("set client TLS ciphers: %s", 653 tls_config_error(client_config)); 654 } 655 if (server_config && server_ctx) { 656 const char *names[2]; 657 658 names[0] = tls_hostport; 659 names[1] = tls_host[0]; 660 661 for (i = 0; i < 2; i++) { 662 if (asprintf(&p, "/etc/ssl/private/%s.key", names[i]) 663 == -1) 664 continue; 665 if (tls_config_set_key_file(server_config, p) == -1) { 666 log_warnx("load server TLS key: %s", 667 tls_config_error(server_config)); 668 free(p); 669 continue; 670 } 671 log_debug("Keyfile %s", p); 672 free(p); 673 if (asprintf(&p, "/etc/ssl/%s.crt", names[i]) == -1) 674 continue; 675 if (tls_config_set_cert_file(server_config, p) == -1) { 676 log_warnx("load server TLS cert: %s", 677 tls_config_error(server_config)); 678 free(p); 679 continue; 680 } 681 log_debug("Certfile %s", p); 682 free(p); 683 break; 684 } 685 686 if (ServerCAfile) { 687 if (tls_config_set_ca_file(server_config, 688 ServerCAfile) == -1) { 689 log_warnx("load server TLS CA: %s", 690 tls_config_error(server_config)); 691 /* avoid reading default certs in chroot */ 692 tls_config_set_ca_mem(server_config, "", 0); 693 } else 694 log_debug("Server CAfile %s", ServerCAfile); 695 tls_config_verify_client(server_config); 696 } 697 if (tls_config_set_protocols(server_config, 698 TLS_PROTOCOLS_ALL) != 0) 699 log_warnx("set server TLS protocols: %s", 700 tls_config_error(server_config)); 701 if (tls_config_set_ciphers(server_config, "compat") != 0) 702 log_warnx("Set server TLS ciphers: %s", 703 tls_config_error(server_config)); 704 if (tls_configure(server_ctx, server_config) != 0) { 705 log_warnx("tls_configure server: %s", 706 tls_error(server_ctx)); 707 tls_free(server_ctx); 708 server_ctx = NULL; 709 for (i = 0; i < ntls; i++) 710 close(fd_tls[i]); 711 free(fd_tls); 712 fd_tls = NULL; 713 free(tls_host); 714 free(tls_port); 715 tls_host = tls_port = NULL; 716 ntls = 0; 717 } 718 } 719 720 log_debug("off & running...."); 721 722 if (!Debug && !Foreground) { 723 char c; 724 725 pipe(lockpipe); 726 727 switch(fork()) { 728 case -1: 729 err(1, "fork"); 730 case 0: 731 setsid(); 732 close(lockpipe[0]); 733 break; 734 default: 735 close(lockpipe[1]); 736 read(lockpipe[0], &c, 1); 737 _exit(0); 738 } 739 } 740 741 /* tuck my process id away */ 742 if (!Debug) { 743 FILE *fp; 744 745 fp = fopen(_PATH_LOGPID, "w"); 746 if (fp != NULL) { 747 fprintf(fp, "%ld\n", (long)getpid()); 748 (void) fclose(fp); 749 } 750 } 751 752 /* Privilege separation begins here */ 753 priv_init(lockpipe[1], nullfd, argc, argv); 754 755 if (pledge("stdio unix inet recvfd", NULL) == -1) 756 err(1, "pledge"); 757 758 Started = 1; 759 760 /* Process is now unprivileged and inside a chroot */ 761 if (Debug) 762 event_set_log_callback(logevent); 763 event_init(); 764 765 if ((ev_ctlaccept = malloc(sizeof(struct event))) == NULL || 766 (ev_ctlread = malloc(sizeof(struct event))) == NULL || 767 (ev_ctlwrite = malloc(sizeof(struct event))) == NULL || 768 (ev_klog = malloc(sizeof(struct event))) == NULL || 769 (ev_sendsys = malloc(sizeof(struct event))) == NULL || 770 (ev_udp = malloc(sizeof(struct event))) == NULL || 771 (ev_udp6 = malloc(sizeof(struct event))) == NULL || 772 (ev_bind = reallocarray(NULL, nbind, sizeof(struct event))) 773 == NULL || 774 (ev_listen = reallocarray(NULL, nlisten, sizeof(struct event))) 775 == NULL || 776 (ev_tls = reallocarray(NULL, ntls, sizeof(struct event))) 777 == NULL || 778 (ev_unix = reallocarray(NULL, nunix, sizeof(struct event))) 779 == NULL || 780 (ev_hup = malloc(sizeof(struct event))) == NULL || 781 (ev_int = malloc(sizeof(struct event))) == NULL || 782 (ev_quit = malloc(sizeof(struct event))) == NULL || 783 (ev_term = malloc(sizeof(struct event))) == NULL || 784 (ev_mark = malloc(sizeof(struct event))) == NULL) 785 err(1, "malloc"); 786 787 event_set(ev_ctlaccept, fd_ctlsock, EV_READ|EV_PERSIST, 788 ctlsock_acceptcb, ev_ctlaccept); 789 event_set(ev_ctlread, fd_ctlconn, EV_READ|EV_PERSIST, 790 ctlconn_readcb, ev_ctlread); 791 event_set(ev_ctlwrite, fd_ctlconn, EV_WRITE|EV_PERSIST, 792 ctlconn_writecb, ev_ctlwrite); 793 event_set(ev_klog, fd_klog, EV_READ|EV_PERSIST, klog_readcb, ev_klog); 794 event_set(ev_sendsys, fd_sendsys, EV_READ|EV_PERSIST, unix_readcb, 795 ev_sendsys); 796 event_set(ev_udp, fd_udp, EV_READ|EV_PERSIST, udp_readcb, ev_udp); 797 event_set(ev_udp6, fd_udp6, EV_READ|EV_PERSIST, udp_readcb, ev_udp6); 798 for (i = 0; i < nbind; i++) 799 event_set(&ev_bind[i], fd_bind[i], EV_READ|EV_PERSIST, 800 udp_readcb, &ev_bind[i]); 801 for (i = 0; i < nlisten; i++) 802 event_set(&ev_listen[i], fd_listen[i], EV_READ|EV_PERSIST, 803 tcp_acceptcb, &ev_listen[i]); 804 for (i = 0; i < ntls; i++) 805 event_set(&ev_tls[i], fd_tls[i], EV_READ|EV_PERSIST, 806 tls_acceptcb, &ev_tls[i]); 807 for (i = 0; i < nunix; i++) 808 event_set(&ev_unix[i], fd_unix[i], EV_READ|EV_PERSIST, 809 unix_readcb, &ev_unix[i]); 810 811 signal_set(ev_hup, SIGHUP, init_signalcb, ev_hup); 812 signal_set(ev_int, SIGINT, die_signalcb, ev_int); 813 signal_set(ev_quit, SIGQUIT, die_signalcb, ev_quit); 814 signal_set(ev_term, SIGTERM, die_signalcb, ev_term); 815 816 evtimer_set(ev_mark, mark_timercb, ev_mark); 817 818 init(); 819 820 /* Allocate ctl socket reply buffer if we have a ctl socket */ 821 if (fd_ctlsock != -1 && 822 (ctl_reply = malloc(CTL_REPLY_MAXSIZE)) == NULL) 823 fatal("allocate control socket reply buffer"); 824 reply_text = ctl_reply + CTL_HDR_LEN; 825 826 if (!Debug) { 827 close(lockpipe[1]); 828 dup2(nullfd, STDIN_FILENO); 829 dup2(nullfd, STDOUT_FILENO); 830 dup2(nullfd, STDERR_FILENO); 831 } 832 if (nullfd > 2) 833 close(nullfd); 834 835 /* 836 * Signal to the priv process that the initial config parsing is done 837 * so that it will reject any future attempts to open more files 838 */ 839 priv_config_parse_done(); 840 841 if (fd_ctlsock != -1) 842 event_add(ev_ctlaccept, NULL); 843 if (fd_klog != -1) 844 event_add(ev_klog, NULL); 845 if (fd_sendsys != -1) 846 event_add(ev_sendsys, NULL); 847 if (!SecureMode) { 848 if (fd_udp != -1) 849 event_add(ev_udp, NULL); 850 if (fd_udp6 != -1) 851 event_add(ev_udp6, NULL); 852 } 853 for (i = 0; i < nbind; i++) 854 if (fd_bind[i] != -1) 855 event_add(&ev_bind[i], NULL); 856 for (i = 0; i < nlisten; i++) 857 if (fd_listen[i] != -1) 858 event_add(&ev_listen[i], NULL); 859 for (i = 0; i < ntls; i++) 860 if (fd_tls[i] != -1) 861 event_add(&ev_tls[i], NULL); 862 for (i = 0; i < nunix; i++) 863 if (fd_unix[i] != -1) 864 event_add(&ev_unix[i], NULL); 865 866 signal_add(ev_hup, NULL); 867 signal_add(ev_term, NULL); 868 if (Debug || Foreground) { 869 signal_add(ev_int, NULL); 870 signal_add(ev_quit, NULL); 871 } else { 872 (void)signal(SIGINT, SIG_IGN); 873 (void)signal(SIGQUIT, SIG_IGN); 874 } 875 (void)signal(SIGCHLD, SIG_IGN); 876 (void)signal(SIGPIPE, SIG_IGN); 877 878 to.tv_sec = TIMERINTVL; 879 to.tv_usec = 0; 880 evtimer_add(ev_mark, &to); 881 882 log_info(LOG_INFO, "start"); 883 log_debug("syslogd: started"); 884 885 sigemptyset(&sigmask); 886 if (sigprocmask(SIG_SETMASK, &sigmask, NULL) == -1) 887 err(1, "sigprocmask unblock"); 888 889 /* Send message via libc, flushes log stash in kernel. */ 890 openlog("syslogd", LOG_PID, LOG_SYSLOG); 891 syslog(LOG_DEBUG, "running"); 892 893 event_dispatch(); 894 /* NOTREACHED */ 895 return (0); 896 } 897 898 void 899 address_alloc(const char *name, const char *address, char ***host, 900 char ***port, int *num) 901 { 902 char *p; 903 904 /* do not care about memory leak, argv has to be preserved */ 905 if ((p = strdup(address)) == NULL) 906 err(1, "%s address %s", name, address); 907 if ((*host = reallocarray(*host, *num + 1, sizeof(**host))) == NULL) 908 err(1, "%s host %s", name, address); 909 if ((*port = reallocarray(*port, *num + 1, sizeof(**port))) == NULL) 910 err(1, "%s port %s", name, address); 911 if (loghost_parse(p, NULL, *host + *num, *port + *num) == -1) 912 errx(1, "bad %s address: %s", name, address); 913 (*num)++; 914 } 915 916 int 917 socket_bind(const char *proto, const char *host, const char *port, 918 int shutread, int *fd, int *fd6) 919 { 920 struct addrinfo hints, *res, *res0; 921 char hostname[NI_MAXHOST], servname[NI_MAXSERV]; 922 int *fdp, error, reuseaddr; 923 924 *fd = *fd6 = -1; 925 if (proto == NULL) 926 proto = "udp"; 927 if (port == NULL) 928 port = strcmp(proto, "tls") == 0 ? "syslog-tls" : "syslog"; 929 930 memset(&hints, 0, sizeof(hints)); 931 hints.ai_family = Family; 932 if (strcmp(proto, "udp") == 0) { 933 hints.ai_socktype = SOCK_DGRAM; 934 hints.ai_protocol = IPPROTO_UDP; 935 } else { 936 hints.ai_socktype = SOCK_STREAM; 937 hints.ai_protocol = IPPROTO_TCP; 938 } 939 hints.ai_flags = AI_PASSIVE; 940 941 if ((error = getaddrinfo(host, port, &hints, &res0))) { 942 log_warnx("getaddrinfo proto %s, host %s, port %s: %s", 943 proto, host ? host : "*", port, gai_strerror(error)); 944 return (-1); 945 } 946 947 for (res = res0; res; res = res->ai_next) { 948 switch (res->ai_family) { 949 case AF_INET: 950 fdp = fd; 951 break; 952 case AF_INET6: 953 fdp = fd6; 954 break; 955 default: 956 continue; 957 } 958 if (*fdp >= 0) 959 continue; 960 961 if ((*fdp = socket(res->ai_family, 962 res->ai_socktype | SOCK_NONBLOCK, res->ai_protocol)) == -1) 963 continue; 964 965 if (getnameinfo(res->ai_addr, res->ai_addrlen, hostname, 966 sizeof(hostname), servname, sizeof(servname), 967 NI_NUMERICHOST | NI_NUMERICSERV | 968 (res->ai_socktype == SOCK_DGRAM ? NI_DGRAM : 0)) != 0) { 969 log_debug("Malformed bind address"); 970 hostname[0] = servname[0] = '\0'; 971 } 972 if (shutread && shutdown(*fdp, SHUT_RD) == -1) { 973 log_warn("shutdown SHUT_RD " 974 "protocol %d, address %s, portnum %s", 975 res->ai_protocol, hostname, servname); 976 close(*fdp); 977 *fdp = -1; 978 continue; 979 } 980 if (!shutread && res->ai_protocol == IPPROTO_UDP) 981 double_sockbuf(*fdp, SO_RCVBUF, 0); 982 else if (res->ai_protocol == IPPROTO_TCP) { 983 set_sockbuf(*fdp); 984 set_keepalive(*fdp); 985 } 986 reuseaddr = 1; 987 if (setsockopt(*fdp, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, 988 sizeof(reuseaddr)) == -1) { 989 log_warn("setsockopt SO_REUSEADDR " 990 "protocol %d, address %s, portnum %s", 991 res->ai_protocol, hostname, servname); 992 close(*fdp); 993 *fdp = -1; 994 continue; 995 } 996 if (bind(*fdp, res->ai_addr, res->ai_addrlen) == -1) { 997 log_warn("bind protocol %d, address %s, portnum %s", 998 res->ai_protocol, hostname, servname); 999 close(*fdp); 1000 *fdp = -1; 1001 continue; 1002 } 1003 if (!shutread && res->ai_protocol == IPPROTO_TCP && 1004 listen(*fdp, 10) == -1) { 1005 log_warn("listen protocol %d, address %s, portnum %s", 1006 res->ai_protocol, hostname, servname); 1007 close(*fdp); 1008 *fdp = -1; 1009 continue; 1010 } 1011 } 1012 1013 freeaddrinfo(res0); 1014 1015 if (*fd == -1 && *fd6 == -1) 1016 return (-1); 1017 return (0); 1018 } 1019 1020 void 1021 klog_readcb(int fd, short event, void *arg) 1022 { 1023 struct event *ev = arg; 1024 ssize_t n; 1025 1026 n = read(fd, linebuf, linesize - 1); 1027 if (n > 0) { 1028 linebuf[n] = '\0'; 1029 printsys(linebuf); 1030 } else if (n == -1 && errno != EINTR) { 1031 log_warn("read klog"); 1032 event_del(ev); 1033 } 1034 } 1035 1036 void 1037 udp_readcb(int fd, short event, void *arg) 1038 { 1039 struct sockaddr_storage sa; 1040 socklen_t salen; 1041 ssize_t n; 1042 1043 salen = sizeof(sa); 1044 n = recvfrom(fd, linebuf, LOG_MAXLINE, 0, (struct sockaddr *)&sa, 1045 &salen); 1046 if (n > 0) { 1047 char resolve[NI_MAXHOST]; 1048 1049 linebuf[n] = '\0'; 1050 cvthname((struct sockaddr *)&sa, resolve, sizeof(resolve)); 1051 log_debug("cvthname res: %s", resolve); 1052 printline(resolve, linebuf); 1053 } else if (n == -1 && errno != EINTR && errno != EWOULDBLOCK) 1054 log_warn("recvfrom udp"); 1055 } 1056 1057 void 1058 unix_readcb(int fd, short event, void *arg) 1059 { 1060 struct sockaddr_un sa; 1061 socklen_t salen; 1062 ssize_t n; 1063 1064 salen = sizeof(sa); 1065 n = recvfrom(fd, linebuf, LOG_MAXLINE, 0, (struct sockaddr *)&sa, 1066 &salen); 1067 if (n > 0) { 1068 linebuf[n] = '\0'; 1069 printline(LocalHostName, linebuf); 1070 } else if (n == -1 && errno != EINTR && errno != EWOULDBLOCK) 1071 log_warn("recvfrom unix"); 1072 } 1073 1074 int 1075 reserve_accept4(int lfd, int event, struct event *ev, 1076 void (*cb)(int, short, void *), 1077 struct sockaddr *sa, socklen_t *salen, int flags) 1078 { 1079 struct timeval to = { 1, 0 }; 1080 int afd; 1081 1082 if (event & EV_TIMEOUT) { 1083 log_debug("Listen again"); 1084 /* Enable the listen event, there is no timeout anymore. */ 1085 event_set(ev, lfd, EV_READ|EV_PERSIST, cb, ev); 1086 event_add(ev, NULL); 1087 errno = EWOULDBLOCK; 1088 return (-1); 1089 } 1090 1091 if (getdtablecount() + FD_RESERVE >= getdtablesize()) { 1092 afd = -1; 1093 errno = EMFILE; 1094 } else 1095 afd = accept4(lfd, sa, salen, flags); 1096 1097 if (afd == -1 && (errno == ENFILE || errno == EMFILE)) { 1098 log_info(LOG_WARNING, "accept deferred: %s", strerror(errno)); 1099 /* 1100 * Disable the listen event and convert it to a timeout. 1101 * Pass the listen file descriptor to the callback. 1102 */ 1103 event_del(ev); 1104 event_set(ev, lfd, 0, cb, ev); 1105 event_add(ev, &to); 1106 return (-1); 1107 } 1108 1109 return (afd); 1110 } 1111 1112 void 1113 tcp_acceptcb(int lfd, short event, void *arg) 1114 { 1115 acceptcb(lfd, event, arg, 0); 1116 } 1117 1118 void 1119 tls_acceptcb(int lfd, short event, void *arg) 1120 { 1121 acceptcb(lfd, event, arg, 1); 1122 } 1123 1124 void 1125 acceptcb(int lfd, short event, void *arg, int usetls) 1126 { 1127 struct event *ev = arg; 1128 struct peer *p; 1129 struct sockaddr_storage ss; 1130 socklen_t sslen; 1131 char hostname[NI_MAXHOST], servname[NI_MAXSERV]; 1132 char *peername; 1133 int fd; 1134 1135 sslen = sizeof(ss); 1136 if ((fd = reserve_accept4(lfd, event, ev, tcp_acceptcb, 1137 (struct sockaddr *)&ss, &sslen, SOCK_NONBLOCK)) == -1) { 1138 if (errno != ENFILE && errno != EMFILE && 1139 errno != EINTR && errno != EWOULDBLOCK && 1140 errno != ECONNABORTED) 1141 log_warn("accept tcp socket"); 1142 return; 1143 } 1144 log_debug("Accepting tcp connection"); 1145 1146 if (getnameinfo((struct sockaddr *)&ss, sslen, hostname, 1147 sizeof(hostname), servname, sizeof(servname), 1148 NI_NUMERICHOST | NI_NUMERICSERV) != 0 || 1149 asprintf(&peername, ss.ss_family == AF_INET6 ? 1150 "[%s]:%s" : "%s:%s", hostname, servname) == -1) { 1151 log_debug("Malformed accept address"); 1152 peername = hostname_unknown; 1153 } 1154 log_debug("Peer addresss and port %s", peername); 1155 if ((p = malloc(sizeof(*p))) == NULL) { 1156 log_warn("allocate \"%s\"", peername); 1157 close(fd); 1158 return; 1159 } 1160 p->p_fd = fd; 1161 if ((p->p_bufev = bufferevent_new(fd, tcp_readcb, NULL, tcp_closecb, 1162 p)) == NULL) { 1163 log_warn("bufferevent \"%s\"", peername); 1164 free(p); 1165 close(fd); 1166 return; 1167 } 1168 p->p_ctx = NULL; 1169 if (usetls) { 1170 if (tls_accept_socket(server_ctx, &p->p_ctx, fd) == -1) { 1171 log_warnx("tls_accept_socket \"%s\": %s", 1172 peername, tls_error(server_ctx)); 1173 bufferevent_free(p->p_bufev); 1174 free(p); 1175 close(fd); 1176 return; 1177 } 1178 buffertls_set(&p->p_buftls, p->p_bufev, p->p_ctx, fd); 1179 buffertls_accept(&p->p_buftls, fd); 1180 log_debug("tcp accept callback: tls context success"); 1181 } 1182 if (!NoDNS && peername != hostname_unknown && 1183 priv_getnameinfo((struct sockaddr *)&ss, ss.ss_len, hostname, 1184 sizeof(hostname)) != 0) { 1185 log_debug("Host name for accept address (%s) unknown", 1186 hostname); 1187 } 1188 if (peername == hostname_unknown || 1189 (p->p_hostname = strdup(hostname)) == NULL) 1190 p->p_hostname = hostname_unknown; 1191 log_debug("Peer hostname %s", hostname); 1192 p->p_peername = peername; 1193 bufferevent_enable(p->p_bufev, EV_READ); 1194 1195 log_info(LOG_DEBUG, "%s logger \"%s\" accepted", 1196 p->p_ctx ? "tls" : "tcp", peername); 1197 } 1198 1199 /* 1200 * Syslog over TCP RFC 6587 3.4.1. Octet Counting 1201 */ 1202 int 1203 octet_counting(struct evbuffer *evbuf, char **msg, int drain) 1204 { 1205 char *p, *buf, *end; 1206 int len; 1207 1208 buf = EVBUFFER_DATA(evbuf); 1209 end = buf + EVBUFFER_LENGTH(evbuf); 1210 /* 1211 * It can be assumed that octet-counting framing is used if a syslog 1212 * frame starts with a digit. 1213 */ 1214 if (buf >= end || !isdigit((unsigned char)*buf)) 1215 return (-1); 1216 /* 1217 * SYSLOG-FRAME = MSG-LEN SP SYSLOG-MSG 1218 * MSG-LEN is the octet count of the SYSLOG-MSG in the SYSLOG-FRAME. 1219 * We support up to 5 digits in MSG-LEN, so the maximum is 99999. 1220 */ 1221 for (p = buf; p < end && p < buf + 5; p++) { 1222 if (!isdigit((unsigned char)*p)) 1223 break; 1224 } 1225 if (buf >= p || p >= end || *p != ' ') 1226 return (-1); 1227 p++; 1228 /* Using atoi() is safe as buf starts with 1 to 5 digits and a space. */ 1229 len = atoi(buf); 1230 if (drain) 1231 log_debugadd(" octet counting %d", len); 1232 if (p + len > end) 1233 return (0); 1234 if (drain) 1235 evbuffer_drain(evbuf, p - buf); 1236 if (msg) 1237 *msg = p; 1238 return (len); 1239 } 1240 1241 /* 1242 * Syslog over TCP RFC 6587 3.4.2. Non-Transparent-Framing 1243 */ 1244 int 1245 non_transparent_framing(struct evbuffer *evbuf, char **msg) 1246 { 1247 char *p, *buf, *end; 1248 1249 buf = EVBUFFER_DATA(evbuf); 1250 end = buf + EVBUFFER_LENGTH(evbuf); 1251 /* 1252 * The TRAILER has usually been a single character and most often 1253 * is ASCII LF (%d10). However, other characters have also been 1254 * seen, with ASCII NUL (%d00) being a prominent example. 1255 */ 1256 for (p = buf; p < end; p++) { 1257 if (*p == '\0' || *p == '\n') 1258 break; 1259 } 1260 if (p + 1 - buf >= INT_MAX) 1261 return (-1); 1262 log_debugadd(" non transparent framing"); 1263 if (p >= end) 1264 return (0); 1265 /* 1266 * Some devices have also been seen to emit a two-character 1267 * TRAILER, which is usually CR and LF. 1268 */ 1269 if (buf < p && p[0] == '\n' && p[-1] == '\r') 1270 p[-1] = '\0'; 1271 if (msg) 1272 *msg = buf; 1273 return (p + 1 - buf); 1274 } 1275 1276 void 1277 tcp_readcb(struct bufferevent *bufev, void *arg) 1278 { 1279 struct peer *p = arg; 1280 char *msg; 1281 int len; 1282 1283 while (EVBUFFER_LENGTH(bufev->input) > 0) { 1284 log_debugadd("%s logger \"%s\"", p->p_ctx ? "tls" : "tcp", 1285 p->p_peername); 1286 msg = NULL; 1287 len = octet_counting(bufev->input, &msg, 1); 1288 if (len < 0) 1289 len = non_transparent_framing(bufev->input, &msg); 1290 if (len < 0) 1291 log_debugadd("unknown method"); 1292 if (msg == NULL) { 1293 log_debugadd(", incomplete frame"); 1294 break; 1295 } 1296 log_debug(", use %d bytes", len); 1297 if (len > 0 && msg[len-1] == '\n') 1298 msg[len-1] = '\0'; 1299 if (len == 0 || msg[len-1] != '\0') { 1300 memcpy(linebuf, msg, MINIMUM(len, LOG_MAXLINE)); 1301 linebuf[MINIMUM(len, LOG_MAXLINE)] = '\0'; 1302 msg = linebuf; 1303 } 1304 printline(p->p_hostname, msg); 1305 evbuffer_drain(bufev->input, len); 1306 } 1307 /* Maximum frame has 5 digits, 1 space, MAXLINE chars, 1 new line. */ 1308 if (EVBUFFER_LENGTH(bufev->input) >= 5 + 1 + LOG_MAXLINE + 1) { 1309 log_debug(", use %zu bytes", EVBUFFER_LENGTH(bufev->input)); 1310 EVBUFFER_DATA(bufev->input)[5 + 1 + LOG_MAXLINE] = '\0'; 1311 printline(p->p_hostname, EVBUFFER_DATA(bufev->input)); 1312 evbuffer_drain(bufev->input, -1); 1313 } else if (EVBUFFER_LENGTH(bufev->input) > 0) 1314 log_debug(", buffer %zu bytes", EVBUFFER_LENGTH(bufev->input)); 1315 } 1316 1317 void 1318 tcp_closecb(struct bufferevent *bufev, short event, void *arg) 1319 { 1320 struct peer *p = arg; 1321 1322 if (event & EVBUFFER_EOF) { 1323 log_info(LOG_DEBUG, "%s logger \"%s\" connection close", 1324 p->p_ctx ? "tls" : "tcp", p->p_peername); 1325 } else { 1326 log_info(LOG_NOTICE, "%s logger \"%s\" connection error: %s", 1327 p->p_ctx ? "tls" : "tcp", p->p_peername, 1328 p->p_ctx ? tls_error(p->p_ctx) : strerror(errno)); 1329 } 1330 1331 if (p->p_peername != hostname_unknown) 1332 free(p->p_peername); 1333 if (p->p_hostname != hostname_unknown) 1334 free(p->p_hostname); 1335 bufferevent_free(p->p_bufev); 1336 close(p->p_fd); 1337 free(p); 1338 } 1339 1340 int 1341 tcp_socket(struct filed *f) 1342 { 1343 int s; 1344 1345 if ((s = socket(f->f_un.f_forw.f_addr.ss_family, 1346 SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP)) == -1) { 1347 log_warn("socket \"%s\"", f->f_un.f_forw.f_loghost); 1348 return (-1); 1349 } 1350 set_sockbuf(s); 1351 if (connect(s, (struct sockaddr *)&f->f_un.f_forw.f_addr, 1352 f->f_un.f_forw.f_addr.ss_len) == -1 && errno != EINPROGRESS) { 1353 log_warn("connect \"%s\"", f->f_un.f_forw.f_loghost); 1354 close(s); 1355 return (-1); 1356 } 1357 return (s); 1358 } 1359 1360 void 1361 tcp_dropcb(struct bufferevent *bufev, void *arg) 1362 { 1363 struct filed *f = arg; 1364 1365 /* 1366 * Drop data received from the forward log server. 1367 */ 1368 log_debug("loghost \"%s\" did send %zu bytes back", 1369 f->f_un.f_forw.f_loghost, EVBUFFER_LENGTH(bufev->input)); 1370 evbuffer_drain(bufev->input, -1); 1371 } 1372 1373 void 1374 tcp_writecb(struct bufferevent *bufev, void *arg) 1375 { 1376 struct filed *f = arg; 1377 char ebuf[ERRBUFSIZE]; 1378 1379 /* 1380 * Successful write, connection to server is good, reset wait time. 1381 */ 1382 log_debug("loghost \"%s\" successful write", f->f_un.f_forw.f_loghost); 1383 f->f_un.f_forw.f_reconnectwait = 0; 1384 1385 if (f->f_dropped > 0 && 1386 EVBUFFER_LENGTH(f->f_un.f_forw.f_bufev->output) < MAX_TCPBUF) { 1387 snprintf(ebuf, sizeof(ebuf), "to loghost \"%s\"", 1388 f->f_un.f_forw.f_loghost); 1389 dropped_warn(&f->f_dropped, ebuf); 1390 } 1391 } 1392 1393 void 1394 tcp_errorcb(struct bufferevent *bufev, short event, void *arg) 1395 { 1396 struct filed *f = arg; 1397 char *p, *buf, *end; 1398 int l; 1399 char ebuf[ERRBUFSIZE]; 1400 1401 if (event & EVBUFFER_EOF) 1402 snprintf(ebuf, sizeof(ebuf), "loghost \"%s\" connection close", 1403 f->f_un.f_forw.f_loghost); 1404 else 1405 snprintf(ebuf, sizeof(ebuf), 1406 "loghost \"%s\" connection error: %s", 1407 f->f_un.f_forw.f_loghost, f->f_un.f_forw.f_ctx ? 1408 tls_error(f->f_un.f_forw.f_ctx) : strerror(errno)); 1409 log_debug("%s", ebuf); 1410 1411 /* The SIGHUP handler may also close the socket, so invalidate it. */ 1412 if (f->f_un.f_forw.f_ctx) { 1413 tls_close(f->f_un.f_forw.f_ctx); 1414 tls_free(f->f_un.f_forw.f_ctx); 1415 f->f_un.f_forw.f_ctx = NULL; 1416 } 1417 close(f->f_file); 1418 f->f_file = -1; 1419 1420 /* 1421 * The messages in the output buffer may be out of sync. 1422 * Check that the buffer starts with "1234 <1234 octets>\n". 1423 * Otherwise remove the partial message from the beginning. 1424 */ 1425 buf = EVBUFFER_DATA(bufev->output); 1426 end = buf + EVBUFFER_LENGTH(bufev->output); 1427 if (buf < end && !((l = octet_counting(bufev->output, &p, 0)) > 0 && 1428 p[l-1] == '\n')) { 1429 for (p = buf; p < end; p++) { 1430 if (*p == '\n') { 1431 evbuffer_drain(bufev->output, p - buf + 1); 1432 break; 1433 } 1434 } 1435 /* Without '\n' discard everything. */ 1436 if (p == end) 1437 evbuffer_drain(bufev->output, -1); 1438 log_debug("loghost \"%s\" dropped partial message", 1439 f->f_un.f_forw.f_loghost); 1440 f->f_dropped++; 1441 } 1442 1443 tcp_connect_retry(bufev, f); 1444 1445 /* Log the connection error to the fresh buffer after reconnecting. */ 1446 log_info(LOG_WARNING, "%s", ebuf); 1447 } 1448 1449 void 1450 tcp_connectcb(int fd, short event, void *arg) 1451 { 1452 struct filed *f = arg; 1453 struct bufferevent *bufev = f->f_un.f_forw.f_bufev; 1454 int s; 1455 1456 if ((s = tcp_socket(f)) == -1) { 1457 tcp_connect_retry(bufev, f); 1458 return; 1459 } 1460 log_debug("tcp connect callback: socket success, event %#x", event); 1461 f->f_file = s; 1462 1463 bufferevent_setfd(bufev, s); 1464 bufferevent_setcb(bufev, tcp_dropcb, tcp_writecb, tcp_errorcb, f); 1465 /* 1466 * Although syslog is a write only protocol, enable reading from 1467 * the socket to detect connection close and errors. 1468 */ 1469 bufferevent_enable(bufev, EV_READ|EV_WRITE); 1470 1471 if (f->f_type == F_FORWTLS) { 1472 if ((f->f_un.f_forw.f_ctx = tls_client()) == NULL) { 1473 log_warn("tls_client \"%s\"", f->f_un.f_forw.f_loghost); 1474 goto error; 1475 } 1476 if (client_config && 1477 tls_configure(f->f_un.f_forw.f_ctx, client_config) == -1) { 1478 log_warnx("tls_configure \"%s\": %s", 1479 f->f_un.f_forw.f_loghost, 1480 tls_error(f->f_un.f_forw.f_ctx)); 1481 goto error; 1482 } 1483 if (tls_connect_socket(f->f_un.f_forw.f_ctx, s, 1484 f->f_un.f_forw.f_host) == -1) { 1485 log_warnx("tls_connect_socket \"%s\": %s", 1486 f->f_un.f_forw.f_loghost, 1487 tls_error(f->f_un.f_forw.f_ctx)); 1488 goto error; 1489 } 1490 log_debug("tcp connect callback: tls context success"); 1491 1492 buffertls_set(&f->f_un.f_forw.f_buftls, bufev, 1493 f->f_un.f_forw.f_ctx, s); 1494 buffertls_connect(&f->f_un.f_forw.f_buftls, s); 1495 } 1496 1497 return; 1498 1499 error: 1500 if (f->f_un.f_forw.f_ctx) { 1501 tls_free(f->f_un.f_forw.f_ctx); 1502 f->f_un.f_forw.f_ctx = NULL; 1503 } 1504 close(f->f_file); 1505 f->f_file = -1; 1506 tcp_connect_retry(bufev, f); 1507 } 1508 1509 void 1510 tcp_connect_retry(struct bufferevent *bufev, struct filed *f) 1511 { 1512 struct timeval to; 1513 1514 if (f->f_un.f_forw.f_reconnectwait == 0) 1515 f->f_un.f_forw.f_reconnectwait = 1; 1516 else 1517 f->f_un.f_forw.f_reconnectwait <<= 1; 1518 if (f->f_un.f_forw.f_reconnectwait > 600) 1519 f->f_un.f_forw.f_reconnectwait = 600; 1520 to.tv_sec = f->f_un.f_forw.f_reconnectwait; 1521 to.tv_usec = 0; 1522 1523 log_debug("tcp connect retry: wait %d", 1524 f->f_un.f_forw.f_reconnectwait); 1525 bufferevent_setfd(bufev, -1); 1526 /* We can reuse the write event as bufferevent is disabled. */ 1527 evtimer_set(&bufev->ev_write, tcp_connectcb, f); 1528 evtimer_add(&bufev->ev_write, &to); 1529 } 1530 1531 int 1532 tcpbuf_countmsg(struct bufferevent *bufev) 1533 { 1534 char *p, *buf, *end; 1535 int i = 0; 1536 1537 buf = EVBUFFER_DATA(bufev->output); 1538 end = buf + EVBUFFER_LENGTH(bufev->output); 1539 for (p = buf; p < end; p++) { 1540 if (*p == '\n') 1541 i++; 1542 } 1543 return (i); 1544 } 1545 1546 void 1547 usage(void) 1548 { 1549 1550 (void)fprintf(stderr, 1551 "usage: syslogd [-46dFhnruVZ] [-a path] [-C CAfile]\n" 1552 "\t[-c cert_file] [-f config_file] [-K CAfile] [-k key_file]\n" 1553 "\t[-m mark_interval] [-p log_socket] [-S listen_address]\n" 1554 "\t[-s reporting_socket] [-T listen_address] [-U bind_address]\n"); 1555 exit(1); 1556 } 1557 1558 /* 1559 * Parse a priority code of the form "<123>" into pri, and return the 1560 * length of the priority code including the surrounding angle brackets. 1561 */ 1562 size_t 1563 parsepriority(const char *msg, int *pri) 1564 { 1565 size_t nlen; 1566 char buf[11]; 1567 const char *errstr; 1568 int maybepri; 1569 1570 if (*msg++ == '<') { 1571 nlen = strspn(msg, "1234567890"); 1572 if (nlen > 0 && nlen < sizeof(buf) && msg[nlen] == '>') { 1573 strlcpy(buf, msg, nlen + 1); 1574 maybepri = strtonum(buf, 0, INT_MAX, &errstr); 1575 if (errstr == NULL) { 1576 *pri = maybepri; 1577 return nlen + 2; 1578 } 1579 } 1580 } 1581 1582 return 0; 1583 } 1584 1585 /* 1586 * Take a raw input line, decode the message, and print the message 1587 * on the appropriate log files. 1588 */ 1589 void 1590 printline(char *hname, char *msg) 1591 { 1592 int pri; 1593 char *p, *q, line[LOG_MAXLINE + 4 + 1]; /* message, encoding, NUL */ 1594 1595 /* test for special codes */ 1596 pri = DEFUPRI; 1597 p = msg; 1598 p += parsepriority(p, &pri); 1599 if (pri &~ (LOG_FACMASK|LOG_PRIMASK)) 1600 pri = DEFUPRI; 1601 1602 /* 1603 * Don't allow users to log kernel messages. 1604 * NOTE: since LOG_KERN == 0 this will also match 1605 * messages with no facility specified. 1606 */ 1607 if (LOG_FAC(pri) == LOG_KERN) 1608 pri = LOG_USER | LOG_PRI(pri); 1609 1610 for (q = line; *p && q < &line[LOG_MAXLINE]; p++) { 1611 if (*p == '\n') 1612 *q++ = ' '; 1613 else 1614 q = vis(q, *p, 0, 0); 1615 } 1616 line[LOG_MAXLINE] = *q = '\0'; 1617 1618 logline(pri, 0, hname, line); 1619 } 1620 1621 /* 1622 * Take a raw input line from /dev/klog, split and format similar to syslog(). 1623 */ 1624 void 1625 printsys(char *msg) 1626 { 1627 int c, pri, flags; 1628 char *lp, *p, *q, line[LOG_MAXLINE + 1]; 1629 size_t prilen; 1630 int l; 1631 1632 l = snprintf(line, sizeof(line), "%s: ", _PATH_UNIX); 1633 if (l < 0 || l >= sizeof(line)) { 1634 line[0] = '\0'; 1635 l = 0; 1636 } 1637 lp = line + l; 1638 for (p = msg; *p != '\0'; ) { 1639 flags = SYNC_FILE | ADDDATE; /* fsync file after write */ 1640 pri = DEFSPRI; 1641 prilen = parsepriority(p, &pri); 1642 p += prilen; 1643 if (prilen == 0) { 1644 /* kernel printf's come out on console */ 1645 flags |= IGN_CONS; 1646 } 1647 if (pri &~ (LOG_FACMASK|LOG_PRIMASK)) 1648 pri = DEFSPRI; 1649 1650 q = lp; 1651 while (*p && (c = *p++) != '\n' && q < &line[sizeof(line) - 4]) 1652 q = vis(q, c, 0, 0); 1653 1654 logline(pri, flags, LocalHostName, line); 1655 } 1656 } 1657 1658 void 1659 vlogmsg(int pri, const char *proc, const char *fmt, va_list ap) 1660 { 1661 char msg[ERRBUFSIZE]; 1662 int l; 1663 1664 l = snprintf(msg, sizeof(msg), "%s[%d]: ", proc, getpid()); 1665 if (l < 0 || l >= sizeof(msg)) 1666 l = 0; 1667 l = vsnprintf(msg + l, sizeof(msg) - l, fmt, ap); 1668 if (l < 0) 1669 strlcpy(msg, fmt, sizeof(msg)); 1670 1671 if (!Started) { 1672 fprintf(stderr, "%s\n", msg); 1673 init_dropped++; 1674 return; 1675 } 1676 logline(pri, ADDDATE, LocalHostName, msg); 1677 } 1678 1679 struct timeval now; 1680 1681 /* 1682 * Log a message to the appropriate log files, users, etc. based on 1683 * the priority. 1684 */ 1685 void 1686 logline(int pri, int flags, char *from, char *msg) 1687 { 1688 struct filed *f; 1689 int fac, msglen, prilev, i; 1690 char timestamp[33]; 1691 char prog[NAME_MAX+1]; 1692 1693 log_debug("logline: pri 0%o, flags 0x%x, from %s, msg %s", 1694 pri, flags, from, msg); 1695 1696 /* 1697 * Check to see if msg looks non-standard. 1698 */ 1699 timestamp[0] = '\0'; 1700 msglen = strlen(msg); 1701 if ((flags & ADDDATE) == 0) { 1702 if (msglen >= 16 && msg[3] == ' ' && msg[6] == ' ' && 1703 msg[9] == ':' && msg[12] == ':' && msg[15] == ' ') { 1704 /* BSD syslog TIMESTAMP, RFC 3164 */ 1705 strlcpy(timestamp, msg, 16); 1706 msg += 16; 1707 msglen -= 16; 1708 if (ZuluTime) 1709 flags |= ADDDATE; 1710 } else if (msglen >= 20 && 1711 isdigit(msg[0]) && isdigit(msg[1]) && isdigit(msg[2]) && 1712 isdigit(msg[3]) && msg[4] == '-' && 1713 isdigit(msg[5]) && isdigit(msg[6]) && msg[7] == '-' && 1714 isdigit(msg[8]) && isdigit(msg[9]) && msg[10] == 'T' && 1715 isdigit(msg[11]) && isdigit(msg[12]) && msg[13] == ':' && 1716 isdigit(msg[14]) && isdigit(msg[15]) && msg[16] == ':' && 1717 isdigit(msg[17]) && isdigit(msg[18]) && (msg[19] == '.' || 1718 msg[19] == 'Z' || msg[19] == '+' || msg[19] == '-')) { 1719 /* FULL-DATE "T" FULL-TIME, RFC 5424 */ 1720 strlcpy(timestamp, msg, sizeof(timestamp)); 1721 msg += 19; 1722 msglen -= 19; 1723 i = 0; 1724 if (msglen >= 3 && msg[0] == '.' && isdigit(msg[1])) { 1725 /* TIME-SECFRAC */ 1726 msg += 2; 1727 msglen -= 2; 1728 i += 2; 1729 while(i < 7 && msglen >= 1 && isdigit(msg[0])) { 1730 msg++; 1731 msglen--; 1732 i++; 1733 } 1734 } 1735 if (msglen >= 2 && msg[0] == 'Z' && msg[1] == ' ') { 1736 /* "Z" */ 1737 timestamp[20+i] = '\0'; 1738 msg += 2; 1739 msglen -= 2; 1740 } else if (msglen >= 7 && 1741 (msg[0] == '+' || msg[0] == '-') && 1742 isdigit(msg[1]) && isdigit(msg[2]) && 1743 msg[3] == ':' && 1744 isdigit(msg[4]) && isdigit(msg[5]) && 1745 msg[6] == ' ') { 1746 /* TIME-NUMOFFSET */ 1747 timestamp[25+i] = '\0'; 1748 msg += 7; 1749 msglen -= 7; 1750 } else { 1751 /* invalid time format, roll back */ 1752 timestamp[0] = '\0'; 1753 msg -= 19 + i; 1754 msglen += 19 + i; 1755 flags |= ADDDATE; 1756 } 1757 } else if (msglen >= 2 && msg[0] == '-' && msg[1] == ' ') { 1758 /* NILVALUE, RFC 5424 */ 1759 msg += 2; 1760 msglen -= 2; 1761 flags |= ADDDATE; 1762 } else 1763 flags |= ADDDATE; 1764 } 1765 1766 (void)gettimeofday(&now, NULL); 1767 if (flags & ADDDATE) { 1768 if (ZuluTime) { 1769 struct tm *tm; 1770 size_t l; 1771 1772 tm = gmtime(&now.tv_sec); 1773 l = strftime(timestamp, sizeof(timestamp), "%FT%T", tm); 1774 /* 1775 * Use only millisecond precision as some time has 1776 * passed since syslog(3) was called. 1777 */ 1778 snprintf(timestamp + l, sizeof(timestamp) - l, 1779 ".%03ldZ", now.tv_usec / 1000); 1780 } else 1781 strlcpy(timestamp, ctime(&now.tv_sec) + 4, 16); 1782 } 1783 1784 /* extract facility and priority level */ 1785 if (flags & MARK) 1786 fac = LOG_NFACILITIES; 1787 else { 1788 fac = LOG_FAC(pri); 1789 if (fac >= LOG_NFACILITIES || fac < 0) 1790 fac = LOG_USER; 1791 } 1792 prilev = LOG_PRI(pri); 1793 1794 /* extract program name */ 1795 while (isspace((unsigned char)*msg)) { 1796 msg++; 1797 msglen--; 1798 } 1799 for (i = 0; i < NAME_MAX; i++) { 1800 if (!isalnum((unsigned char)msg[i]) && 1801 msg[i] != '-' && msg[i] != '.' && msg[i] != '_') 1802 break; 1803 prog[i] = msg[i]; 1804 } 1805 prog[i] = 0; 1806 1807 /* log the message to the particular outputs */ 1808 if (!Initialized) { 1809 f = &consfile; 1810 if (f->f_type == F_CONSOLE) { 1811 strlcpy(f->f_lasttime, timestamp, 1812 sizeof(f->f_lasttime)); 1813 strlcpy(f->f_prevhost, from, 1814 sizeof(f->f_prevhost)); 1815 fprintlog(f, flags, msg); 1816 /* May be set to F_UNUSED, try again next time. */ 1817 f->f_type = F_CONSOLE; 1818 } 1819 init_dropped++; 1820 return; 1821 } 1822 SIMPLEQ_FOREACH(f, &Files, f_next) { 1823 /* skip messages that are incorrect priority */ 1824 if (f->f_pmask[fac] < prilev || 1825 f->f_pmask[fac] == INTERNAL_NOPRI) 1826 continue; 1827 1828 /* skip messages with the incorrect program or hostname */ 1829 if (f->f_program && fnmatch(f->f_program, prog, 0) != 0) 1830 continue; 1831 if (f->f_hostname && fnmatch(f->f_hostname, from, 0) != 0) 1832 continue; 1833 1834 if (f->f_type == F_CONSOLE && (flags & IGN_CONS)) 1835 continue; 1836 1837 /* don't output marks to recently written files */ 1838 if ((flags & MARK) && 1839 (now.tv_sec - f->f_time) < MarkInterval / 2) 1840 continue; 1841 1842 /* 1843 * suppress duplicate lines to this file 1844 */ 1845 if ((Repeat == 0 || (Repeat == 1 && 1846 (f->f_type != F_PIPE && f->f_type != F_FORWUDP && 1847 f->f_type != F_FORWTCP && f->f_type != F_FORWTLS))) && 1848 (flags & MARK) == 0 && msglen == f->f_prevlen && 1849 !strcmp(msg, f->f_prevline) && 1850 !strcmp(from, f->f_prevhost)) { 1851 strlcpy(f->f_lasttime, timestamp, 1852 sizeof(f->f_lasttime)); 1853 f->f_prevcount++; 1854 log_debug("msg repeated %d times, %ld sec of %d", 1855 f->f_prevcount, (long)(now.tv_sec - f->f_time), 1856 repeatinterval[f->f_repeatcount]); 1857 /* 1858 * If domark would have logged this by now, 1859 * flush it now (so we don't hold isolated messages), 1860 * but back off so we'll flush less often 1861 * in the future. 1862 */ 1863 if (now.tv_sec > REPEATTIME(f)) { 1864 fprintlog(f, flags, (char *)NULL); 1865 BACKOFF(f); 1866 } 1867 } else { 1868 /* new line, save it */ 1869 if (f->f_prevcount) 1870 fprintlog(f, 0, (char *)NULL); 1871 f->f_repeatcount = 0; 1872 f->f_prevpri = pri; 1873 strlcpy(f->f_lasttime, timestamp, 1874 sizeof(f->f_lasttime)); 1875 strlcpy(f->f_prevhost, from, 1876 sizeof(f->f_prevhost)); 1877 if (msglen < MAXSVLINE) { 1878 f->f_prevlen = msglen; 1879 strlcpy(f->f_prevline, msg, 1880 sizeof(f->f_prevline)); 1881 fprintlog(f, flags, (char *)NULL); 1882 } else { 1883 f->f_prevline[0] = 0; 1884 f->f_prevlen = 0; 1885 fprintlog(f, flags, msg); 1886 } 1887 } 1888 1889 if (f->f_quick) 1890 break; 1891 } 1892 } 1893 1894 void 1895 fprintlog(struct filed *f, int flags, char *msg) 1896 { 1897 struct iovec iov[IOVCNT], *v; 1898 int l, retryonce; 1899 char line[LOG_MAXLINE + 1], pribuf[13], greetings[500], repbuf[80]; 1900 char ebuf[ERRBUFSIZE]; 1901 1902 v = iov; 1903 switch (f->f_type) { 1904 case F_FORWUDP: 1905 case F_FORWTCP: 1906 case F_FORWTLS: 1907 l = snprintf(pribuf, sizeof(pribuf), "<%d>", f->f_prevpri); 1908 if (l < 0) 1909 l = strlcpy(pribuf, "<13>", sizeof(pribuf)); 1910 if (l >= sizeof(pribuf)) 1911 l = sizeof(pribuf) - 1; 1912 v->iov_base = pribuf; 1913 v->iov_len = l; 1914 break; 1915 case F_WALL: 1916 l = snprintf(greetings, sizeof(greetings), 1917 "\r\n\7Message from syslogd@%s at %.24s ...\r\n", 1918 f->f_prevhost, ctime(&now.tv_sec)); 1919 if (l < 0) 1920 l = strlcpy(greetings, 1921 "\r\n\7Message from syslogd ...\r\n", 1922 sizeof(greetings)); 1923 if (l >= sizeof(greetings)) 1924 l = sizeof(greetings) - 1; 1925 v->iov_base = greetings; 1926 v->iov_len = l; 1927 break; 1928 default: 1929 v->iov_base = ""; 1930 v->iov_len = 0; 1931 break; 1932 } 1933 v++; 1934 1935 if (f->f_lasttime[0] != '\0') { 1936 v->iov_base = f->f_lasttime; 1937 v->iov_len = strlen(f->f_lasttime); 1938 v++; 1939 v->iov_base = " "; 1940 v->iov_len = 1; 1941 } else { 1942 v->iov_base = ""; 1943 v->iov_len = 0; 1944 v++; 1945 v->iov_base = ""; 1946 v->iov_len = 0; 1947 } 1948 v++; 1949 1950 switch (f->f_type) { 1951 case F_FORWUDP: 1952 case F_FORWTCP: 1953 case F_FORWTLS: 1954 if (IncludeHostname) { 1955 v->iov_base = LocalHostName; 1956 v->iov_len = strlen(LocalHostName); 1957 v++; 1958 v->iov_base = " "; 1959 v->iov_len = 1; 1960 } else { 1961 /* XXX RFC requires to include host name */ 1962 v->iov_base = ""; 1963 v->iov_len = 0; 1964 v++; 1965 v->iov_base = ""; 1966 v->iov_len = 0; 1967 } 1968 break; 1969 default: 1970 if (f->f_prevhost[0] != '\0') { 1971 v->iov_base = f->f_prevhost; 1972 v->iov_len = strlen(v->iov_base); 1973 v++; 1974 v->iov_base = " "; 1975 v->iov_len = 1; 1976 } else { 1977 v->iov_base = ""; 1978 v->iov_len = 0; 1979 v++; 1980 v->iov_base = ""; 1981 v->iov_len = 0; 1982 } 1983 break; 1984 } 1985 v++; 1986 1987 if (msg) { 1988 v->iov_base = msg; 1989 v->iov_len = strlen(msg); 1990 } else if (f->f_prevcount > 1) { 1991 l = snprintf(repbuf, sizeof(repbuf), 1992 "last message repeated %d times", f->f_prevcount); 1993 if (l < 0) 1994 l = strlcpy(repbuf, "last message repeated", 1995 sizeof(repbuf)); 1996 if (l >= sizeof(repbuf)) 1997 l = sizeof(repbuf) - 1; 1998 v->iov_base = repbuf; 1999 v->iov_len = l; 2000 } else { 2001 v->iov_base = f->f_prevline; 2002 v->iov_len = f->f_prevlen; 2003 } 2004 v++; 2005 2006 switch (f->f_type) { 2007 case F_CONSOLE: 2008 case F_TTY: 2009 case F_USERS: 2010 case F_WALL: 2011 v->iov_base = "\r\n"; 2012 v->iov_len = 2; 2013 break; 2014 case F_FILE: 2015 case F_PIPE: 2016 case F_FORWTCP: 2017 case F_FORWTLS: 2018 v->iov_base = "\n"; 2019 v->iov_len = 1; 2020 break; 2021 default: 2022 v->iov_base = ""; 2023 v->iov_len = 0; 2024 break; 2025 } 2026 v = NULL; 2027 2028 log_debugadd("Logging to %s", TypeNames[f->f_type]); 2029 f->f_time = now.tv_sec; 2030 2031 switch (f->f_type) { 2032 case F_UNUSED: 2033 log_debug("%s", ""); 2034 break; 2035 2036 case F_FORWUDP: 2037 log_debug(" %s", f->f_un.f_forw.f_loghost); 2038 l = snprintf(line, MINIMUM(MAX_UDPMSG + 1, sizeof(line)), 2039 "%s%s%s%s%s%s%s", (char *)iov[0].iov_base, 2040 (char *)iov[1].iov_base, (char *)iov[2].iov_base, 2041 (char *)iov[3].iov_base, (char *)iov[4].iov_base, 2042 (char *)iov[5].iov_base, (char *)iov[6].iov_base); 2043 if (l < 0) 2044 l = strlcpy(line, iov[5].iov_base, sizeof(line)); 2045 if (l >= sizeof(line)) 2046 l = sizeof(line) - 1; 2047 if (l >= MAX_UDPMSG + 1) 2048 l = MAX_UDPMSG; 2049 if (sendto(f->f_file, line, l, 0, 2050 (struct sockaddr *)&f->f_un.f_forw.f_addr, 2051 f->f_un.f_forw.f_addr.ss_len) != l) { 2052 switch (errno) { 2053 case EADDRNOTAVAIL: 2054 case EHOSTDOWN: 2055 case EHOSTUNREACH: 2056 case ENETDOWN: 2057 case ENETUNREACH: 2058 case ENOBUFS: 2059 case EWOULDBLOCK: 2060 /* silently dropped */ 2061 break; 2062 default: 2063 f->f_type = F_UNUSED; 2064 log_warn("sendto \"%s\"", 2065 f->f_un.f_forw.f_loghost); 2066 break; 2067 } 2068 } 2069 break; 2070 2071 case F_FORWTCP: 2072 case F_FORWTLS: 2073 log_debugadd(" %s", f->f_un.f_forw.f_loghost); 2074 if (EVBUFFER_LENGTH(f->f_un.f_forw.f_bufev->output) >= 2075 MAX_TCPBUF) { 2076 log_debug(" (dropped)"); 2077 f->f_dropped++; 2078 break; 2079 } 2080 /* 2081 * Syslog over TLS RFC 5425 4.3. Sending Data 2082 * Syslog over TCP RFC 6587 3.4.1. Octet Counting 2083 * Use an additional '\n' to split messages. This allows 2084 * buffer synchronisation, helps legacy implementations, 2085 * and makes line based testing easier. 2086 */ 2087 l = evbuffer_add_printf(f->f_un.f_forw.f_bufev->output, 2088 "%zu %s%s%s%s%s%s%s", iov[0].iov_len + 2089 iov[1].iov_len + iov[2].iov_len + 2090 iov[3].iov_len + iov[4].iov_len + 2091 iov[5].iov_len + iov[6].iov_len, 2092 (char *)iov[0].iov_base, 2093 (char *)iov[1].iov_base, (char *)iov[2].iov_base, 2094 (char *)iov[3].iov_base, (char *)iov[4].iov_base, 2095 (char *)iov[5].iov_base, (char *)iov[6].iov_base); 2096 if (l < 0) { 2097 log_debug(" (dropped evbuffer_add_printf)"); 2098 f->f_dropped++; 2099 break; 2100 } 2101 bufferevent_enable(f->f_un.f_forw.f_bufev, EV_WRITE); 2102 log_debug("%s", ""); 2103 break; 2104 2105 case F_CONSOLE: 2106 if (flags & IGN_CONS) { 2107 log_debug(" (ignored)"); 2108 break; 2109 } 2110 /* FALLTHROUGH */ 2111 case F_TTY: 2112 case F_FILE: 2113 case F_PIPE: 2114 log_debug(" %s", f->f_un.f_fname); 2115 retryonce = 0; 2116 again: 2117 if (writev(f->f_file, iov, IOVCNT) == -1) { 2118 int e = errno; 2119 2120 /* allow to recover from file system full */ 2121 if (e == ENOSPC && f->f_type == F_FILE) { 2122 if (f->f_dropped++ == 0) { 2123 f->f_type = F_UNUSED; 2124 errno = e; 2125 log_warn("write to file \"%s\"", 2126 f->f_un.f_fname); 2127 f->f_type = F_FILE; 2128 } 2129 break; 2130 } 2131 2132 /* pipe is non-blocking. log and drop message if full */ 2133 if (e == EAGAIN && f->f_type == F_PIPE) { 2134 if (now.tv_sec - f->f_lasterrtime > 120) { 2135 f->f_lasterrtime = now.tv_sec; 2136 log_warn("write to pipe \"%s\"", 2137 f->f_un.f_fname); 2138 } 2139 break; 2140 } 2141 2142 /* 2143 * Check for errors on TTY's or program pipes. 2144 * Errors happen due to loss of tty or died programs. 2145 */ 2146 if (e == EAGAIN) { 2147 /* 2148 * Silently drop messages on blocked write. 2149 * This can happen when logging to a locked tty. 2150 */ 2151 break; 2152 } 2153 2154 (void)close(f->f_file); 2155 if ((e == EIO || e == EBADF) && 2156 f->f_type != F_FILE && f->f_type != F_PIPE && 2157 !retryonce) { 2158 f->f_file = priv_open_tty(f->f_un.f_fname); 2159 retryonce = 1; 2160 if (f->f_file < 0) { 2161 f->f_type = F_UNUSED; 2162 log_warn("priv_open_tty \"%s\"", 2163 f->f_un.f_fname); 2164 } else 2165 goto again; 2166 } else if ((e == EPIPE || e == EBADF) && 2167 f->f_type == F_PIPE && !retryonce) { 2168 f->f_file = priv_open_log(f->f_un.f_fname); 2169 retryonce = 1; 2170 if (f->f_file < 0) { 2171 f->f_type = F_UNUSED; 2172 log_warn("priv_open_log \"%s\"", 2173 f->f_un.f_fname); 2174 } else 2175 goto again; 2176 } else { 2177 f->f_type = F_UNUSED; 2178 f->f_file = -1; 2179 errno = e; 2180 log_warn("writev \"%s\"", f->f_un.f_fname); 2181 } 2182 } else { 2183 if (flags & SYNC_FILE) 2184 (void)fsync(f->f_file); 2185 if (f->f_dropped && f->f_type == F_FILE) { 2186 snprintf(ebuf, sizeof(ebuf), "to file \"%s\"", 2187 f->f_un.f_fname); 2188 dropped_warn(&f->f_dropped, ebuf); 2189 } 2190 } 2191 break; 2192 2193 case F_USERS: 2194 case F_WALL: 2195 log_debug("%s", ""); 2196 wallmsg(f, iov); 2197 break; 2198 2199 case F_MEMBUF: 2200 log_debug("%s", ""); 2201 l = snprintf(line, sizeof(line), 2202 "%s%s%s%s%s%s%s", (char *)iov[0].iov_base, 2203 (char *)iov[1].iov_base, (char *)iov[2].iov_base, 2204 (char *)iov[3].iov_base, (char *)iov[4].iov_base, 2205 (char *)iov[5].iov_base, (char *)iov[6].iov_base); 2206 if (l < 0) 2207 l = strlcpy(line, iov[5].iov_base, sizeof(line)); 2208 if (ringbuf_append_line(f->f_un.f_mb.f_rb, line) == 1) 2209 f->f_un.f_mb.f_overflow = 1; 2210 if (f->f_un.f_mb.f_attached) 2211 ctlconn_logto(line); 2212 break; 2213 } 2214 f->f_prevcount = 0; 2215 } 2216 2217 /* 2218 * WALLMSG -- Write a message to the world at large 2219 * 2220 * Write the specified message to either the entire 2221 * world, or a list of approved users. 2222 */ 2223 void 2224 wallmsg(struct filed *f, struct iovec *iov) 2225 { 2226 struct utmp ut; 2227 char utline[sizeof(ut.ut_line) + 1]; 2228 static int reenter; /* avoid calling ourselves */ 2229 FILE *uf; 2230 int i; 2231 2232 if (reenter++) 2233 return; 2234 if ((uf = priv_open_utmp()) == NULL) { 2235 log_warn("priv_open_utmp"); 2236 reenter = 0; 2237 return; 2238 } 2239 while (fread(&ut, sizeof(ut), 1, uf) == 1) { 2240 if (ut.ut_name[0] == '\0') 2241 continue; 2242 /* must use strncpy since ut_* may not be NUL terminated */ 2243 strncpy(utline, ut.ut_line, sizeof(utline) - 1); 2244 utline[sizeof(utline) - 1] = '\0'; 2245 if (f->f_type == F_WALL) { 2246 ttymsg(utline, iov); 2247 continue; 2248 } 2249 /* should we send the message to this user? */ 2250 for (i = 0; i < MAXUNAMES; i++) { 2251 if (!f->f_un.f_uname[i][0]) 2252 break; 2253 if (!strncmp(f->f_un.f_uname[i], ut.ut_name, 2254 UT_NAMESIZE)) { 2255 ttymsg(utline, iov); 2256 break; 2257 } 2258 } 2259 } 2260 (void)fclose(uf); 2261 reenter = 0; 2262 } 2263 2264 /* 2265 * Return a printable representation of a host address. 2266 */ 2267 void 2268 cvthname(struct sockaddr *f, char *result, size_t res_len) 2269 { 2270 if (getnameinfo(f, f->sa_len, result, res_len, NULL, 0, 2271 NI_NUMERICHOST|NI_NUMERICSERV|NI_DGRAM) != 0) { 2272 log_debug("Malformed from address"); 2273 strlcpy(result, hostname_unknown, res_len); 2274 return; 2275 } 2276 log_debug("cvthname(%s)", result); 2277 if (NoDNS) 2278 return; 2279 2280 if (priv_getnameinfo(f, f->sa_len, result, res_len) != 0) 2281 log_debug("Host name for from address (%s) unknown", result); 2282 } 2283 2284 void 2285 die_signalcb(int signum, short event, void *arg) 2286 { 2287 die(signum); 2288 } 2289 2290 void 2291 mark_timercb(int unused, short event, void *arg) 2292 { 2293 struct event *ev = arg; 2294 struct timeval to; 2295 2296 markit(); 2297 2298 to.tv_sec = TIMERINTVL; 2299 to.tv_usec = 0; 2300 evtimer_add(ev, &to); 2301 } 2302 2303 void 2304 init_signalcb(int signum, short event, void *arg) 2305 { 2306 init(); 2307 log_info(LOG_INFO, "restart"); 2308 2309 dropped_warn(&file_dropped, "to file"); 2310 dropped_warn(&tcpbuf_dropped, "to remote loghost"); 2311 log_debug("syslogd: restarted"); 2312 } 2313 2314 void 2315 logevent(int severity, const char *msg) 2316 { 2317 log_debug("libevent: [%d] %s", severity, msg); 2318 } 2319 2320 void 2321 dropped_warn(int *count, const char *what) 2322 { 2323 int dropped; 2324 2325 if (*count == 0) 2326 return; 2327 2328 dropped = *count; 2329 *count = 0; 2330 log_info(LOG_WARNING, "dropped %d message%s %s", 2331 dropped, dropped == 1 ? "" : "s", what); 2332 } 2333 2334 __dead void 2335 die(int signo) 2336 { 2337 struct filed *f; 2338 2339 SIMPLEQ_FOREACH(f, &Files, f_next) { 2340 /* flush any pending output */ 2341 if (f->f_prevcount) 2342 fprintlog(f, 0, (char *)NULL); 2343 if (f->f_type == F_FORWTLS || f->f_type == F_FORWTCP) { 2344 tcpbuf_dropped += f->f_dropped + 2345 tcpbuf_countmsg(f->f_un.f_forw.f_bufev); 2346 f->f_dropped = 0; 2347 } 2348 if (f->f_type == F_FILE) { 2349 file_dropped += f->f_dropped; 2350 f->f_dropped = 0; 2351 } 2352 } 2353 dropped_warn(&init_dropped, "during initialization"); 2354 dropped_warn(&file_dropped, "to file"); 2355 dropped_warn(&tcpbuf_dropped, "to remote loghost"); 2356 2357 if (signo) 2358 log_info(LOG_ERR, "exiting on signal %d", signo); 2359 log_debug("syslogd: exited"); 2360 exit(0); 2361 } 2362 2363 /* 2364 * INIT -- Initialize syslogd from configuration table 2365 */ 2366 void 2367 init(void) 2368 { 2369 char progblock[NAME_MAX+1], hostblock[NAME_MAX+1], *cline, *p, *q; 2370 struct filed_list mb; 2371 struct filed *f, *m; 2372 FILE *cf; 2373 int i; 2374 size_t s; 2375 2376 log_debug("init"); 2377 2378 /* If config file has been modified, then just die to restart */ 2379 if (priv_config_modified()) { 2380 log_debug("config file changed: dying"); 2381 die(0); 2382 } 2383 2384 /* 2385 * Close all open log files. 2386 */ 2387 Initialized = 0; 2388 SIMPLEQ_INIT(&mb); 2389 while (!SIMPLEQ_EMPTY(&Files)) { 2390 f = SIMPLEQ_FIRST(&Files); 2391 SIMPLEQ_REMOVE_HEAD(&Files, f_next); 2392 /* flush any pending output */ 2393 if (f->f_prevcount) 2394 fprintlog(f, 0, (char *)NULL); 2395 2396 switch (f->f_type) { 2397 case F_FORWTLS: 2398 if (f->f_un.f_forw.f_ctx) { 2399 tls_close(f->f_un.f_forw.f_ctx); 2400 tls_free(f->f_un.f_forw.f_ctx); 2401 } 2402 free(f->f_un.f_forw.f_host); 2403 /* FALLTHROUGH */ 2404 case F_FORWTCP: 2405 tcpbuf_dropped += f->f_dropped + 2406 tcpbuf_countmsg(f->f_un.f_forw.f_bufev); 2407 bufferevent_free(f->f_un.f_forw.f_bufev); 2408 /* FALLTHROUGH */ 2409 case F_FILE: 2410 if (f->f_type == F_FILE) { 2411 file_dropped += f->f_dropped; 2412 f->f_dropped = 0; 2413 } 2414 case F_TTY: 2415 case F_CONSOLE: 2416 case F_PIPE: 2417 (void)close(f->f_file); 2418 break; 2419 } 2420 free(f->f_program); 2421 free(f->f_hostname); 2422 if (f->f_type == F_MEMBUF) { 2423 f->f_program = NULL; 2424 f->f_hostname = NULL; 2425 log_debug("add %p to mb", f); 2426 SIMPLEQ_INSERT_HEAD(&mb, f, f_next); 2427 } else 2428 free(f); 2429 } 2430 SIMPLEQ_INIT(&Files); 2431 2432 /* open the configuration file */ 2433 if ((cf = priv_open_config()) == NULL) { 2434 log_debug("cannot open %s", ConfFile); 2435 SIMPLEQ_INSERT_TAIL(&Files, 2436 cfline("*.ERR\t/dev/console", "*", "*"), f_next); 2437 SIMPLEQ_INSERT_TAIL(&Files, 2438 cfline("*.PANIC\t*", "*", "*"), f_next); 2439 Initialized = 1; 2440 dropped_warn(&init_dropped, "during initialization"); 2441 return; 2442 } 2443 2444 /* 2445 * Foreach line in the conf table, open that file. 2446 */ 2447 cline = NULL; 2448 s = 0; 2449 strlcpy(progblock, "*", sizeof(progblock)); 2450 strlcpy(hostblock, "*", sizeof(hostblock)); 2451 send_udp = send_udp6 = 0; 2452 while (getline(&cline, &s, cf) != -1) { 2453 /* 2454 * check for end-of-section, comments, strip off trailing 2455 * spaces and newline character. !progblock and +hostblock 2456 * are treated specially: the following lines apply only to 2457 * that program. 2458 */ 2459 for (p = cline; isspace((unsigned char)*p); ++p) 2460 continue; 2461 if (*p == '\0' || *p == '#') 2462 continue; 2463 if (*p == '!' || *p == '+') { 2464 q = (*p == '!') ? progblock : hostblock; 2465 p++; 2466 while (isspace((unsigned char)*p)) 2467 p++; 2468 if (*p == '\0' || (*p == '*' && (p[1] == '\0' || 2469 isspace((unsigned char)p[1])))) { 2470 strlcpy(q, "*", NAME_MAX+1); 2471 continue; 2472 } 2473 for (i = 0; i < NAME_MAX; i++) { 2474 if (*p == '\0' || isspace((unsigned char)*p)) 2475 break; 2476 *q++ = *p++; 2477 } 2478 *q = '\0'; 2479 continue; 2480 } 2481 2482 p = cline + strlen(cline); 2483 while (p > cline) 2484 if (!isspace((unsigned char)*--p)) { 2485 p++; 2486 break; 2487 } 2488 *p = '\0'; 2489 f = cfline(cline, progblock, hostblock); 2490 if (f != NULL) 2491 SIMPLEQ_INSERT_TAIL(&Files, f, f_next); 2492 } 2493 free(cline); 2494 if (!feof(cf)) 2495 fatal("read config file"); 2496 2497 /* Match and initialize the memory buffers */ 2498 SIMPLEQ_FOREACH(f, &Files, f_next) { 2499 if (f->f_type != F_MEMBUF) 2500 continue; 2501 log_debug("Initialize membuf %s at %p", 2502 f->f_un.f_mb.f_mname, f); 2503 2504 SIMPLEQ_FOREACH(m, &mb, f_next) { 2505 if (m->f_un.f_mb.f_rb == NULL) 2506 continue; 2507 if (strcmp(m->f_un.f_mb.f_mname, 2508 f->f_un.f_mb.f_mname) == 0) 2509 break; 2510 } 2511 if (m == NULL) { 2512 log_debug("Membuf no match"); 2513 f->f_un.f_mb.f_rb = ringbuf_init(f->f_un.f_mb.f_len); 2514 if (f->f_un.f_mb.f_rb == NULL) { 2515 f->f_type = F_UNUSED; 2516 log_warn("allocate membuf"); 2517 } 2518 } else { 2519 log_debug("Membuf match f:%p, m:%p", f, m); 2520 f->f_un = m->f_un; 2521 m->f_un.f_mb.f_rb = NULL; 2522 } 2523 } 2524 2525 /* make sure remaining buffers are freed */ 2526 while (!SIMPLEQ_EMPTY(&mb)) { 2527 m = SIMPLEQ_FIRST(&mb); 2528 SIMPLEQ_REMOVE_HEAD(&mb, f_next); 2529 if (m->f_un.f_mb.f_rb != NULL) { 2530 log_warnx("mismatched membuf"); 2531 ringbuf_free(m->f_un.f_mb.f_rb); 2532 } 2533 log_debug("Freeing membuf %p", m); 2534 2535 free(m); 2536 } 2537 2538 /* close the configuration file */ 2539 (void)fclose(cf); 2540 2541 Initialized = 1; 2542 dropped_warn(&init_dropped, "during initialization"); 2543 2544 if (SecureMode) { 2545 /* 2546 * If generic UDP file descriptors are used neither 2547 * for receiving nor for sending, close them. Then 2548 * there is no useless *.514 in netstat. 2549 */ 2550 if (fd_udp != -1 && !send_udp) { 2551 close(fd_udp); 2552 fd_udp = -1; 2553 } 2554 if (fd_udp6 != -1 && !send_udp6) { 2555 close(fd_udp6); 2556 fd_udp6 = -1; 2557 } 2558 } 2559 2560 if (Debug) { 2561 SIMPLEQ_FOREACH(f, &Files, f_next) { 2562 for (i = 0; i <= LOG_NFACILITIES; i++) 2563 if (f->f_pmask[i] == INTERNAL_NOPRI) 2564 printf("X "); 2565 else 2566 printf("%d ", f->f_pmask[i]); 2567 printf("%s: ", TypeNames[f->f_type]); 2568 switch (f->f_type) { 2569 case F_FILE: 2570 case F_TTY: 2571 case F_CONSOLE: 2572 case F_PIPE: 2573 printf("%s", f->f_un.f_fname); 2574 break; 2575 2576 case F_FORWUDP: 2577 case F_FORWTCP: 2578 case F_FORWTLS: 2579 printf("%s", f->f_un.f_forw.f_loghost); 2580 break; 2581 2582 case F_USERS: 2583 for (i = 0; i < MAXUNAMES && 2584 *f->f_un.f_uname[i]; i++) 2585 printf("%s, ", f->f_un.f_uname[i]); 2586 break; 2587 2588 case F_MEMBUF: 2589 printf("%s", f->f_un.f_mb.f_mname); 2590 break; 2591 2592 } 2593 if (f->f_program || f->f_hostname) 2594 printf(" (%s, %s)", 2595 f->f_program ? f->f_program : "*", 2596 f->f_hostname ? f->f_hostname : "*"); 2597 printf("\n"); 2598 } 2599 } 2600 } 2601 2602 #define progmatches(p1, p2) \ 2603 (p1 == p2 || (p1 != NULL && p2 != NULL && strcmp(p1, p2) == 0)) 2604 2605 /* 2606 * Spot a line with a duplicate file, pipe, console, tty, or membuf target. 2607 */ 2608 struct filed * 2609 find_dup(struct filed *f) 2610 { 2611 struct filed *list; 2612 2613 SIMPLEQ_FOREACH(list, &Files, f_next) { 2614 if (list->f_quick || f->f_quick) 2615 continue; 2616 switch (list->f_type) { 2617 case F_FILE: 2618 case F_TTY: 2619 case F_CONSOLE: 2620 case F_PIPE: 2621 if (strcmp(list->f_un.f_fname, f->f_un.f_fname) == 0 && 2622 progmatches(list->f_program, f->f_program) && 2623 progmatches(list->f_hostname, f->f_hostname)) { 2624 log_debug("duplicate %s", f->f_un.f_fname); 2625 return (list); 2626 } 2627 break; 2628 case F_MEMBUF: 2629 if (strcmp(list->f_un.f_mb.f_mname, 2630 f->f_un.f_mb.f_mname) == 0 && 2631 progmatches(list->f_program, f->f_program) && 2632 progmatches(list->f_hostname, f->f_hostname)) { 2633 log_debug("duplicate membuf %s", 2634 f->f_un.f_mb.f_mname); 2635 return (list); 2636 } 2637 break; 2638 } 2639 } 2640 return (NULL); 2641 } 2642 2643 /* 2644 * Crack a configuration file line 2645 */ 2646 struct filed * 2647 cfline(char *line, char *progblock, char *hostblock) 2648 { 2649 int i, pri; 2650 size_t rb_len; 2651 char *bp, *p, *q, *proto, *host, *port, *ipproto; 2652 char buf[LOG_MAXLINE]; 2653 struct filed *xf, *f, *d; 2654 struct timeval to; 2655 2656 log_debug("cfline(\"%s\", f, \"%s\", \"%s\")", 2657 line, progblock, hostblock); 2658 2659 if ((f = calloc(1, sizeof(*f))) == NULL) 2660 fatal("allocate struct filed"); 2661 for (i = 0; i <= LOG_NFACILITIES; i++) 2662 f->f_pmask[i] = INTERNAL_NOPRI; 2663 2664 /* save program name if any */ 2665 f->f_quick = 0; 2666 if (*progblock == '!') { 2667 progblock++; 2668 f->f_quick = 1; 2669 } 2670 if (*hostblock == '+') { 2671 hostblock++; 2672 f->f_quick = 1; 2673 } 2674 if (strcmp(progblock, "*") != 0) 2675 f->f_program = strdup(progblock); 2676 if (strcmp(hostblock, "*") != 0) 2677 f->f_hostname = strdup(hostblock); 2678 2679 /* scan through the list of selectors */ 2680 for (p = line; *p && *p != '\t' && *p != ' ';) { 2681 2682 /* find the end of this facility name list */ 2683 for (q = p; *q && *q != '\t' && *q != ' ' && *q++ != '.'; ) 2684 continue; 2685 2686 /* collect priority name */ 2687 for (bp = buf; *q && !strchr("\t,; ", *q); ) 2688 *bp++ = *q++; 2689 *bp = '\0'; 2690 2691 /* skip cruft */ 2692 while (*q && strchr(",;", *q)) 2693 q++; 2694 2695 /* decode priority name */ 2696 if (*buf == '*') 2697 pri = LOG_PRIMASK + 1; 2698 else { 2699 /* ignore trailing spaces */ 2700 for (i=strlen(buf)-1; i >= 0 && buf[i] == ' '; i--) { 2701 buf[i]='\0'; 2702 } 2703 2704 pri = decode(buf, prioritynames); 2705 if (pri < 0) { 2706 log_warnx("unknown priority name \"%s\"", buf); 2707 free(f); 2708 return (NULL); 2709 } 2710 } 2711 2712 /* scan facilities */ 2713 while (*p && !strchr("\t.; ", *p)) { 2714 for (bp = buf; *p && !strchr("\t,;. ", *p); ) 2715 *bp++ = *p++; 2716 *bp = '\0'; 2717 if (*buf == '*') 2718 for (i = 0; i < LOG_NFACILITIES; i++) 2719 f->f_pmask[i] = pri; 2720 else { 2721 i = decode(buf, facilitynames); 2722 if (i < 0) { 2723 log_warnx("unknown facility name " 2724 "\"%s\"", buf); 2725 free(f); 2726 return (NULL); 2727 } 2728 f->f_pmask[i >> 3] = pri; 2729 } 2730 while (*p == ',' || *p == ' ') 2731 p++; 2732 } 2733 2734 p = q; 2735 } 2736 2737 /* skip to action part */ 2738 while (*p == '\t' || *p == ' ') 2739 p++; 2740 2741 switch (*p) { 2742 case '@': 2743 if ((strlcpy(f->f_un.f_forw.f_loghost, p, 2744 sizeof(f->f_un.f_forw.f_loghost)) >= 2745 sizeof(f->f_un.f_forw.f_loghost))) { 2746 log_warnx("loghost too long \"%s\"", p); 2747 break; 2748 } 2749 if (loghost_parse(++p, &proto, &host, &port) == -1) { 2750 log_warnx("bad loghost \"%s\"", 2751 f->f_un.f_forw.f_loghost); 2752 break; 2753 } 2754 if (proto == NULL) 2755 proto = "udp"; 2756 if (strcmp(proto, "udp") == 0) { 2757 if (fd_udp == -1) 2758 proto = "udp6"; 2759 if (fd_udp6 == -1) 2760 proto = "udp4"; 2761 } 2762 ipproto = proto; 2763 if (strcmp(proto, "udp") == 0) { 2764 send_udp = send_udp6 = 1; 2765 } else if (strcmp(proto, "udp4") == 0) { 2766 send_udp = 1; 2767 if (fd_udp == -1) { 2768 log_warnx("no udp4 \"%s\"", 2769 f->f_un.f_forw.f_loghost); 2770 break; 2771 } 2772 } else if (strcmp(proto, "udp6") == 0) { 2773 send_udp6 = 1; 2774 if (fd_udp6 == -1) { 2775 log_warnx("no udp6 \"%s\"", 2776 f->f_un.f_forw.f_loghost); 2777 break; 2778 } 2779 } else if (strcmp(proto, "tcp") == 0 || 2780 strcmp(proto, "tcp4") == 0 || strcmp(proto, "tcp6") == 0) { 2781 ; 2782 } else if (strcmp(proto, "tls") == 0) { 2783 ipproto = "tcp"; 2784 } else if (strcmp(proto, "tls4") == 0) { 2785 ipproto = "tcp4"; 2786 } else if (strcmp(proto, "tls6") == 0) { 2787 ipproto = "tcp6"; 2788 } else { 2789 log_warnx("bad protocol \"%s\"", 2790 f->f_un.f_forw.f_loghost); 2791 break; 2792 } 2793 if (strlen(host) >= NI_MAXHOST) { 2794 log_warnx("host too long \"%s\"", 2795 f->f_un.f_forw.f_loghost); 2796 break; 2797 } 2798 if (port == NULL) 2799 port = strncmp(proto, "tls", 3) == 0 ? 2800 "syslog-tls" : "syslog"; 2801 if (strlen(port) >= NI_MAXSERV) { 2802 log_warnx("port too long \"%s\"", 2803 f->f_un.f_forw.f_loghost); 2804 break; 2805 } 2806 if (priv_getaddrinfo(ipproto, host, port, 2807 (struct sockaddr*)&f->f_un.f_forw.f_addr, 2808 sizeof(f->f_un.f_forw.f_addr)) != 0) { 2809 log_warnx("bad hostname \"%s\"", 2810 f->f_un.f_forw.f_loghost); 2811 break; 2812 } 2813 f->f_file = -1; 2814 if (strncmp(proto, "udp", 3) == 0) { 2815 switch (f->f_un.f_forw.f_addr.ss_family) { 2816 case AF_INET: 2817 f->f_file = fd_udp; 2818 break; 2819 case AF_INET6: 2820 f->f_file = fd_udp6; 2821 break; 2822 } 2823 f->f_type = F_FORWUDP; 2824 } else if (strncmp(ipproto, "tcp", 3) == 0) { 2825 if ((f->f_un.f_forw.f_bufev = bufferevent_new(-1, 2826 tcp_dropcb, tcp_writecb, tcp_errorcb, f)) == NULL) { 2827 log_warn("bufferevent \"%s\"", 2828 f->f_un.f_forw.f_loghost); 2829 break; 2830 } 2831 if (strncmp(proto, "tls", 3) == 0) { 2832 f->f_un.f_forw.f_host = strdup(host); 2833 f->f_type = F_FORWTLS; 2834 } else { 2835 f->f_type = F_FORWTCP; 2836 } 2837 /* 2838 * If we try to connect to a TLS server immediately 2839 * syslogd gets an SIGPIPE as the signal handlers have 2840 * not been set up. Delay the connection until the 2841 * event loop is started. We can reuse the write event 2842 * for that as bufferevent is still disabled. 2843 */ 2844 to.tv_sec = 0; 2845 to.tv_usec = 1; 2846 evtimer_set(&f->f_un.f_forw.f_bufev->ev_write, 2847 tcp_connectcb, f); 2848 evtimer_add(&f->f_un.f_forw.f_bufev->ev_write, &to); 2849 } 2850 break; 2851 2852 case '/': 2853 case '|': 2854 (void)strlcpy(f->f_un.f_fname, p, sizeof(f->f_un.f_fname)); 2855 d = find_dup(f); 2856 if (d != NULL) { 2857 for (i = 0; i <= LOG_NFACILITIES; i++) 2858 if (f->f_pmask[i] != INTERNAL_NOPRI) 2859 d->f_pmask[i] = f->f_pmask[i]; 2860 free(f); 2861 return (NULL); 2862 } 2863 if (strcmp(p, ctty) == 0) { 2864 f->f_file = priv_open_tty(p); 2865 if (f->f_file < 0) 2866 log_warn("priv_open_tty \"%s\"", p); 2867 } else { 2868 f->f_file = priv_open_log(p); 2869 if (f->f_file < 0) 2870 log_warn("priv_open_log \"%s\"", p); 2871 } 2872 if (f->f_file < 0) { 2873 f->f_type = F_UNUSED; 2874 break; 2875 } 2876 if (isatty(f->f_file)) { 2877 if (strcmp(p, ctty) == 0) 2878 f->f_type = F_CONSOLE; 2879 else 2880 f->f_type = F_TTY; 2881 } else { 2882 if (*p == '|') 2883 f->f_type = F_PIPE; 2884 else { 2885 f->f_type = F_FILE; 2886 2887 /* Clear O_NONBLOCK flag on f->f_file */ 2888 if ((i = fcntl(f->f_file, F_GETFL)) != -1) { 2889 i &= ~O_NONBLOCK; 2890 fcntl(f->f_file, F_SETFL, i); 2891 } 2892 } 2893 } 2894 break; 2895 2896 case '*': 2897 f->f_type = F_WALL; 2898 break; 2899 2900 case ':': 2901 f->f_type = F_MEMBUF; 2902 2903 /* Parse buffer size (in kb) */ 2904 errno = 0; 2905 rb_len = strtoul(++p, &q, 0); 2906 if (*p == '\0' || (errno == ERANGE && rb_len == ULONG_MAX) || 2907 *q != ':' || rb_len == 0) { 2908 f->f_type = F_UNUSED; 2909 log_warnx("strtoul \"%s\"", p); 2910 break; 2911 } 2912 q++; 2913 rb_len *= 1024; 2914 2915 /* Copy buffer name */ 2916 for(i = 0; (size_t)i < sizeof(f->f_un.f_mb.f_mname) - 1; i++) { 2917 if (!isalnum((unsigned char)q[i])) 2918 break; 2919 f->f_un.f_mb.f_mname[i] = q[i]; 2920 } 2921 2922 /* Make sure buffer name is unique */ 2923 xf = find_dup(f); 2924 2925 /* Error on missing or non-unique name, or bad buffer length */ 2926 if (i == 0 || rb_len > MAX_MEMBUF || xf != NULL) { 2927 f->f_type = F_UNUSED; 2928 log_warnx("find_dup \"%s\"", p); 2929 break; 2930 } 2931 2932 /* Set buffer length */ 2933 rb_len = MAXIMUM(rb_len, MIN_MEMBUF); 2934 f->f_un.f_mb.f_len = rb_len; 2935 f->f_un.f_mb.f_overflow = 0; 2936 f->f_un.f_mb.f_attached = 0; 2937 break; 2938 2939 default: 2940 for (i = 0; i < MAXUNAMES && *p; i++) { 2941 for (q = p; *q && *q != ','; ) 2942 q++; 2943 (void)strncpy(f->f_un.f_uname[i], p, UT_NAMESIZE); 2944 if ((q - p) > UT_NAMESIZE) 2945 f->f_un.f_uname[i][UT_NAMESIZE] = '\0'; 2946 else 2947 f->f_un.f_uname[i][q - p] = '\0'; 2948 while (*q == ',' || *q == ' ') 2949 q++; 2950 p = q; 2951 } 2952 f->f_type = F_USERS; 2953 break; 2954 } 2955 return (f); 2956 } 2957 2958 /* 2959 * Parse the host and port parts from a loghost string. 2960 */ 2961 int 2962 loghost_parse(char *str, char **proto, char **host, char **port) 2963 { 2964 char *prefix = NULL; 2965 2966 if ((*host = strchr(str, ':')) && 2967 (*host)[1] == '/' && (*host)[2] == '/') { 2968 prefix = str; 2969 **host = '\0'; 2970 str = *host + 3; 2971 } 2972 if (proto) 2973 *proto = prefix; 2974 else if (prefix) 2975 return (-1); 2976 2977 *host = str; 2978 if (**host == '[') { 2979 (*host)++; 2980 str = strchr(*host, ']'); 2981 if (str == NULL) 2982 return (-1); 2983 *str++ = '\0'; 2984 } 2985 *port = strrchr(str, ':'); 2986 if (*port != NULL) 2987 *(*port)++ = '\0'; 2988 2989 return (0); 2990 } 2991 2992 /* 2993 * Retrieve the size of the kernel message buffer, via sysctl. 2994 */ 2995 int 2996 getmsgbufsize(void) 2997 { 2998 int msgbufsize, mib[2]; 2999 size_t size; 3000 3001 mib[0] = CTL_KERN; 3002 mib[1] = KERN_MSGBUFSIZE; 3003 size = sizeof msgbufsize; 3004 if (sysctl(mib, 2, &msgbufsize, &size, NULL, 0) == -1) { 3005 log_debug("couldn't get kern.msgbufsize"); 3006 return (0); 3007 } 3008 return (msgbufsize); 3009 } 3010 3011 /* 3012 * Decode a symbolic name to a numeric value 3013 */ 3014 int 3015 decode(const char *name, const CODE *codetab) 3016 { 3017 const CODE *c; 3018 char *p, buf[40]; 3019 3020 for (p = buf; *name && p < &buf[sizeof(buf) - 1]; p++, name++) { 3021 if (isupper((unsigned char)*name)) 3022 *p = tolower((unsigned char)*name); 3023 else 3024 *p = *name; 3025 } 3026 *p = '\0'; 3027 for (c = codetab; c->c_name; c++) 3028 if (!strcmp(buf, c->c_name)) 3029 return (c->c_val); 3030 3031 return (-1); 3032 } 3033 3034 void 3035 markit(void) 3036 { 3037 struct filed *f; 3038 3039 (void)gettimeofday(&now, NULL); 3040 MarkSeq += TIMERINTVL; 3041 if (MarkSeq >= MarkInterval) { 3042 logline(LOG_INFO, ADDDATE|MARK, LocalHostName, "-- MARK --"); 3043 MarkSeq = 0; 3044 } 3045 3046 SIMPLEQ_FOREACH(f, &Files, f_next) { 3047 if (f->f_prevcount && now.tv_sec >= REPEATTIME(f)) { 3048 log_debug("flush %s: repeated %d times, %d sec", 3049 TypeNames[f->f_type], f->f_prevcount, 3050 repeatinterval[f->f_repeatcount]); 3051 fprintlog(f, 0, (char *)NULL); 3052 BACKOFF(f); 3053 } 3054 } 3055 } 3056 3057 int 3058 unix_socket(char *path, int type, mode_t mode) 3059 { 3060 struct sockaddr_un s_un; 3061 int fd, optval; 3062 mode_t old_umask; 3063 3064 memset(&s_un, 0, sizeof(s_un)); 3065 s_un.sun_family = AF_UNIX; 3066 if (strlcpy(s_un.sun_path, path, sizeof(s_un.sun_path)) >= 3067 sizeof(s_un.sun_path)) { 3068 log_warnx("socket path too long \"%s\"", path); 3069 return (-1); 3070 } 3071 3072 if ((fd = socket(AF_UNIX, type, 0)) == -1) { 3073 log_warn("socket unix \"%s\"", path); 3074 return (-1); 3075 } 3076 3077 if (Debug) { 3078 if (connect(fd, (struct sockaddr *)&s_un, sizeof(s_un)) == 0 || 3079 errno == EPROTOTYPE) { 3080 close(fd); 3081 errno = EISCONN; 3082 log_warn("connect unix \"%s\"", path); 3083 return (-1); 3084 } 3085 } 3086 3087 old_umask = umask(0177); 3088 3089 unlink(path); 3090 if (bind(fd, (struct sockaddr *)&s_un, sizeof(s_un)) == -1) { 3091 log_warn("bind unix \"%s\"", path); 3092 umask(old_umask); 3093 close(fd); 3094 return (-1); 3095 } 3096 3097 umask(old_umask); 3098 3099 if (chmod(path, mode) == -1) { 3100 log_warn("chmod unix \"%s\"", path); 3101 close(fd); 3102 unlink(path); 3103 return (-1); 3104 } 3105 3106 optval = LOG_MAXLINE + PATH_MAX; 3107 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &optval, sizeof(optval)) 3108 == -1) 3109 log_warn("setsockopt unix \"%s\"", path); 3110 3111 return (fd); 3112 } 3113 3114 /* 3115 * Increase socket buffer size in small steps to get partial success 3116 * if we hit a kernel limit. Allow an optional final step. 3117 */ 3118 void 3119 double_sockbuf(int fd, int optname, int bigsize) 3120 { 3121 socklen_t len; 3122 int i, newsize, oldsize = 0; 3123 3124 len = sizeof(oldsize); 3125 if (getsockopt(fd, SOL_SOCKET, optname, &oldsize, &len) == -1) 3126 log_warn("getsockopt bufsize"); 3127 len = sizeof(newsize); 3128 newsize = LOG_MAXLINE + 128; /* data + control */ 3129 /* allow 8 full length messages, that is 66560 bytes */ 3130 for (i = 0; i < 4; i++, newsize *= 2) { 3131 if (newsize <= oldsize) 3132 continue; 3133 if (setsockopt(fd, SOL_SOCKET, optname, &newsize, len) == -1) 3134 log_warn("setsockopt bufsize %d", newsize); 3135 else 3136 oldsize = newsize; 3137 } 3138 if (bigsize && bigsize > oldsize) { 3139 if (setsockopt(fd, SOL_SOCKET, optname, &bigsize, len) == -1) 3140 log_warn("setsockopt bufsize %d", bigsize); 3141 } 3142 } 3143 3144 void 3145 set_sockbuf(int fd) 3146 { 3147 int size = 65536; 3148 3149 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &size, sizeof(size)) == -1) 3150 log_warn("setsockopt sndbufsize %d", size); 3151 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size)) == -1) 3152 log_warn("setsockopt rcvbufsize %d", size); 3153 } 3154 3155 void 3156 set_keepalive(int fd) 3157 { 3158 int val = 1; 3159 3160 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(val)) == -1) 3161 log_warn("setsockopt keepalive %d", val); 3162 } 3163 3164 void 3165 ctlconn_cleanup(void) 3166 { 3167 struct filed *f; 3168 3169 close(fd_ctlconn); 3170 fd_ctlconn = -1; 3171 event_del(ev_ctlread); 3172 event_del(ev_ctlwrite); 3173 event_add(ev_ctlaccept, NULL); 3174 3175 if (ctl_state == CTL_WRITING_CONT_REPLY) 3176 SIMPLEQ_FOREACH(f, &Files, f_next) 3177 if (f->f_type == F_MEMBUF) 3178 f->f_un.f_mb.f_attached = 0; 3179 3180 ctl_state = ctl_cmd_bytes = ctl_reply_offset = ctl_reply_size = 0; 3181 } 3182 3183 void 3184 ctlsock_acceptcb(int fd, short event, void *arg) 3185 { 3186 struct event *ev = arg; 3187 3188 if ((fd = reserve_accept4(fd, event, ev, ctlsock_acceptcb, 3189 NULL, NULL, SOCK_NONBLOCK)) == -1) { 3190 if (errno != ENFILE && errno != EMFILE && 3191 errno != EINTR && errno != EWOULDBLOCK && 3192 errno != ECONNABORTED) 3193 log_warn("accept control socket"); 3194 return; 3195 } 3196 log_debug("Accepting control connection"); 3197 3198 if (fd_ctlconn != -1) 3199 ctlconn_cleanup(); 3200 3201 /* Only one connection at a time */ 3202 event_del(ev); 3203 3204 fd_ctlconn = fd; 3205 /* file descriptor has changed, reset event */ 3206 event_set(ev_ctlread, fd_ctlconn, EV_READ|EV_PERSIST, 3207 ctlconn_readcb, ev_ctlread); 3208 event_set(ev_ctlwrite, fd_ctlconn, EV_WRITE|EV_PERSIST, 3209 ctlconn_writecb, ev_ctlwrite); 3210 event_add(ev_ctlread, NULL); 3211 ctl_state = CTL_READING_CMD; 3212 ctl_cmd_bytes = 0; 3213 } 3214 3215 static struct filed 3216 *find_membuf_log(const char *name) 3217 { 3218 struct filed *f; 3219 3220 SIMPLEQ_FOREACH(f, &Files, f_next) { 3221 if (f->f_type == F_MEMBUF && 3222 strcmp(f->f_un.f_mb.f_mname, name) == 0) 3223 break; 3224 } 3225 return (f); 3226 } 3227 3228 void 3229 ctlconn_readcb(int fd, short event, void *arg) 3230 { 3231 struct filed *f; 3232 struct ctl_reply_hdr *reply_hdr = (struct ctl_reply_hdr *)ctl_reply; 3233 ssize_t n; 3234 u_int32_t flags = 0; 3235 3236 if (ctl_state == CTL_WRITING_REPLY || 3237 ctl_state == CTL_WRITING_CONT_REPLY) { 3238 /* client has closed the connection */ 3239 ctlconn_cleanup(); 3240 return; 3241 } 3242 3243 retry: 3244 n = read(fd, (char*)&ctl_cmd + ctl_cmd_bytes, 3245 sizeof(ctl_cmd) - ctl_cmd_bytes); 3246 switch (n) { 3247 case -1: 3248 if (errno == EINTR) 3249 goto retry; 3250 if (errno == EWOULDBLOCK) 3251 return; 3252 log_warn("read control socket"); 3253 /* FALLTHROUGH */ 3254 case 0: 3255 ctlconn_cleanup(); 3256 return; 3257 default: 3258 ctl_cmd_bytes += n; 3259 } 3260 if (ctl_cmd_bytes < sizeof(ctl_cmd)) 3261 return; 3262 3263 if (ntohl(ctl_cmd.version) != CTL_VERSION) { 3264 log_warnx("unknown client protocol version"); 3265 ctlconn_cleanup(); 3266 return; 3267 } 3268 3269 /* Ensure that logname is \0 terminated */ 3270 if (memchr(ctl_cmd.logname, '\0', sizeof(ctl_cmd.logname)) == NULL) { 3271 log_warnx("corrupt control socket command"); 3272 ctlconn_cleanup(); 3273 return; 3274 } 3275 3276 *reply_text = '\0'; 3277 3278 ctl_reply_size = ctl_reply_offset = 0; 3279 memset(reply_hdr, '\0', sizeof(*reply_hdr)); 3280 3281 ctl_cmd.cmd = ntohl(ctl_cmd.cmd); 3282 log_debug("ctlcmd %x logname \"%s\"", ctl_cmd.cmd, ctl_cmd.logname); 3283 3284 switch (ctl_cmd.cmd) { 3285 case CMD_READ: 3286 case CMD_READ_CLEAR: 3287 case CMD_READ_CONT: 3288 case CMD_FLAGS: 3289 f = find_membuf_log(ctl_cmd.logname); 3290 if (f == NULL) { 3291 strlcpy(reply_text, "No such log\n", MAX_MEMBUF); 3292 } else { 3293 if (ctl_cmd.cmd != CMD_FLAGS) { 3294 ringbuf_to_string(reply_text, MAX_MEMBUF, 3295 f->f_un.f_mb.f_rb); 3296 } 3297 if (f->f_un.f_mb.f_overflow) 3298 flags |= CTL_HDR_FLAG_OVERFLOW; 3299 if (ctl_cmd.cmd == CMD_READ_CLEAR) { 3300 ringbuf_clear(f->f_un.f_mb.f_rb); 3301 f->f_un.f_mb.f_overflow = 0; 3302 } 3303 if (ctl_cmd.cmd == CMD_READ_CONT) { 3304 f->f_un.f_mb.f_attached = 1; 3305 tailify_replytext(reply_text, 3306 ctl_cmd.lines > 0 ? ctl_cmd.lines : 10); 3307 } else if (ctl_cmd.lines > 0) { 3308 tailify_replytext(reply_text, ctl_cmd.lines); 3309 } 3310 } 3311 break; 3312 case CMD_CLEAR: 3313 f = find_membuf_log(ctl_cmd.logname); 3314 if (f == NULL) { 3315 strlcpy(reply_text, "No such log\n", MAX_MEMBUF); 3316 } else { 3317 ringbuf_clear(f->f_un.f_mb.f_rb); 3318 if (f->f_un.f_mb.f_overflow) 3319 flags |= CTL_HDR_FLAG_OVERFLOW; 3320 f->f_un.f_mb.f_overflow = 0; 3321 strlcpy(reply_text, "Log cleared\n", MAX_MEMBUF); 3322 } 3323 break; 3324 case CMD_LIST: 3325 SIMPLEQ_FOREACH(f, &Files, f_next) { 3326 if (f->f_type == F_MEMBUF) { 3327 strlcat(reply_text, f->f_un.f_mb.f_mname, 3328 MAX_MEMBUF); 3329 if (f->f_un.f_mb.f_overflow) { 3330 strlcat(reply_text, "*", MAX_MEMBUF); 3331 flags |= CTL_HDR_FLAG_OVERFLOW; 3332 } 3333 strlcat(reply_text, " ", MAX_MEMBUF); 3334 } 3335 } 3336 strlcat(reply_text, "\n", MAX_MEMBUF); 3337 break; 3338 default: 3339 log_warnx("unsupported control socket command"); 3340 ctlconn_cleanup(); 3341 return; 3342 } 3343 reply_hdr->version = htonl(CTL_VERSION); 3344 reply_hdr->flags = htonl(flags); 3345 3346 ctl_reply_size = CTL_REPLY_SIZE; 3347 log_debug("ctlcmd reply length %lu", (u_long)ctl_reply_size); 3348 3349 /* Otherwise, set up to write out reply */ 3350 ctl_state = (ctl_cmd.cmd == CMD_READ_CONT) ? 3351 CTL_WRITING_CONT_REPLY : CTL_WRITING_REPLY; 3352 3353 event_add(ev_ctlwrite, NULL); 3354 3355 /* another syslogc can kick us out */ 3356 if (ctl_state == CTL_WRITING_CONT_REPLY) 3357 event_add(ev_ctlaccept, NULL); 3358 } 3359 3360 void 3361 ctlconn_writecb(int fd, short event, void *arg) 3362 { 3363 struct event *ev = arg; 3364 ssize_t n; 3365 3366 if (!(ctl_state == CTL_WRITING_REPLY || 3367 ctl_state == CTL_WRITING_CONT_REPLY)) { 3368 /* Shouldn't be here! */ 3369 log_warnx("control socket write with bad state"); 3370 ctlconn_cleanup(); 3371 return; 3372 } 3373 3374 retry: 3375 n = write(fd, ctl_reply + ctl_reply_offset, 3376 ctl_reply_size - ctl_reply_offset); 3377 switch (n) { 3378 case -1: 3379 if (errno == EINTR) 3380 goto retry; 3381 if (errno == EWOULDBLOCK) 3382 return; 3383 if (errno != EPIPE) 3384 log_warn("write control socket"); 3385 /* FALLTHROUGH */ 3386 case 0: 3387 ctlconn_cleanup(); 3388 return; 3389 default: 3390 ctl_reply_offset += n; 3391 } 3392 if (ctl_reply_offset < ctl_reply_size) 3393 return; 3394 3395 if (ctl_state != CTL_WRITING_CONT_REPLY) { 3396 ctlconn_cleanup(); 3397 return; 3398 } 3399 3400 /* 3401 * Make space in the buffer for continous writes. 3402 * Set offset behind reply header to skip it 3403 */ 3404 *reply_text = '\0'; 3405 ctl_reply_offset = ctl_reply_size = CTL_REPLY_SIZE; 3406 3407 /* Now is a good time to report dropped lines */ 3408 if (membuf_drop) { 3409 strlcat(reply_text, "<ENOBUFS>\n", MAX_MEMBUF); 3410 ctl_reply_size = CTL_REPLY_SIZE; 3411 membuf_drop = 0; 3412 } else { 3413 /* Nothing left to write */ 3414 event_del(ev); 3415 } 3416 } 3417 3418 /* Shorten replytext to number of lines */ 3419 void 3420 tailify_replytext(char *replytext, int lines) 3421 { 3422 char *start, *nl; 3423 int count = 0; 3424 start = nl = replytext; 3425 3426 while ((nl = strchr(nl, '\n')) != NULL) { 3427 nl++; 3428 if (++count > lines) { 3429 start = strchr(start, '\n'); 3430 start++; 3431 } 3432 } 3433 if (start != replytext) { 3434 int len = strlen(start); 3435 memmove(replytext, start, len); 3436 *(replytext + len) = '\0'; 3437 } 3438 } 3439 3440 void 3441 ctlconn_logto(char *line) 3442 { 3443 size_t l; 3444 3445 if (membuf_drop) 3446 return; 3447 3448 l = strlen(line); 3449 if (l + 2 > (CTL_REPLY_MAXSIZE - ctl_reply_size)) { 3450 /* remember line drops for later report */ 3451 membuf_drop = 1; 3452 return; 3453 } 3454 memcpy(ctl_reply + ctl_reply_size, line, l); 3455 memcpy(ctl_reply + ctl_reply_size + l, "\n", 2); 3456 ctl_reply_size += l + 1; 3457 event_add(ev_ctlwrite, NULL); 3458 } 3459