1 #include "first.h" 2 3 #include "base.h" 4 #include "buffer.h" 5 #include "network.h" 6 #include "log.h" 7 #include "rand.h" 8 #include "chunk.h" 9 #include "h2.h" /* h2_send_1xx() */ 10 #include "http_range.h" /* http_range_config_allow_http10() */ 11 #include "fdevent.h" 12 #include "fdlog.h" 13 #include "connections.h" 14 #include "sock_addr.h" 15 #include "stat_cache.h" 16 #include "plugin.h" 17 #include "plugins.h" 18 #include "plugin_config.h" /* config_plugin_value_tobool() */ 19 #include "network_write.h" /* network_write_show_handlers() */ 20 #include "reqpool.h" /* request_pool_init() request_pool_free() */ 21 #include "response.h" /* http_response_send_1xx_cb_set() strftime_cache_reset() */ 22 23 #ifdef HAVE_VERSIONSTAMP_H 24 # include "versionstamp.h" 25 #else 26 # define REPO_VERSION "" 27 #endif 28 29 #define PACKAGE_DESC PACKAGE_NAME "/" PACKAGE_VERSION REPO_VERSION 30 static const buffer default_server_tag = 31 { PACKAGE_DESC "\0server", sizeof(PACKAGE_DESC), 0 }; 32 33 #include <sys/types.h> 34 #include <sys/stat.h> 35 #include "sys-setjmp.h" 36 #include "sys-time.h" 37 38 #include <string.h> 39 #include <errno.h> 40 #include <fcntl.h> 41 #include <unistd.h> 42 #include <stdlib.h> 43 #include <signal.h> 44 #include <locale.h> 45 46 #include <stdio.h> 47 48 #ifdef HAVE_GETOPT_H 49 # include <getopt.h> 50 #endif 51 52 #ifdef HAVE_VALGRIND_VALGRIND_H 53 # include <valgrind/valgrind.h> 54 #endif 55 56 #ifdef HAVE_PWD_H 57 # include <grp.h> 58 # include <pwd.h> 59 #endif 60 61 #ifdef HAVE_SYS_LOADAVG_H 62 # include <sys/loadavg.h> 63 #endif 64 65 #ifdef HAVE_SYS_RESOURCE_H 66 # include <sys/resource.h> 67 #endif 68 69 #ifdef HAVE_SYS_PRCTL_H 70 # include <sys/prctl.h> 71 #endif 72 #ifdef HAVE_SYS_PROCCTL_H 73 # include <sys/procctl.h> 74 #endif 75 #ifdef HAVE_PRIV_H 76 # include <priv.h> 77 #endif 78 79 #ifdef HAVE_MALLOC_H 80 #ifndef LIGHTTPD_STATIC 81 #ifdef HAVE_DLFCN_H 82 #include <dlfcn.h> 83 #endif 84 #endif 85 #include <malloc.h> 86 #if defined(HAVE_MALLOC_TRIM) 87 static int(*malloc_trim_fn)(size_t); 88 static size_t malloc_top_pad; 89 #endif 90 #endif 91 92 #include "sys-crypto.h" 93 #if defined(USE_OPENSSL_CRYPTO) \ 94 || defined(USE_MBEDTLS_CRYPTO) \ 95 || defined(USE_NSS_CRYPTO) \ 96 || defined(USE_GNUTLS_CRYPTO) \ 97 || defined(USE_WOLFTLS_CRYPTO) 98 #define TEXT_SSL " (ssl)" 99 #else 100 #define TEXT_SSL 101 #endif 102 103 #ifndef __sgi 104 /* IRIX doesn't like the alarm based time() optimization */ 105 /* #define USE_ALARM */ 106 #endif 107 108 static int oneshot_fd = 0; 109 static int oneshot_fdout = -1; 110 static fdnode *oneshot_fdn = NULL; 111 static int (*oneshot_read_cq)(connection *con, chunkqueue *cq, off_t max_bytes); 112 static volatile int pid_fd = -2; 113 static server_socket_array graceful_sockets; 114 static server_socket_array inherited_sockets; 115 static volatile sig_atomic_t graceful_restart = 0; 116 static volatile sig_atomic_t graceful_shutdown = 0; 117 static volatile sig_atomic_t srv_shutdown = 0; 118 static volatile sig_atomic_t handle_sig_child = 0; 119 static volatile sig_atomic_t handle_sig_alarm = 1; 120 static volatile sig_atomic_t handle_sig_hup = 0; 121 static int idle_limit = 0; 122 123 #if defined(HAVE_SIGACTION) && defined(SA_SIGINFO) 124 static volatile siginfo_t last_sigterm_info; 125 static volatile siginfo_t last_sighup_info; 126 127 static void sigaction_handler(int sig, siginfo_t *si, void *context) { 128 static const siginfo_t empty_siginfo; 129 UNUSED(context); 130 131 if (!si) *(const siginfo_t **)&si = &empty_siginfo; 132 133 switch (sig) { 134 case SIGTERM: 135 srv_shutdown = 1; 136 last_sigterm_info = *si; 137 break; 138 case SIGUSR1: 139 if (!graceful_shutdown) { 140 graceful_restart = 1; 141 graceful_shutdown = 1; 142 last_sigterm_info = *si; 143 } 144 break; 145 case SIGINT: 146 if (graceful_shutdown) { 147 if (2 == graceful_restart) 148 graceful_restart = 1; 149 else 150 srv_shutdown = 1; 151 } else { 152 graceful_shutdown = 1; 153 } 154 last_sigterm_info = *si; 155 156 break; 157 case SIGALRM: 158 handle_sig_alarm = 1; 159 break; 160 case SIGHUP: 161 handle_sig_hup = 1; 162 last_sighup_info = *si; 163 break; 164 case SIGCHLD: 165 handle_sig_child = 1; 166 break; 167 } 168 } 169 #elif defined(HAVE_SIGNAL) || defined(HAVE_SIGACTION) 170 static void signal_handler(int sig) { 171 switch (sig) { 172 case SIGTERM: srv_shutdown = 1; break; 173 case SIGUSR1: 174 if (!graceful_shutdown) { 175 graceful_restart = 1; 176 graceful_shutdown = 1; 177 } 178 break; 179 case SIGINT: 180 if (graceful_shutdown) { 181 if (2 == graceful_restart) 182 graceful_restart = 1; 183 else 184 srv_shutdown = 1; 185 } else { 186 graceful_shutdown = 1; 187 } 188 break; 189 case SIGALRM: handle_sig_alarm = 1; break; 190 case SIGHUP: handle_sig_hup = 1; break; 191 case SIGCHLD: handle_sig_child = 1; break; 192 } 193 } 194 #endif 195 196 #ifdef HAVE_FORK 197 static int daemonize(void) { 198 int pipefd[2]; 199 pid_t pid; 200 #ifdef SIGTTOU 201 signal(SIGTTOU, SIG_IGN); 202 #endif 203 #ifdef SIGTTIN 204 signal(SIGTTIN, SIG_IGN); 205 #endif 206 #ifdef SIGTSTP 207 signal(SIGTSTP, SIG_IGN); 208 #endif 209 210 if (fdevent_pipe_cloexec(pipefd, 64) < 0) exit(-1); 211 212 if (0 > (pid = fork())) exit(-1); 213 214 if (0 < pid) { 215 char buf; 216 ssize_t bytes; 217 218 close(pipefd[1]); 219 /* parent waits for grandchild to be ready */ 220 do { 221 bytes = read(pipefd[0], &buf, sizeof(buf)); 222 } while (bytes < 0 && EINTR == errno); 223 close(pipefd[0]); 224 225 if (bytes <= 0) { 226 /* closed fd (without writing) == failure in grandchild */ 227 fputs("daemonized server failed to start; check error log for details\n", stderr); 228 exit(-1); 229 } 230 231 exit(0); 232 } 233 234 close(pipefd[0]); 235 236 if (-1 == setsid()) exit(0); 237 238 signal(SIGHUP, SIG_IGN); 239 240 if (0 != fork()) exit(0); 241 242 if (0 != chdir("/")) exit(0); 243 244 return pipefd[1]; 245 } 246 #endif 247 248 static int clockid_mono_coarse = 0; 249 250 static unix_time64_t 251 server_monotonic_secs (void) 252 { 253 unix_timespec64_t ts; 254 return (0 == log_clock_gettime(clockid_mono_coarse, &ts)) 255 ? ts.tv_sec 256 : log_monotonic_secs; 257 } 258 259 static unix_time64_t 260 server_epoch_secs (server * const srv, unix_time64_t mono_ts_delta) 261 { 262 const unix_time64_t cur_ts = log_epoch_secs; 263 const unix_time64_t new_ts = TIME64_CAST(time(NULL)); 264 const unix_time64_t new_ts_adj = new_ts - mono_ts_delta; 265 /* attempt to detect large clock jump */ 266 if (new_ts_adj < cur_ts || new_ts_adj - cur_ts > 300) { /*(5 mins)*/ 267 log_error(srv->errh, __FILE__, __LINE__, 268 "warning: clock jumped %lld secs", 269 (long long)((int64_t)new_ts_adj - (int64_t)cur_ts)); 270 int delta = /*(30 mins default)*/ 271 config_feature_int(srv, "server.clock-jump-restart", 1800); 272 if (delta && (new_ts_adj > cur_ts 273 ? new_ts_adj-cur_ts 274 : cur_ts-new_ts_adj) > delta) { 275 log_error(srv->errh, __FILE__, __LINE__, 276 "attempting graceful restart in < ~5 seconds, else hard restart"); 277 srv->graceful_expire_ts = log_monotonic_secs + 5; 278 raise(SIGUSR1); 279 } 280 } 281 return new_ts; 282 } 283 284 __attribute_cold__ 285 __attribute_noinline__ 286 __attribute_returns_nonnull__ 287 static server *server_init(void) { 288 server *srv = calloc(1, sizeof(*srv)); 289 force_assert(srv); 290 291 srv->tmp_buf = buffer_init(); 292 293 strftime_cache_reset(); 294 295 li_rand_reseed(); 296 297 srv->startup_ts = log_epoch_secs = TIME64_CAST(time(NULL)); 298 #ifdef HAVE_CLOCK_GETTIME 299 unix_timespec64_t ts; 300 UNUSED(&ts); 301 #ifdef CLOCK_MONOTONIC_COARSE 302 if (0 == log_clock_gettime(CLOCK_MONOTONIC_COARSE, &ts)) 303 clockid_mono_coarse = CLOCK_MONOTONIC_COARSE; 304 else 305 #endif 306 #ifdef CLOCK_MONOTONIC_RAW_APPROX 307 if (0 == log_clock_gettime(CLOCK_MONOTONIC_RAW_APPROX, &ts)) 308 clockid_mono_coarse = CLOCK_MONOTONIC_RAW_APPROX; 309 else 310 #endif 311 #ifdef CLOCK_MONOTONIC_RAW 312 if (0 == log_clock_gettime(CLOCK_MONOTONIC_RAW, &ts)) 313 clockid_mono_coarse = CLOCK_MONOTONIC_RAW; 314 else 315 #endif 316 clockid_mono_coarse = CLOCK_MONOTONIC; 317 #endif 318 log_monotonic_secs = server_monotonic_secs(); 319 320 srv->errh = log_set_global_errh(NULL, 0); 321 322 config_init(srv); 323 324 srv->request_env = plugins_call_handle_request_env; 325 srv->plugins_request_reset = plugins_call_handle_request_reset; 326 327 srv->loadavg[0] = 0.0; 328 srv->loadavg[1] = 0.0; 329 srv->loadavg[2] = 0.0; 330 srv->stdin_fd = -1; 331 332 log_con_jqueue = (connection *)(uintptr_t)&log_con_jqueue;/*(sentinel)*/ 333 334 return srv; 335 } 336 337 __attribute_cold__ 338 __attribute_noinline__ 339 static void server_free(server *srv) { 340 if (oneshot_fd > 0) { 341 if (oneshot_fdn) { 342 fdevent_fdnode_event_del(srv->ev, oneshot_fdn); 343 fdevent_unregister(srv->ev, oneshot_fd); 344 oneshot_fdn = NULL; 345 } 346 close(oneshot_fd); 347 } 348 if (oneshot_fdout >= 0) { 349 close(oneshot_fdout); 350 } 351 if (srv->stdin_fd >= 0) { 352 close(srv->stdin_fd); 353 } 354 355 buffer_free(srv->tmp_buf); 356 357 fdevent_free(srv->ev); 358 359 config_free(srv); 360 361 stat_cache_free(); 362 363 li_rand_cleanup(); 364 chunkqueue_chunk_pool_free(); 365 366 if (srv->errh != log_set_global_errh(NULL, 0)) 367 fdlog_free(srv->errh); 368 free(srv); 369 } 370 371 __attribute_cold__ 372 __attribute_noinline__ 373 static void remove_pid_file(server *srv) { 374 if (pid_fd <= -2) return; 375 if (srv->srvconf.pid_file && 0 <= pid_fd) { 376 if (0 != ftruncate(pid_fd, 0)) { 377 log_perror(srv->errh, __FILE__, __LINE__, 378 "ftruncate failed for: %s", srv->srvconf.pid_file->ptr); 379 } 380 } 381 if (0 <= pid_fd) { 382 close(pid_fd); 383 pid_fd = -1; 384 } 385 if (srv->srvconf.pid_file && !srv->srvconf.changeroot) { 386 if (0 != unlink(srv->srvconf.pid_file->ptr)) { 387 if (errno != EACCES && errno != EPERM) { 388 log_perror(srv->errh, __FILE__, __LINE__, 389 "unlink failed for: %s", srv->srvconf.pid_file->ptr); 390 } 391 } 392 } 393 } 394 395 396 __attribute_cold__ 397 static server_socket * server_oneshot_getsock(server *srv, sock_addr *cnt_addr) { 398 server_socket *srv_socket, *srv_socket_wild = NULL; 399 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) { 400 srv_socket = srv->srv_sockets.ptr[i]; 401 if (!sock_addr_is_port_eq(&srv_socket->addr,cnt_addr)) continue; 402 if (sock_addr_is_addr_eq(&srv_socket->addr,cnt_addr)) return srv_socket; 403 404 if (NULL != srv_socket_wild) continue; 405 if (sock_addr_is_addr_wildcard(&srv_socket->addr)) { 406 srv_socket_wild = srv_socket; 407 } 408 } 409 410 if (NULL != srv_socket_wild) { 411 return srv_socket_wild; 412 } else if (srv->srv_sockets.used) { 413 return srv->srv_sockets.ptr[0]; 414 } else { 415 log_error(srv->errh, __FILE__, __LINE__, "no sockets configured"); 416 return NULL; 417 } 418 } 419 420 421 static int server_oneshot_read_cq(connection *con, chunkqueue *cq, off_t max_bytes) { 422 /* temporary set con->fd to oneshot_fd (fd input) rather than outshot_fdout 423 * (lighttpd generally assumes operation on sockets, so this is a kludge) */ 424 int fd = con->fd; 425 con->fd = oneshot_fdn->fd; 426 int rc = oneshot_read_cq(con, cq, max_bytes); 427 con->fd = fd; 428 429 /* note: optimistic reads (elsewhere) may or may not be enough to re-enable 430 * read interest after FDEVENT_IN interest was paused for other reasons */ 431 432 const int events = fdevent_fdnode_interest(oneshot_fdn); 433 int n = con->is_readable > 0 ? 0 : FDEVENT_IN; 434 if (events & FDEVENT_RDHUP) 435 n |= FDEVENT_RDHUP; 436 fdevent_fdnode_event_set(con->srv->ev, oneshot_fdn, n); 437 return rc; 438 } 439 440 441 static handler_t server_oneshot_handle_fdevent(void *context, int revents) { 442 connection *con = context; 443 444 /* note: not sync'd with con->fdn or connection_set_fdevent_interest() */ 445 int rdhup = 0; 446 int n = fdevent_fdnode_interest(oneshot_fdn); 447 if (revents & FDEVENT_IN) 448 n &= ~FDEVENT_IN; 449 request_st * const r = &con->request; 450 if (r->state != CON_STATE_ERROR && (revents & (FDEVENT_HUP|FDEVENT_RDHUP))){ 451 revents &= ~(FDEVENT_HUP|FDEVENT_RDHUP); 452 /* copied and modified from connection_handle_fdevent() 453 * fdevent_is_tcp_half_closed() will fail on pipe 454 * and, besides, read end of pipes should treat POLLHUP as POLLRDHUP */ 455 n &= ~(FDEVENT_IN|FDEVENT_RDHUP); 456 rdhup = 1; 457 } 458 fdevent_fdnode_event_set(con->srv->ev, oneshot_fdn, n); 459 460 fdnode * const fdn = con->fdn; /* fdn->ctx == con */ 461 handler_t rc = (fdn && (fdevent_handler)NULL != fdn->handler) 462 ? (*fdn->handler)(con, revents) 463 : HANDLER_FINISHED; 464 465 if (rdhup) { 466 r->conf.stream_request_body &= 467 ~(FDEVENT_STREAM_REQUEST_BUFMIN|FDEVENT_STREAM_REQUEST_POLLIN); 468 r->conf.stream_request_body |= FDEVENT_STREAM_REQUEST_POLLRDHUP; 469 r->conf.stream_request_body |= FDEVENT_STREAM_REQUEST_TCP_FIN; 470 con->is_readable = 1; /*(can read 0 for end-of-stream)*/ 471 if (chunkqueue_is_empty(con->read_queue)) r->keep_alive = 0; 472 if (r->reqbody_length < -1) /*(transparent proxy mode; no more data)*/ 473 r->reqbody_length = r->reqbody_queue.bytes_in; 474 } 475 476 return rc; 477 } 478 479 480 __attribute_cold__ 481 static int server_oneshot_init_pipe(server *srv, int fdin, int fdout) { 482 /* Note: attempt to work with netcat pipes though other code expects socket. 483 * netcat has different fds (pipes) for stdin and stdout. To support 484 * netcat, need to avoid S_ISSOCK(), getsockname(), and getpeername(), 485 * reconstructing addresses from environment variables: 486 * NCAT_LOCAL_ADDR NCAT_LOCAL_PORT 487 * NCAT_REMOTE_ADDR NCAT_REMOTE_PORT 488 * NCAT_PROTO (TCP, UDP, SCTP) 489 */ 490 connection *con; 491 const server_socket *srv_socket; 492 sock_addr cnt_addr; 493 494 /* detect if called from netcat or else fabricate localhost addrs */ 495 const char * const ncat = 496 getenv("NCAT_LOCAL_ADDR"); 497 const char * const ncat_local_addr = 498 ncat ? ncat : "127.0.0.1"; /*(fabricated)*/ 499 const char * const ncat_local_port = 500 ncat ? getenv("NCAT_LOCAL_PORT") : "80"; /*(fabricated)*/ 501 const char * const ncat_remote_addr = 502 ncat ? getenv("NCAT_REMOTE_ADDR") : "127.0.0.1"; /*(fabricated)*/ 503 const char * const ncat_remote_port = 504 ncat ? getenv("NCAT_REMOTE_PORT") : "48080"; /*(fabricated)*/ 505 if (NULL == ncat_local_addr || NULL == ncat_local_port) return 0; 506 if (NULL == ncat_remote_addr || NULL == ncat_remote_port) return 0; 507 508 const int family = ncat && strchr(ncat_local_addr,':') ? AF_INET6 : AF_INET; 509 unsigned short port; 510 511 port = (unsigned short)strtol(ncat_local_port, NULL, 10); 512 if (1 != sock_addr_inet_pton(&cnt_addr, ncat_local_addr, family, port)) { 513 log_error(srv->errh, __FILE__, __LINE__, "invalid local addr"); 514 return 0; 515 } 516 517 srv_socket = server_oneshot_getsock(srv, &cnt_addr); 518 if (NULL == srv_socket) return 0; 519 520 port = (unsigned short)strtol(ncat_remote_port, NULL, 10); 521 if (1 != sock_addr_inet_pton(&cnt_addr, ncat_remote_addr, family, port)) { 522 log_error(srv->errh, __FILE__, __LINE__, "invalid remote addr"); 523 return 0; 524 } 525 526 /*(must set flags; fd did not pass through fdevent accept() logic)*/ 527 if (-1 == fdevent_fcntl_set_nb_cloexec(fdin)) { 528 log_perror(srv->errh, __FILE__, __LINE__, "fcntl()"); 529 return 0; 530 } 531 if (-1 == fdevent_fcntl_set_nb_cloexec(fdout)) { 532 log_perror(srv->errh, __FILE__, __LINE__, "fcntl()"); 533 return 0; 534 } 535 536 con = connection_accepted(srv, srv_socket, &cnt_addr, fdout); 537 if (NULL == con) return 0; 538 539 /* note: existing routines assume socket, not pipe 540 * connections.c:connection_read_cq() 541 * uses recv() ifdef __WIN32 542 * passes S_IFSOCK to fdevent_ioctl_fionread() 543 * (The routine could be copied and modified, if required) 544 * This is unlikely to work if TLS is used over pipe since the SSL_CTX 545 * is associated with the other end of the pipe. However, if using 546 * pipes, using TLS is unexpected behavior. 547 */ 548 549 /*assert(oneshot_fd == fdin);*/ 550 oneshot_read_cq = con->network_read; 551 con->network_read = server_oneshot_read_cq; 552 oneshot_fdn = 553 fdevent_register(srv->ev, fdin, server_oneshot_handle_fdevent, con); 554 fdevent_fdnode_event_set(srv->ev, oneshot_fdn, FDEVENT_RDHUP); 555 556 connection_state_machine(con); 557 return 1; 558 } 559 560 561 __attribute_cold__ 562 static int server_oneshot_init(server *srv, int fd) { 563 connection *con; 564 const server_socket *srv_socket; 565 sock_addr cnt_addr; 566 socklen_t cnt_len; 567 568 cnt_len = sizeof(cnt_addr); 569 if (0 != getsockname(fd, (struct sockaddr *)&cnt_addr, &cnt_len)) { 570 log_perror(srv->errh, __FILE__, __LINE__, "getsockname()"); 571 return 0; 572 } 573 574 srv_socket = server_oneshot_getsock(srv, &cnt_addr); 575 if (NULL == srv_socket) return 0; 576 577 #ifdef __clang_analyzer__ 578 memset(&cnt_addr, 0, sizeof(cnt_addr)); 579 #endif 580 cnt_len = sizeof(cnt_addr); 581 if (0 != getpeername(fd, (struct sockaddr *)&cnt_addr, &cnt_len)) { 582 log_perror(srv->errh, __FILE__, __LINE__, "getpeername()"); 583 return 0; 584 } 585 586 /*(must set flags; fd did not pass through fdevent accept() logic)*/ 587 if (-1 == fdevent_fcntl_set_nb_cloexec(fd)) { 588 log_perror(srv->errh, __FILE__, __LINE__, "fcntl()"); 589 return 0; 590 } 591 592 if (sock_addr_get_family(&cnt_addr) != AF_UNIX) { 593 network_accept_tcp_nagle_disable(fd); 594 } 595 596 con = connection_accepted(srv, srv_socket, &cnt_addr, fd); 597 if (NULL == con) return 0; 598 599 connection_state_machine(con); 600 return 1; 601 } 602 603 604 __attribute_cold__ 605 static void show_version (void) { 606 char *b = PACKAGE_DESC TEXT_SSL \ 607 " - a light and fast webserver\n" 608 #ifdef NONREPRODUCIBLE_BUILD 609 "Build-Date: " __DATE__ " " __TIME__ "\n"; 610 #endif 611 ; 612 write_all(STDOUT_FILENO, b, strlen(b)); 613 } 614 615 __attribute_cold__ 616 static void show_features (void) { 617 static const char features[] = 618 "\nFeatures:\n\n" 619 #ifdef HAVE_IPV6 620 "\t+ IPv6 support\n" 621 #else 622 "\t- IPv6 support\n" 623 #endif 624 #if defined HAVE_ZLIB_H && defined HAVE_LIBZ 625 "\t+ zlib support\n" 626 #else 627 "\t- zlib support\n" 628 #endif 629 #if defined HAVE_ZSTD_H && defined HAVE_ZSTD 630 "\t+ zstd support\n" 631 #else 632 "\t- zstd support\n" 633 #endif 634 #if defined HAVE_BZLIB_H && defined HAVE_LIBBZ2 635 "\t+ bzip2 support\n" 636 #else 637 "\t- bzip2 support\n" 638 #endif 639 #if defined HAVE_BROTLI_ENCODE_H && defined HAVE_BROTLI 640 "\t+ brotli support\n" 641 #else 642 "\t- brotli support\n" 643 #endif 644 #if defined(HAVE_CRYPT) || defined(HAVE_CRYPT_R) 645 "\t+ crypt support\n" 646 #else 647 "\t- crypt support\n" 648 #endif 649 #ifdef USE_OPENSSL_CRYPTO 650 "\t+ OpenSSL support\n" 651 #else 652 "\t- OpenSSL support\n" 653 #endif 654 #ifdef USE_MBEDTLS_CRYPTO 655 "\t+ mbedTLS support\n" 656 #else 657 "\t- mbedTLS support\n" 658 #endif 659 #ifdef USE_NSS_CRYPTO 660 "\t+ NSS crypto support\n" 661 #else 662 "\t- NSS crypto support\n" 663 #endif 664 #ifdef USE_GNUTLS_CRYPTO 665 "\t+ GnuTLS support\n" 666 #else 667 "\t- GnuTLS support\n" 668 #endif 669 #ifdef USE_WOLFSSL_CRYPTO 670 "\t+ WolfSSL support\n" 671 #else 672 "\t- WolfSSL support\n" 673 #endif 674 #ifdef USE_NETTLE_CRYPTO 675 "\t+ Nettle support\n" 676 #else 677 "\t- Nettle support\n" 678 #endif 679 #ifdef HAVE_PCRE 680 "\t+ PCRE support\n" 681 #else 682 "\t- PCRE support\n" 683 #endif 684 #ifdef HAVE_MYSQL 685 "\t+ MySQL support\n" 686 #else 687 "\t- MySQL support\n" 688 #endif 689 #ifdef HAVE_PGSQL 690 "\t+ PgSQL support\n" 691 #else 692 "\t- PgSQL support\n" 693 #endif 694 #ifdef HAVE_DBI 695 "\t+ DBI support\n" 696 #else 697 "\t- DBI support\n" 698 #endif 699 #ifdef HAVE_KRB5 700 "\t+ Kerberos support\n" 701 #else 702 "\t- Kerberos support\n" 703 #endif 704 #if defined(HAVE_LDAP_H) && defined(HAVE_LBER_H) && defined(HAVE_LIBLDAP) && defined(HAVE_LIBLBER) 705 "\t+ LDAP support\n" 706 #else 707 "\t- LDAP support\n" 708 #endif 709 #ifdef HAVE_PAM 710 "\t+ PAM support\n" 711 #else 712 "\t- PAM support\n" 713 #endif 714 #ifdef HAVE_FAM_H 715 "\t+ FAM support\n" 716 #else 717 "\t- FAM support\n" 718 #endif 719 #ifdef HAVE_LUA_H 720 "\t+ LUA support\n" 721 #else 722 "\t- LUA support\n" 723 #endif 724 #ifdef HAVE_LIBXML_H 725 "\t+ xml support\n" 726 #else 727 "\t- xml support\n" 728 #endif 729 #ifdef HAVE_SQLITE3_H 730 "\t+ SQLite support\n" 731 #else 732 "\t- SQLite support\n" 733 #endif 734 ; 735 show_version(); 736 printf("%s%s%s%s\n", 737 fdevent_show_event_handlers(), 738 network_write_show_handlers(), 739 features, 740 sizeof(time_t) > 4 || (sizeof(time_t) == 4 && (time_t)-1 > (time_t)1) 741 ? "\t+ Y2038 support\n" 742 : "\t- Y2038 support (unsafe 32-bit signed time_t)\n"); 743 } 744 745 __attribute_cold__ 746 static void show_help (void) { 747 char *b = PACKAGE_DESC TEXT_SSL 748 #ifdef NONREPRODUCIBLE_BUILD 749 " ("__DATE__ " " __TIME__ ")" 750 #endif 751 " - a light and fast webserver\n" \ 752 "usage:\n" \ 753 " -f <name> filename of the config-file\n" \ 754 " -m <name> module directory (default: "LIBRARY_DIR")\n" \ 755 " -i <secs> graceful shutdown after <secs> of inactivity\n" \ 756 " -1 process single (one) request on stdin socket, then exit\n" \ 757 " -p print the parsed config-file in internal form, and exit\n" \ 758 " -t test config-file syntax, then exit\n" \ 759 " -tt test config-file syntax, load and init modules, then exit\n" \ 760 " -D don't go to background (default: go to background)\n" \ 761 " -v show version\n" \ 762 " -V show compile-time features\n" \ 763 " -h show this help\n" \ 764 "\n" 765 ; 766 write_all(STDOUT_FILENO, b, strlen(b)); 767 } 768 769 __attribute_cold__ 770 __attribute_noinline__ 771 static void server_sockets_save (server *srv) { /* graceful_restart */ 772 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) 773 srv->srv_sockets.ptr[i]->srv = NULL; /* srv will shortly be invalid */ 774 for (uint32_t i = 0; i < srv->srv_sockets_inherited.used; ++i) 775 srv->srv_sockets_inherited.ptr[i]->srv = NULL; /* srv to be invalid */ 776 memcpy(&graceful_sockets, &srv->srv_sockets, sizeof(server_socket_array)); 777 memset(&srv->srv_sockets, 0, sizeof(server_socket_array)); 778 memcpy(&inherited_sockets, &srv->srv_sockets_inherited, sizeof(server_socket_array)); 779 memset(&srv->srv_sockets_inherited, 0, sizeof(server_socket_array)); 780 } 781 782 __attribute_cold__ 783 __attribute_noinline__ 784 static void server_sockets_restore (server *srv) { /* graceful_restart */ 785 memcpy(&srv->srv_sockets, &graceful_sockets, sizeof(server_socket_array)); 786 memset(&graceful_sockets, 0, sizeof(server_socket_array)); 787 memcpy(&srv->srv_sockets_inherited, &inherited_sockets, sizeof(server_socket_array)); 788 memset(&inherited_sockets, 0, sizeof(server_socket_array)); 789 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) 790 srv->srv_sockets.ptr[i]->srv = srv; /* update ptr */ 791 for (uint32_t i = 0; i < srv->srv_sockets_inherited.used; ++i) 792 srv->srv_sockets_inherited.ptr[i]->srv = srv; /* update ptr */ 793 } 794 795 __attribute_cold__ 796 static int server_sockets_set_nb_cloexec (server *srv) { 797 if (srv->sockets_disabled) return 0; /* lighttpd -1 (one-shot mode) */ 798 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) { 799 server_socket *srv_socket = srv->srv_sockets.ptr[i]; 800 if (-1 == fdevent_fcntl_set_nb_cloexec_sock(srv_socket->fd)) { 801 log_perror(srv->errh, __FILE__, __LINE__, "fcntl()"); 802 return -1; 803 } 804 } 805 return 0; 806 } 807 808 __attribute_cold__ 809 static void server_sockets_set_event (server *srv, int event) { 810 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) { 811 server_socket *srv_socket = srv->srv_sockets.ptr[i]; 812 fdevent_fdnode_event_set(srv->ev, srv_socket->fdn, event); 813 } 814 } 815 816 __attribute_cold__ 817 static void server_sockets_unregister (server *srv) { 818 if (2 == srv->sockets_disabled) return; 819 srv->sockets_disabled = 2; 820 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) 821 network_unregister_sock(srv, srv->srv_sockets.ptr[i]); 822 } 823 824 __attribute_cold__ 825 static void server_sockets_close (server *srv) { 826 /* closing socket right away will make it possible for the next lighttpd 827 * to take over (old-style graceful restart), but only if backends 828 * (e.g. fastcgi, scgi, etc) are independent from lighttpd, rather 829 * than started by lighttpd via "bin-path") 830 */ 831 if (3 == srv->sockets_disabled) return; 832 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) { 833 server_socket *srv_socket = srv->srv_sockets.ptr[i]; 834 if (-1 == srv_socket->fd) continue; 835 if (2 != srv->sockets_disabled) network_unregister_sock(srv,srv_socket); 836 close(srv_socket->fd); 837 srv_socket->fd = -1; 838 /* network_close() will cleanup after us */ 839 } 840 srv->sockets_disabled = 3; 841 } 842 843 __attribute_cold__ 844 static void server_graceful_signal_prev_generation (void) 845 { 846 const char * const prev_gen = getenv("LIGHTTPD_PREV_GEN"); 847 if (NULL == prev_gen) return; 848 pid_t pid = (pid_t)strtol(prev_gen, NULL, 10); 849 unsetenv("LIGHTTPD_PREV_GEN"); 850 if (pid <= 0) return; /*(should not happen)*/ 851 if (pid == fdevent_waitpid(pid,NULL,1)) return; /*(pid exited; unexpected)*/ 852 kill(pid, SIGINT); /* signal previous generation for graceful shutdown */ 853 } 854 855 __attribute_cold__ 856 static int server_graceful_state_bg (server *srv) { 857 /*assert(graceful_restart);*/ 858 /*(SIGUSR1 set to SIG_IGN in workers, so should not reach here if worker)*/ 859 if (srv_shutdown) return 0; 860 861 /* check if server should fork and background (bg) itself 862 * to continue processing requests already in progress */ 863 if (!config_feature_bool(srv, "server.graceful-restart-bg", 0)) return 0; 864 865 /*(set flag to false to avoid repeating)*/ 866 data_unset * const du = 867 array_get_data_unset(srv->srvconf.feature_flags, 868 CONST_STR_LEN("server.graceful-restart-bg")); 869 if (du->type == TYPE_STRING) 870 buffer_copy_string_len(&((data_string *)du)->value, 871 CONST_STR_LEN("false")); 872 else /* (du->type == TYPE_INTEGER) */ 873 ((data_integer *)du)->value = 0; 874 875 /* require exec'd via absolute path or daemon in foreground 876 * and exec'd with path containing '/' (e.g. "./xxxxx") */ 877 char ** const argv = srv->argv; 878 if (0 == srv->srvconf.dont_daemonize 879 ? argv[0][0] != '/' 880 : NULL == strchr(argv[0], '/')) return 0; 881 882 #if 0 883 /* disabled; not fully implemented 884 * srv->srvconf.systemd_socket_activation might be cleared in network_init() 885 * leading to issuing a false warning 886 */ 887 /* warn if server.systemd-socket-activation not enabled 888 * (While this warns on existing config rather than new config, 889 * it is probably a decent predictor for presence in new config) */ 890 if (!srv->srvconf.systemd_socket_activation) 891 log_error(srv->errh, __FILE__, __LINE__, 892 "[note] server.systemd-socket-activation not enabled; " 893 "listen sockets will be closed and reopened"); 894 #endif 895 896 /* flush log buffers to avoid potential duplication of entries 897 * server_handle_sighup(srv) does the following, but skip logging */ 898 plugins_call_handle_sighup(srv); 899 fdlog_files_cycle(srv->errh); /* reopen log files, not pipes */ 900 901 /* backgrounding to continue processing requests in progress */ 902 /* re-exec lighttpd in original process 903 * Note: using path in re-exec is portable and allows lighttpd upgrade. 904 * OTOH, getauxval() AT_EXECFD and fexecve() could be used on Linux to 905 * re-exec without access to original executable on disk, which might be 906 * desirable in some situations, but is not implemented here. 907 * Alternatively, if argv[] was not available, could use readlink() on 908 * /proc/self/exe (Linux-specific), though there are ways on many other 909 * platforms to achieve the same: 910 * https://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe 911 */ 912 #if defined(HAVE_KQUEUE) 913 #if defined(__FreeBSD__) || defined(__DragonFly__) 914 /*(must *exclude* rfork RFFDG flag for kqueue to work across rfork)*/ 915 pid_t pid = rfork(RFPROC); 916 #else 917 pid_t pid = -1; 918 if (pid < 0) { 919 /* kqueue is not inherited across fork 920 * future: fdevent kqueue and stat_cache kqueue would need to be closed, 921 * re-opened, and active fds re-registered. Not current done. 922 * Need to create some routines like fdevent_reinit_after_fork*/ 923 log_error(srv->errh, __FILE__, __LINE__, 924 "server.graceful-restart-bg ignored on OpenBSD and NetBSD " 925 "due to limitation in kqueue inheritance and lacking rfork"); 926 return 0; 927 } 928 #endif 929 #else 930 pid_t pid = fork(); 931 #endif 932 if (pid) { /* original process */ 933 if (pid < 0) return 0; 934 network_socket_activation_to_env(srv); 935 /* save pid of original server in environment so that it can be 936 * signalled by restarted server once restarted server is ready 937 * to accept new connections */ 938 server_graceful_signal_prev_generation();/*(expect no prev gen active)*/ 939 if (0 == srv->srvconf.max_worker) { 940 buffer * const tb = srv->tmp_buf; 941 buffer_clear(tb); 942 buffer_append_int(tb, pid); 943 setenv("LIGHTTPD_PREV_GEN", tb->ptr, 1); 944 } 945 /*fdevent_waitpid(pid, NULL, 0);*//* detach? */ 946 execv(argv[0], argv); 947 _exit(1); 948 } 949 /* else child/grandchild */ 950 951 /*if (-1 == setsid()) _exit(1);*//* should we detach? */ 952 /* Note: restarted server will fail with socket-in-use error if 953 * server.systemd-socket-activation not enabled in restarted server */ 954 if (0 != srv->srvconf.max_worker) 955 server_sockets_close(srv);/*(close before parent reaps pid in waitpid)*/ 956 /*if (0 != fork()) _exit(0);*//* should we detach? */ 957 /*(grandchild is now backgrounded and detached from original process)*/ 958 959 /* XXX: might extend code to have new server.feature-flags param specify 960 * max lifetime before aborting remaining connections */ 961 962 /* (reached if lighttpd workers or if sole process w/o workers) 963 * use same code as comment elsewhere in server.c: 964 * make sure workers do not muck with pid-file */ 965 if (0 <= pid_fd) { 966 close(pid_fd); 967 pid_fd = -1; 968 } 969 srv->srvconf.pid_file = NULL; 970 971 /* (original process is backgrounded -- even if no active connections -- 972 * to allow graceful shutdown tasks to be run by server and by modules) */ 973 log_error(srv->errh, __FILE__, __LINE__, 974 "[note] pid %lld continuing to handle %u connection(s) in progress", 975 (long long)getpid(), srv->srvconf.max_conns - srv->lim_conns); 976 977 if (0 == srv->srvconf.max_worker) { 978 /* reset graceful_shutdown; wait for signal from restarted server */ 979 srv->graceful_expire_ts = 0; 980 graceful_shutdown = 0; 981 } 982 graceful_restart = 0; 983 return 1; 984 } 985 986 __attribute_cold__ 987 __attribute_noinline__ 988 static void server_graceful_shutdown_maint (server *srv) { 989 if (oneshot_fd) { 990 /* permit keep-alive on one-shot connections until graceful_expire_ts */ 991 if (!srv->graceful_expire_ts) return; 992 if (srv->graceful_expire_ts >= log_monotonic_secs) return; 993 } 994 connection_graceful_shutdown_maint(srv); 995 } 996 997 __attribute_cold__ 998 __attribute_noinline__ 999 static void server_graceful_state (server *srv) { 1000 1001 if (!srv_shutdown) { 1002 if (0 == srv->graceful_expire_ts) { 1003 srv->graceful_expire_ts = 1004 config_feature_int(srv, "server.graceful-shutdown-timeout", 8); 1005 if (srv->graceful_expire_ts) 1006 srv->graceful_expire_ts += log_monotonic_secs; 1007 } 1008 server_graceful_shutdown_maint(srv); 1009 } 1010 1011 if (2 == srv->sockets_disabled || 3 == srv->sockets_disabled) { 1012 if (oneshot_fd) graceful_restart = 0; 1013 return; 1014 } 1015 1016 log_error(srv->errh,__FILE__,__LINE__,"[note] graceful shutdown started"); 1017 1018 /* no graceful restart if chroot()ed, if oneshot mode, or if idle timeout */ 1019 if (srv->srvconf.changeroot || oneshot_fd || 2 == graceful_shutdown) 1020 graceful_restart = 0; 1021 1022 if (graceful_restart) { 1023 if (!server_graceful_state_bg(srv)) 1024 server_sockets_unregister(srv); 1025 if (pid_fd > 0) pid_fd = -pid_fd; /*(flag to skip removing pid file)*/ 1026 } 1027 else { 1028 server_sockets_close(srv); 1029 remove_pid_file(srv); 1030 /*(prevent more removal attempts)*/ 1031 srv->srvconf.pid_file = NULL; 1032 } 1033 } 1034 1035 __attribute_cold__ 1036 __attribute_noinline__ 1037 static void server_sockets_enable (server *srv) { 1038 server_sockets_set_event(srv, FDEVENT_IN); 1039 srv->sockets_disabled = 0; 1040 log_error(srv->errh, __FILE__, __LINE__, "[note] sockets enabled again"); 1041 } 1042 1043 __attribute_cold__ 1044 __attribute_noinline__ 1045 static void server_sockets_disable (server *srv) { 1046 server_sockets_set_event(srv, 0); 1047 srv->sockets_disabled = 1; 1048 log_error(srv->errh, __FILE__, __LINE__, 1049 (0 == srv->lim_conns) 1050 ? "[note] sockets disabled, connection limit reached" 1051 : "[note] sockets disabled, out-of-fds"); 1052 } 1053 1054 __attribute_cold__ 1055 static void server_overload_check (server *srv) { 1056 if (srv->cur_fds < srv->max_fds_lowat && 0 != srv->lim_conns) 1057 server_sockets_enable(srv); 1058 } 1059 1060 static void server_load_check (server *srv) { 1061 /* check if hit limits for num fds used or num connections */ 1062 if (srv->cur_fds > srv->max_fds_hiwat || 0 == srv->lim_conns) 1063 server_sockets_disable(srv); 1064 } 1065 1066 __attribute_cold__ 1067 __attribute_noinline__ 1068 static int server_main_setup (server * const srv, int argc, char **argv) { 1069 int print_config = 0; 1070 int test_config = 0; 1071 int i_am_root = 0; 1072 int o; 1073 #ifdef HAVE_FORK 1074 int num_childs = 0; 1075 #endif 1076 uint32_t i; 1077 #ifdef HAVE_SIGACTION 1078 struct sigaction act; 1079 #endif 1080 1081 #ifdef HAVE_FORK 1082 int parent_pipe_fd = -1; 1083 #endif 1084 1085 #ifdef HAVE_GETUID 1086 i_am_root = (0 == getuid()); 1087 #endif 1088 1089 /* initialize globals (including file-scoped static globals) */ 1090 oneshot_fd = 0; 1091 oneshot_fdout = -1; 1092 srv_shutdown = 0; 1093 graceful_shutdown = 0; 1094 handle_sig_alarm = 1; 1095 handle_sig_hup = 0; 1096 idle_limit = 0; 1097 chunkqueue_set_tempdirs_default_reset(); 1098 /*graceful_restart = 0;*//*(reset below to avoid further daemonizing)*/ 1099 /*(intentionally preserved)*/ 1100 /*memset(graceful_sockets, 0, sizeof(graceful_sockets));*/ 1101 /*memset(inherited_sockets, 0, sizeof(inherited_sockets));*/ 1102 /*pid_fd = -1;*/ 1103 srv->argv = argv; 1104 1105 while(-1 != (o = getopt(argc, argv, "f:m:i:hvVD1pt"))) { 1106 switch(o) { 1107 case 'f': 1108 if (srv->config_data_base) { 1109 log_error(srv->errh, __FILE__, __LINE__, 1110 "Can only read one config file. Use the include command to use multiple config files."); 1111 return -1; 1112 } 1113 if (config_read(srv, optarg)) { 1114 return -1; 1115 } 1116 break; 1117 case 'm': 1118 srv->srvconf.modules_dir = optarg; 1119 break; 1120 case 'i': { 1121 char *endptr; 1122 long timeout = strtol(optarg, &endptr, 0); 1123 if (!*optarg || *endptr || timeout < 0) { 1124 log_error(srv->errh, __FILE__, __LINE__, 1125 "Invalid idle timeout value: %s", optarg); 1126 return -1; 1127 } 1128 idle_limit = (int)timeout; 1129 break; 1130 } 1131 case 'p': print_config = 1; break; 1132 case 't': ++test_config; break; 1133 case '1': if (0 == oneshot_fd) oneshot_fd = dup(STDIN_FILENO); 1134 break; 1135 case 'D': srv->srvconf.dont_daemonize = 1; break; 1136 case 'v': show_version(); return 0; 1137 case 'V': show_features(); return 0; 1138 case 'h': show_help(); return 0; 1139 default: 1140 show_help(); 1141 return -1; 1142 } 1143 } 1144 1145 #ifdef __CYGWIN__ 1146 if (!srv->config_data_base && NULL != getenv("NSSM_SERVICE_NAME")) { 1147 char *dir = getenv("NSSM_SERVICE_DIR"); 1148 if (NULL != dir && 0 != chdir(dir)) { 1149 log_perror(srv->errh, __FILE__, __LINE__, "chdir %s failed", dir); 1150 return -1; 1151 } 1152 srv->srvconf.dont_daemonize = 1; 1153 srv->srvconf.modules_dir = "modules"; 1154 if (config_read(srv, "conf/lighttpd.conf")) return -1; 1155 } 1156 #endif 1157 1158 if (!srv->config_data_base) { 1159 log_error(srv->errh, __FILE__, __LINE__, 1160 "No configuration available. Try using -f option."); 1161 return -1; 1162 } 1163 1164 if (print_config) { 1165 config_print(srv); 1166 puts(srv->tmp_buf->ptr); 1167 } 1168 1169 if (test_config) { 1170 srv->srvconf.pid_file = NULL; 1171 if (1 == test_config) { 1172 printf("Syntax OK\n"); 1173 } else { /*(test_config > 1)*/ 1174 test_config = 0; 1175 srv->srvconf.preflight_check = 1; 1176 srv->srvconf.dont_daemonize = 1; 1177 } 1178 } 1179 1180 if (test_config || print_config) { 1181 return 0; 1182 } 1183 1184 if (oneshot_fd) { 1185 if (oneshot_fd <= STDERR_FILENO) { 1186 log_error(srv->errh, __FILE__, __LINE__, 1187 "Invalid fds at startup with lighttpd -1"); 1188 return -1; 1189 } 1190 graceful_shutdown = 1; 1191 srv->sockets_disabled = 2; 1192 srv->srvconf.dont_daemonize = 1; 1193 srv->srvconf.pid_file = NULL; 1194 if (srv->srvconf.max_worker) { 1195 srv->srvconf.max_worker = 0; 1196 log_error(srv->errh, __FILE__, __LINE__, 1197 "server one-shot command line option disables server.max-worker config file option."); 1198 } 1199 1200 struct stat st; 1201 if (0 != fstat(oneshot_fd, &st)) { 1202 log_perror(srv->errh, __FILE__, __LINE__, "fstat()"); 1203 return -1; 1204 } 1205 1206 if (S_ISFIFO(st.st_mode)) { 1207 oneshot_fdout = dup(STDOUT_FILENO); 1208 if (oneshot_fdout <= STDERR_FILENO) { 1209 log_perror(srv->errh, __FILE__, __LINE__, "dup()"); 1210 return -1; 1211 } 1212 } 1213 else if (!S_ISSOCK(st.st_mode)) { 1214 /* require that fd is a socket 1215 * (modules might expect STDIN_FILENO and STDOUT_FILENO opened to /dev/null) */ 1216 log_error(srv->errh, __FILE__, __LINE__, 1217 "lighttpd -1 stdin is not a socket"); 1218 return -1; 1219 } 1220 } 1221 1222 if (srv->srvconf.bindhost && buffer_is_equal_string(srv->srvconf.bindhost, CONST_STR_LEN("/dev/stdin"))) { 1223 if (-1 == srv->stdin_fd) 1224 srv->stdin_fd = dup(STDIN_FILENO); 1225 if (srv->stdin_fd <= STDERR_FILENO) { 1226 log_error(srv->errh, __FILE__, __LINE__, 1227 "Invalid fds at startup"); 1228 return -1; 1229 } 1230 } 1231 1232 /* close stdin and stdout, as they are not needed */ 1233 { 1234 struct stat st; 1235 int devnull; 1236 int errfd; 1237 do { 1238 /* coverity[overwrite_var : FALSE] */ 1239 devnull = fdevent_open_devnull(); 1240 #ifdef __COVERITY__ 1241 __coverity_escape__(devnull); 1242 #endif 1243 } while (-1 != devnull && devnull <= STDERR_FILENO); 1244 if (-1 == devnull) { 1245 log_perror(srv->errh, __FILE__, __LINE__, 1246 "opening /dev/null failed"); 1247 return -1; 1248 } 1249 errfd = (0 == fstat(STDERR_FILENO, &st)) ? -1 : devnull; 1250 if (0 != fdevent_set_stdin_stdout_stderr(devnull, devnull, errfd)) { 1251 log_perror(srv->errh, __FILE__, __LINE__, 1252 "setting default fds failed"); 1253 #ifdef FD_CLOEXEC 1254 if (-1 != errfd) close(errfd); 1255 if (devnull != errfd) close(devnull); 1256 #endif 1257 return -1; 1258 } 1259 #ifdef FD_CLOEXEC 1260 if (-1 != errfd) close(errfd); 1261 if (devnull != errfd) close(devnull); 1262 #endif 1263 } 1264 1265 http_response_send_1xx_cb_set(NULL, HTTP_VERSION_2); 1266 if (!config_feature_bool(srv, "server.h2-discard-backend-1xx", 0)) 1267 http_response_send_1xx_cb_set(h2_send_1xx, HTTP_VERSION_2); 1268 1269 http_response_send_1xx_cb_set(NULL, HTTP_VERSION_1_1); 1270 if (!config_feature_bool(srv, "server.h1-discard-backend-1xx", 0)) 1271 http_response_send_1xx_cb_set(connection_send_1xx, HTTP_VERSION_1_1); 1272 1273 http_range_config_allow_http10(config_feature_bool(srv, "http10.range", 0)); 1274 1275 if (0 != config_set_defaults(srv)) { 1276 log_error(srv->errh, __FILE__, __LINE__, 1277 "setting default values failed"); 1278 return -1; 1279 } 1280 1281 if (plugins_load(srv)) { 1282 log_error(srv->errh, __FILE__, __LINE__, 1283 "loading plugins finally failed"); 1284 return -1; 1285 } 1286 1287 if (HANDLER_GO_ON != plugins_call_init(srv)) { 1288 log_error(srv->errh, __FILE__, __LINE__, 1289 "Initialization of plugins failed. Going down."); 1290 return -1; 1291 } 1292 1293 /* mod_indexfile should be listed in server.modules prior to dynamic handlers */ 1294 i = 0; 1295 for (const char *pname = NULL; i < srv->plugins.used; ++i) { 1296 plugin *p = ((plugin **)srv->plugins.ptr)[i]; 1297 if (NULL != pname && 0 == strcmp(p->name, "indexfile")) { 1298 log_error(srv->errh, __FILE__, __LINE__, 1299 "Warning: mod_indexfile should be listed in server.modules prior to mod_%s", pname); 1300 break; 1301 } 1302 if (p->handle_subrequest_start && p->handle_subrequest) { 1303 if (!pname) pname = p->name; 1304 } 1305 } 1306 1307 /* open pid file BEFORE chroot */ 1308 if (-2 == pid_fd) pid_fd = -1; /*(initial startup state)*/ 1309 if (-1 == pid_fd && srv->srvconf.pid_file) { 1310 const char *pidfile = srv->srvconf.pid_file->ptr; 1311 if (-1 == (pid_fd = fdevent_open_cloexec(pidfile, 0, O_WRONLY | O_CREAT | O_EXCL | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) { 1312 struct stat st; 1313 if (errno != EEXIST) { 1314 log_perror(srv->errh, __FILE__, __LINE__, 1315 "opening pid-file failed: %s", pidfile); 1316 return -1; 1317 } 1318 1319 if (0 != stat(pidfile, &st)) { 1320 log_perror(srv->errh, __FILE__, __LINE__, 1321 "stating existing pid-file failed: %s", pidfile); 1322 } 1323 1324 if (!S_ISREG(st.st_mode)) { 1325 log_error(srv->errh, __FILE__, __LINE__, 1326 "pid-file exists and isn't regular file: %s", pidfile); 1327 return -1; 1328 } 1329 1330 if (-1 == (pid_fd = fdevent_open_cloexec(pidfile, 0, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) { 1331 log_perror(srv->errh, __FILE__, __LINE__, 1332 "opening pid-file failed: %s", pidfile); 1333 return -1; 1334 } 1335 } 1336 } 1337 1338 { 1339 #ifdef HAVE_GETRLIMIT 1340 struct rlimit rlim = { 4096, 4096 }; 1341 int use_rlimit = 1; 1342 #ifdef HAVE_VALGRIND_VALGRIND_H 1343 if (RUNNING_ON_VALGRIND) use_rlimit = 0; 1344 #endif 1345 1346 if (0 != getrlimit(RLIMIT_NOFILE, &rlim)) { 1347 log_perror(srv->errh, __FILE__, __LINE__, "getrlimit()"); 1348 use_rlimit = 0; 1349 } 1350 1351 /** 1352 * if we are not root can can't increase the fd-limit above rlim_max, but we can reduce it 1353 */ 1354 if (use_rlimit && srv->srvconf.max_fds 1355 && (i_am_root || srv->srvconf.max_fds <= rlim.rlim_max)) { 1356 /* set rlimits */ 1357 1358 rlim_t rlim_cur = rlim.rlim_cur; 1359 rlim.rlim_cur = srv->srvconf.max_fds; 1360 if (i_am_root) rlim.rlim_max = srv->srvconf.max_fds; 1361 1362 if (0 != setrlimit(RLIMIT_NOFILE, &rlim)) { 1363 log_perror(srv->errh, __FILE__, __LINE__, "setrlimit()"); 1364 log_error(srv->errh, __FILE__, __LINE__, "setrlimit() may need root to run once: setsebool -P httpd_setrlimit on"); 1365 use_rlimit = 0; 1366 if (srv->srvconf.max_fds > rlim_cur) 1367 srv->srvconf.max_fds = rlim_cur; 1368 } 1369 } 1370 1371 /*(default upper limit of 4k if server.max-fds not specified)*/ 1372 if (0 == srv->srvconf.max_fds) 1373 srv->srvconf.max_fds = (rlim.rlim_cur <= 4096) 1374 ? (unsigned short)rlim.rlim_cur 1375 : 4096; 1376 1377 /* set core file rlimit, if enable_cores is set */ 1378 if (use_rlimit && srv->srvconf.enable_cores && getrlimit(RLIMIT_CORE, &rlim) == 0) { 1379 rlim.rlim_cur = rlim.rlim_max; 1380 setrlimit(RLIMIT_CORE, &rlim); 1381 } 1382 #endif 1383 } 1384 1385 /* we need root-perms for port < 1024 */ 1386 if (0 != network_init(srv, srv->stdin_fd)) { 1387 return -1; 1388 } 1389 srv->stdin_fd = -1; 1390 1391 if (i_am_root) { 1392 #ifdef HAVE_PWD_H 1393 /* set user and group */ 1394 struct group *grp = NULL; 1395 struct passwd *pwd = NULL; 1396 1397 if (srv->srvconf.groupname) { 1398 if (NULL == (grp = getgrnam(srv->srvconf.groupname->ptr))) { 1399 log_error(srv->errh, __FILE__, __LINE__, 1400 "can't find groupname %s", srv->srvconf.groupname->ptr); 1401 return -1; 1402 } 1403 } 1404 1405 if (srv->srvconf.username) { 1406 if (NULL == (pwd = getpwnam(srv->srvconf.username->ptr))) { 1407 log_error(srv->errh, __FILE__, __LINE__, 1408 "can't find username %s", srv->srvconf.username->ptr); 1409 return -1; 1410 } 1411 1412 if (pwd->pw_uid == 0) { 1413 log_error(srv->errh, __FILE__, __LINE__, 1414 "I will not set uid to 0\n"); 1415 return -1; 1416 } 1417 1418 if (NULL == grp && NULL == (grp = getgrgid(pwd->pw_gid))) { 1419 log_error(srv->errh, __FILE__, __LINE__, 1420 "can't find group id %d", (int)pwd->pw_gid); 1421 return -1; 1422 } 1423 } 1424 1425 if (NULL != grp) { 1426 if (grp->gr_gid == 0) { 1427 log_error(srv->errh, __FILE__, __LINE__, 1428 "I will not set gid to 0\n"); 1429 return -1; 1430 } 1431 } 1432 1433 /* 1434 * Change group before chroot, when we have access 1435 * to /etc/group 1436 * */ 1437 if (NULL != grp) { 1438 if (-1 == setgid(grp->gr_gid)) { 1439 log_perror(srv->errh, __FILE__, __LINE__, "setgid()"); 1440 return -1; 1441 } 1442 if (-1 == setgroups(0, NULL)) { 1443 log_perror(srv->errh, __FILE__, __LINE__, "setgroups()"); 1444 return -1; 1445 } 1446 if (srv->srvconf.username) { 1447 initgroups(srv->srvconf.username->ptr, grp->gr_gid); 1448 } 1449 } 1450 #endif 1451 #ifdef HAVE_CHROOT 1452 if (srv->srvconf.changeroot) { 1453 tzset(); 1454 1455 if (-1 == chroot(srv->srvconf.changeroot->ptr)) { 1456 log_perror(srv->errh, __FILE__, __LINE__, "chroot()"); 1457 return -1; 1458 } 1459 if (-1 == chdir("/")) { 1460 log_perror(srv->errh, __FILE__, __LINE__, "chdir()"); 1461 return -1; 1462 } 1463 } 1464 #endif 1465 #ifdef HAVE_PWD_H 1466 /* drop root privs */ 1467 if (NULL != pwd) { 1468 if (-1 == setuid(pwd->pw_uid)) { 1469 log_perror(srv->errh, __FILE__, __LINE__, "setuid()"); 1470 return -1; 1471 } 1472 } 1473 #endif 1474 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE) 1475 /** 1476 * on IRIX 6.5.30 they have prctl() but no DUMPABLE 1477 */ 1478 if (srv->srvconf.enable_cores) { 1479 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0); 1480 } 1481 #elif defined(HAVE_SYS_PROCCTL_H) && defined(PROC_TRACE_CTL_ENABLE) 1482 /* (DragonFlyBSD has procctl(), but not PROC_TRACE_CTL_ENABLE) */ 1483 if (srv->srvconf.enable_cores) { 1484 int dumpable = PROC_TRACE_CTL_ENABLE; 1485 procctl(P_PID, 0, PROC_TRACE_CTL, &dumpable); 1486 } 1487 #elif defined(HAVE_SETPFLAGS) && defined(__PROC_PROTECT) 1488 /** 1489 * setpflags seems uniquely a solaris/illumos feature 1490 * but just taking extra precautions clearing __PROC_PROTECT option 1491 */ 1492 if (srv->srvconf.enable_cores) { 1493 setpflags(__PROC_PROTECT, 0); 1494 } 1495 #endif 1496 } 1497 1498 #ifdef HAVE_FORK 1499 /* network is up, let's daemonize ourself */ 1500 if (0 == srv->srvconf.dont_daemonize && 0 == graceful_restart) { 1501 parent_pipe_fd = daemonize(); 1502 } 1503 #endif 1504 graceful_restart = 0;/*(reset here after avoiding further daemonizing)*/ 1505 if (0 == oneshot_fd) graceful_shutdown = 0; 1506 1507 1508 #ifdef HAVE_SIGACTION 1509 memset(&act, 0, sizeof(act)); 1510 sigemptyset(&act.sa_mask); 1511 1512 act.sa_handler = SIG_IGN; 1513 sigaction(SIGPIPE, &act, NULL); 1514 1515 #ifndef _MSC_VER 1516 act.sa_flags = SA_NODEFER; 1517 act.sa_handler = sys_setjmp_sigbus; 1518 sigaction(SIGBUS, &act, NULL); 1519 act.sa_flags = 0; 1520 #endif 1521 1522 # if defined(SA_SIGINFO) 1523 last_sighup_info.si_uid = 0, 1524 last_sighup_info.si_pid = 0; 1525 last_sigterm_info.si_uid = 0, 1526 last_sigterm_info.si_pid = 0; 1527 act.sa_sigaction = sigaction_handler; 1528 act.sa_flags = SA_SIGINFO; 1529 # else 1530 act.sa_handler = signal_handler; 1531 act.sa_flags = 0; 1532 # endif 1533 sigaction(SIGINT, &act, NULL); 1534 sigaction(SIGTERM, &act, NULL); 1535 sigaction(SIGHUP, &act, NULL); 1536 sigaction(SIGALRM, &act, NULL); 1537 sigaction(SIGUSR1, &act, NULL); 1538 1539 /* it should be safe to restart syscalls after SIGCHLD */ 1540 act.sa_flags |= SA_RESTART | SA_NOCLDSTOP; 1541 sigaction(SIGCHLD, &act, NULL); 1542 #elif defined(HAVE_SIGNAL) 1543 /* ignore the SIGPIPE from sendfile() */ 1544 signal(SIGPIPE, SIG_IGN); 1545 signal(SIGALRM, signal_handler); 1546 signal(SIGTERM, signal_handler); 1547 signal(SIGHUP, signal_handler); 1548 signal(SIGCHLD, signal_handler); 1549 signal(SIGINT, signal_handler); 1550 signal(SIGUSR1, signal_handler); 1551 #ifndef _MSC_VER 1552 signal(SIGBUS, sys_setjmp_sigbus); 1553 #endif 1554 #endif 1555 1556 1557 srv->gid = getgid(); 1558 srv->uid = getuid(); 1559 srv->pid = getpid(); 1560 1561 /* write pid file */ 1562 if (pid_fd > 2) { 1563 buffer * const tb = srv->tmp_buf; 1564 buffer_clear(tb); 1565 buffer_append_int(tb, srv->pid); 1566 buffer_append_string_len(tb, CONST_STR_LEN("\n")); 1567 if (-1 == write_all(pid_fd, BUF_PTR_LEN(tb))) { 1568 log_perror(srv->errh, __FILE__, __LINE__, "Couldn't write pid file"); 1569 close(pid_fd); 1570 pid_fd = -1; 1571 return -1; 1572 } 1573 } else if (pid_fd < -2) { 1574 pid_fd = -pid_fd; 1575 } 1576 1577 /* Close stderr ASAP in the child process to make sure that nothing 1578 * is being written to that fd which may not be valid anymore. */ 1579 if (!srv->srvconf.preflight_check) { 1580 if (-1 == config_log_error_open(srv)) { 1581 log_error(srv->errh, __FILE__, __LINE__, "Opening errorlog failed. Going down."); 1582 return -1; 1583 } 1584 if (!oneshot_fd) 1585 log_error(srv->errh, __FILE__, __LINE__, "server started (" PACKAGE_DESC ")"); 1586 } 1587 1588 if (HANDLER_GO_ON != plugins_call_set_defaults(srv)) { 1589 log_error(srv->errh, __FILE__, __LINE__, "Configuration of plugins failed. Going down."); 1590 return -1; 1591 } 1592 1593 if (!config_finalize(srv, &default_server_tag)) { 1594 return -1; 1595 } 1596 1597 if (srv->srvconf.preflight_check) { 1598 /*printf("Preflight OK");*//*(stdout reopened to /dev/null)*/ 1599 return 0; 1600 } 1601 1602 1603 #ifdef HAVE_FORK 1604 /** 1605 * notify daemonize-grandparent of successful startup 1606 * do this before any further forking is done (workers) 1607 */ 1608 if (0 == srv->srvconf.dont_daemonize && -1 != parent_pipe_fd) { 1609 if (0 > write(parent_pipe_fd, "", 1)) return -1; 1610 close(parent_pipe_fd); 1611 } 1612 1613 if (idle_limit && srv->srvconf.max_worker) { 1614 srv->srvconf.max_worker = 0; 1615 log_error(srv->errh, __FILE__, __LINE__, 1616 "server idle time limit command line option disables server.max-worker config file option."); 1617 } 1618 1619 /* start watcher and workers */ 1620 num_childs = srv->srvconf.max_worker; 1621 if (num_childs > 0) { 1622 pid_t pids[num_childs]; 1623 pid_t pid; 1624 const int npids = num_childs; 1625 int child = 0; 1626 unsigned int timer = 0; 1627 for (int n = 0; n < npids; ++n) pids[n] = -1; 1628 server_graceful_signal_prev_generation(); 1629 while (!child && !srv_shutdown && !graceful_shutdown) { 1630 if (num_childs > 0) { 1631 switch ((pid = fork())) { 1632 case -1: 1633 return -1; 1634 case 0: 1635 child = 1; 1636 alarm(0); 1637 break; 1638 default: 1639 num_childs--; 1640 for (int n = 0; n < npids; ++n) { 1641 if (-1 == pids[n]) { 1642 pids[n] = pid; 1643 break; 1644 } 1645 } 1646 break; 1647 } 1648 } else { 1649 int status; 1650 unix_time64_t mono_ts; 1651 1652 if (-1 != (pid = fdevent_waitpid_intr(-1, &status))) { 1653 mono_ts = log_monotonic_secs; 1654 log_monotonic_secs = server_monotonic_secs(); 1655 log_epoch_secs = server_epoch_secs(srv, log_monotonic_secs - mono_ts); 1656 if (plugins_call_handle_waitpid(srv, pid, status) != HANDLER_GO_ON) { 1657 if (!timer) alarm((timer = 5)); 1658 continue; 1659 } 1660 switch (fdlog_pipes_waitpid_cb(pid)) { 1661 default: break; 1662 case -1: if (!timer) alarm((timer = 5)); 1663 __attribute_fallthrough__ 1664 case 1: continue; 1665 } 1666 /** 1667 * check if one of our workers went away 1668 */ 1669 for (int n = 0; n < npids; ++n) { 1670 if (pid == pids[n]) { 1671 pids[n] = -1; 1672 num_childs++; 1673 break; 1674 } 1675 } 1676 } else { 1677 switch (errno) { 1678 case EINTR: 1679 mono_ts = log_monotonic_secs; 1680 log_monotonic_secs = server_monotonic_secs(); 1681 log_epoch_secs = server_epoch_secs(srv, log_monotonic_secs - mono_ts); 1682 /** 1683 * if we receive a SIGHUP we have to close our logs ourself as we don't 1684 * have the mainloop who can help us here 1685 */ 1686 if (handle_sig_hup) { 1687 handle_sig_hup = 0; 1688 fdlog_files_cycle(srv->errh); /* reopen log files, not pipes */ 1689 1690 /* forward SIGHUP to workers */ 1691 for (int n = 0; n < npids; ++n) { 1692 if (pids[n] > 0) kill(pids[n], SIGHUP); 1693 } 1694 } 1695 if (handle_sig_alarm) { 1696 handle_sig_alarm = 0; 1697 timer = 0; 1698 plugins_call_handle_trigger(srv); 1699 fdlog_pipes_restart(log_monotonic_secs); 1700 } 1701 break; 1702 default: 1703 break; 1704 } 1705 } 1706 } 1707 } 1708 1709 /** 1710 * for the parent this is the exit-point 1711 */ 1712 if (!child) { 1713 /** 1714 * kill all children too 1715 */ 1716 if (graceful_shutdown || graceful_restart) { 1717 /* flag to ignore one SIGINT if graceful_restart */ 1718 if (graceful_restart) graceful_restart = 2; 1719 kill(0, SIGINT); 1720 server_graceful_state(srv); 1721 } else if (srv_shutdown) { 1722 kill(0, SIGTERM); 1723 } 1724 1725 return 0; 1726 } 1727 1728 /* ignore SIGUSR1 in workers; only parent directs graceful restart */ 1729 #ifdef HAVE_SIGACTION 1730 { 1731 struct sigaction actignore; 1732 memset(&actignore, 0, sizeof(actignore)); 1733 actignore.sa_handler = SIG_IGN; 1734 sigaction(SIGUSR1, &actignore, NULL); 1735 } 1736 #elif defined(HAVE_SIGNAL) 1737 signal(SIGUSR1, SIG_IGN); 1738 #endif 1739 1740 /** 1741 * make sure workers do not muck with pid-file 1742 */ 1743 if (0 <= pid_fd) { 1744 close(pid_fd); 1745 pid_fd = -1; 1746 } 1747 srv->srvconf.pid_file = NULL; 1748 1749 fdlog_pipes_abandon_pids(); 1750 srv->pid = getpid(); 1751 li_rand_reseed(); 1752 } 1753 #endif 1754 1755 srv->max_fds = (int)srv->srvconf.max_fds; 1756 if (srv->max_fds < 32) /*(sanity check; not expected)*/ 1757 srv->max_fds = 32; /*(server load checks will fail if too low)*/ 1758 srv->ev = fdevent_init(srv->srvconf.event_handler, &srv->max_fds, &srv->cur_fds, srv->errh); 1759 if (NULL == srv->ev) { 1760 log_error(srv->errh, __FILE__, __LINE__, "fdevent_init failed"); 1761 return -1; 1762 } 1763 1764 srv->max_fds_lowat = srv->max_fds * 8 / 10; 1765 srv->max_fds_hiwat = srv->max_fds * 9 / 10; 1766 1767 /* set max-conns */ 1768 if (srv->srvconf.max_conns > srv->max_fds/2) { 1769 /* we can't have more connections than max-fds/2 */ 1770 log_error(srv->errh, __FILE__, __LINE__, 1771 "can't have more connections than fds/2: %hu %d", 1772 srv->srvconf.max_conns, srv->max_fds); 1773 srv->lim_conns = srv->srvconf.max_conns = srv->max_fds/2; 1774 } else if (srv->srvconf.max_conns) { 1775 /* otherwise respect the wishes of the user */ 1776 srv->lim_conns = srv->srvconf.max_conns; 1777 } else { 1778 /* or use the default: we really don't want to hit max-fds */ 1779 srv->lim_conns = srv->srvconf.max_conns = srv->max_fds/3; 1780 } 1781 1782 /* libev backend overwrites our SIGCHLD handler and calls waitpid on SIGCHLD; we want our own SIGCHLD handling. */ 1783 #ifdef HAVE_SIGACTION 1784 sigaction(SIGCHLD, &act, NULL); 1785 #elif defined(HAVE_SIGNAL) 1786 signal(SIGCHLD, signal_handler); 1787 #endif 1788 1789 /* 1790 * kqueue() is called here, select resets its internals, 1791 * all server sockets get their handlers 1792 * 1793 * */ 1794 if (0 != network_register_fdevents(srv)) { 1795 return -1; 1796 } 1797 1798 chunkqueue_internal_pipes(config_feature_bool(srv, "chunkqueue.splice", 1)); 1799 1800 /* might fail if user is using fam (not gamin) and famd isn't running */ 1801 if (!stat_cache_init(srv->ev, srv->errh)) { 1802 log_error(srv->errh, __FILE__, __LINE__, 1803 "stat-cache could not be setup, dying."); 1804 return -1; 1805 } 1806 1807 #ifdef USE_ALARM 1808 { 1809 /* setup periodic timer (1 second) */ 1810 struct itimerval interval; 1811 interval.it_interval.tv_sec = 1; 1812 interval.it_interval.tv_usec = 0; 1813 interval.it_value.tv_sec = 1; 1814 interval.it_value.tv_usec = 0; 1815 if (setitimer(ITIMER_REAL, &interval, NULL)) { 1816 log_perror(srv->errh, __FILE__, __LINE__, "setitimer()"); 1817 return -1; 1818 } 1819 } 1820 #endif 1821 1822 /* get the current number of FDs */ 1823 { 1824 int fd = fdevent_open_devnull(); 1825 if (fd >= 0) { 1826 srv->cur_fds = fd; 1827 close(fd); 1828 } 1829 } 1830 1831 if (0 != server_sockets_set_nb_cloexec(srv)) { 1832 return -1; 1833 } 1834 1835 /* plugin hook for worker_init */ 1836 if (HANDLER_GO_ON != plugins_call_worker_init(srv)) 1837 return -1; 1838 1839 if (oneshot_fdout > 0) { 1840 if (server_oneshot_init_pipe(srv, oneshot_fd, oneshot_fdout)) { 1841 oneshot_fd = -1; 1842 oneshot_fdout = -1; 1843 } 1844 } 1845 else if (oneshot_fd && server_oneshot_init(srv, oneshot_fd)) { 1846 oneshot_fd = -1; 1847 } 1848 1849 if (0 == srv->srvconf.max_worker) 1850 server_graceful_signal_prev_generation(); 1851 1852 return 1; 1853 } 1854 1855 __attribute_cold__ 1856 __attribute_noinline__ 1857 static void server_handle_sighup (server * const srv) { 1858 1859 /* cycle logfiles */ 1860 1861 plugins_call_handle_sighup(srv); 1862 fdlog_files_cycle(srv->errh); /* reopen log files, not pipes */ 1863 #ifdef HAVE_SIGACTION 1864 log_error(srv->errh, __FILE__, __LINE__, 1865 "logfiles cycled UID = %d PID = %d", 1866 (int)last_sighup_info.si_uid, 1867 (int)last_sighup_info.si_pid); 1868 #else 1869 log_error(srv->errh, __FILE__, __LINE__, 1870 "logfiles cycled"); 1871 #endif 1872 } 1873 1874 __attribute_noinline__ 1875 static void server_handle_sigalrm (server * const srv, unix_time64_t mono_ts, unix_time64_t last_active_ts) { 1876 1877 plugins_call_handle_trigger(srv); 1878 1879 log_monotonic_secs = mono_ts; 1880 log_epoch_secs = server_epoch_secs(srv, 0); 1881 1882 /* check idle time limit, if enabled */ 1883 if (idle_limit && idle_limit < mono_ts - last_active_ts && !graceful_shutdown) { 1884 log_error(srv->errh, __FILE__, __LINE__, 1885 "[note] idle timeout %ds exceeded, " 1886 "initiating graceful shutdown", (int)idle_limit); 1887 graceful_shutdown = 2; /* value 2 indicates idle timeout */ 1888 if (graceful_restart) { 1889 graceful_restart = 0; 1890 if (pid_fd < -2) pid_fd = -pid_fd; 1891 server_sockets_close(srv); 1892 } 1893 } 1894 1895 #ifdef HAVE_GETLOADAVG 1896 /* refresh loadavg data every 30 seconds */ 1897 if (srv->loadts + 30 < mono_ts) { 1898 if (-1 != getloadavg(srv->loadavg, 3)) { 1899 srv->loadts = mono_ts; 1900 } 1901 } 1902 #endif 1903 1904 if (0 == (mono_ts & 0x3f)) { /*(once every 64 secs)*/ 1905 /* free logger buffers every 64 secs */ 1906 fdlog_flushall(srv->errh); 1907 /* free excess chunkqueue buffers every 64 secs */ 1908 chunkqueue_chunk_pool_clear(); 1909 /* clear request and connection pools every 64 secs */ 1910 request_pool_free(); 1911 connections_pool_clear(srv); 1912 #if defined(HAVE_MALLOC_TRIM) 1913 if (malloc_trim_fn) malloc_trim_fn(malloc_top_pad); 1914 #endif 1915 /* attempt to restart dead piped loggers every 64 secs */ 1916 if (0 == srv->srvconf.max_worker) 1917 fdlog_pipes_restart(mono_ts); 1918 } 1919 /* cleanup stat-cache */ 1920 stat_cache_trigger_cleanup(); 1921 /* reset global/aggregate rate limit counters */ 1922 config_reset_config_bytes_sec(srv->config_data_base); 1923 /* if graceful_shutdown, accelerate cleanup of recently completed request/responses */ 1924 if (graceful_shutdown && !srv_shutdown) 1925 server_graceful_shutdown_maint(srv); 1926 connection_periodic_maint(srv, mono_ts); 1927 } 1928 1929 __attribute_noinline__ 1930 static void server_handle_sigchld (server * const srv) { 1931 pid_t pid; 1932 do { 1933 int status; 1934 pid = fdevent_waitpid(-1, &status, 1); 1935 if (pid > 0) { 1936 if (plugins_call_handle_waitpid(srv, pid, status) != HANDLER_GO_ON) { 1937 continue; 1938 } 1939 if (0 == srv->srvconf.max_worker) { 1940 /* check piped-loggers and restart, even if shutting down */ 1941 if (fdlog_pipes_waitpid_cb(pid)) { 1942 continue; 1943 } 1944 } 1945 } 1946 } while (pid > 0 || (-1 == pid && errno == EINTR)); 1947 } 1948 1949 __attribute_hot__ 1950 __attribute_nonnull__() 1951 static void server_run_con_queue (connection * const restrict joblist, const connection * const sentinel) { 1952 for (connection *con = joblist, *jqnext; con != sentinel; con = jqnext) { 1953 jqnext = con->jqnext; 1954 con->jqnext = NULL; 1955 connection_state_machine(con); 1956 } 1957 } 1958 1959 __attribute_hot__ 1960 __attribute_noinline__ 1961 static void server_main_loop (server * const srv) { 1962 unix_time64_t last_active_ts = server_monotonic_secs(); 1963 log_epoch_secs = server_epoch_secs(srv, 0); 1964 1965 while (!srv_shutdown) { 1966 1967 if (handle_sig_hup) { 1968 handle_sig_hup = 0; 1969 server_handle_sighup(srv); 1970 } 1971 1972 /*(USE_ALARM not used; fdevent_poll() is effective periodic timer)*/ 1973 #ifdef USE_ALARM 1974 if (handle_sig_alarm) { 1975 handle_sig_alarm = 0; 1976 #endif 1977 unix_time64_t mono_ts = server_monotonic_secs(); 1978 if (mono_ts != log_monotonic_secs) { 1979 server_handle_sigalrm(srv, mono_ts, last_active_ts); 1980 } 1981 #ifdef USE_ALARM 1982 } 1983 #endif 1984 1985 if (handle_sig_child) { 1986 handle_sig_child = 0; 1987 server_handle_sigchld(srv); 1988 } 1989 1990 if (graceful_shutdown) { 1991 server_graceful_state(srv); 1992 if (NULL == srv->conns && graceful_shutdown) { 1993 /* we are in graceful shutdown phase and all connections are closed 1994 * we are ready to terminate without harming anyone */ 1995 srv_shutdown = 1; 1996 break; 1997 } 1998 } else if (srv->sockets_disabled) { 1999 server_overload_check(srv); 2000 } else { 2001 server_load_check(srv); 2002 } 2003 2004 static connection * const sentinel = 2005 (connection *)(uintptr_t)&log_con_jqueue; 2006 connection * const joblist = log_con_jqueue; 2007 log_con_jqueue = sentinel; 2008 server_run_con_queue(joblist, sentinel); 2009 2010 if (fdevent_poll(srv->ev, log_con_jqueue != sentinel ? 0 : 1000) > 0) 2011 last_active_ts = log_monotonic_secs; 2012 } 2013 } 2014 2015 __attribute_cold__ 2016 __attribute_noinline__ 2017 static int main_init_once (void) { 2018 #ifdef HAVE_GETUID 2019 #ifndef HAVE_ISSETUGID 2020 #define issetugid() (geteuid() != getuid() || getegid() != getgid()) 2021 #endif 2022 if (0 != getuid() && issetugid()) { /*check as early as possible in main()*/ 2023 fprintf(stderr, 2024 "Are you nuts ? Don't apply a SUID bit to this binary\n"); 2025 return 0; 2026 } 2027 #endif 2028 2029 #if defined(HAVE_MALLOPT) && defined(M_ARENA_MAX) 2030 #ifdef LIGHTTPD_STATIC 2031 mallopt(M_ARENA_MAX, 2); /*(ignore error, if any)*/ 2032 #else 2033 { 2034 int (*mallopt_fn)(int, int); 2035 mallopt_fn = (int (*)(int, int))(intptr_t)dlsym(RTLD_DEFAULT,"mallopt"); 2036 if (mallopt_fn) mallopt_fn(M_ARENA_MAX, 2); /*(ignore error, if any)*/ 2037 } 2038 #endif 2039 #endif 2040 2041 #if defined(HAVE_MALLOC_TRIM) 2042 malloc_top_pad = 524288; 2043 { 2044 const char * const top_pad_str = getenv("MALLOC_TOP_PAD_"); 2045 if (top_pad_str) { 2046 unsigned long top_pad = strtoul(top_pad_str, NULL, 10); 2047 if (top_pad != ULONG_MAX) malloc_top_pad = (size_t)top_pad; 2048 } 2049 } 2050 #ifdef LIGHTTPD_STATIC 2051 malloc_trim_fn = malloc_trim; 2052 #else 2053 malloc_trim_fn = 2054 (int (*)(size_t))(intptr_t)dlsym(RTLD_DEFAULT,"malloc_trim"); 2055 #endif 2056 #endif 2057 2058 /* for nice %b handling in strftime() */ 2059 setlocale(LC_TIME, "C"); 2060 tzset(); 2061 2062 return 1; 2063 } 2064 2065 __attribute_cold__ 2066 int main (int argc, char ** argv) { 2067 if (!main_init_once()) return -1; 2068 2069 int rc; 2070 2071 do { 2072 server * const srv = server_init(); 2073 2074 if (graceful_restart) { 2075 server_sockets_restore(srv); 2076 optind = 1; 2077 } 2078 2079 rc = server_main_setup(srv, argc, argv); 2080 if (rc > 0) { 2081 2082 server_main_loop(srv); 2083 2084 if (graceful_shutdown || graceful_restart) { 2085 server_graceful_state(srv); 2086 } 2087 2088 if (NULL == srv->conns) rc = 0; 2089 if (2 == graceful_shutdown) { /* value 2 indicates idle timeout */ 2090 log_error(srv->errh, __FILE__, __LINE__, 2091 "server stopped after idle timeout"); 2092 } else if (!oneshot_fd) { 2093 #ifdef HAVE_SIGACTION 2094 log_error(srv->errh, __FILE__, __LINE__, 2095 "server stopped by UID = %d PID = %d", 2096 (int)last_sigterm_info.si_uid, 2097 (int)last_sigterm_info.si_pid); 2098 #else 2099 log_error(srv->errh, __FILE__, __LINE__, 2100 "server stopped"); 2101 #endif 2102 } 2103 } 2104 2105 /* clean-up */ 2106 chunkqueue_internal_pipes(0); 2107 remove_pid_file(srv); 2108 config_log_error_close(srv); 2109 if (graceful_restart) 2110 server_sockets_save(srv); 2111 else 2112 network_close(srv); 2113 request_pool_free(); 2114 connections_free(srv); 2115 plugins_free(srv); 2116 server_free(srv); 2117 2118 if (rc < 0 || !graceful_restart) break; 2119 2120 /* wait for all children to exit before graceful restart */ 2121 while (fdevent_waitpid(-1, NULL, 0) > 0) ; 2122 } while (graceful_restart); 2123 2124 return rc; 2125 } 2126