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