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 "http_auth.h" /* http_auth_dumbdata_reset() */ 10 #include "http_vhostdb.h" /* http_vhostdb_dumbdata_reset() */ 11 #include "fdevent.h" 12 #include "connections.h" 13 #include "sock_addr.h" 14 #include "stat_cache.h" 15 #include "plugin.h" 16 #include "network_write.h" /* network_write_show_handlers() */ 17 #include "response.h" /* strftime_cache_reset() */ 18 19 #ifdef HAVE_VERSIONSTAMP_H 20 # include "versionstamp.h" 21 #else 22 # define REPO_VERSION "" 23 #endif 24 25 #define PACKAGE_DESC PACKAGE_NAME "/" PACKAGE_VERSION REPO_VERSION 26 static const buffer default_server_tag = { CONST_STR_LEN(PACKAGE_DESC), 0 }; 27 28 #include <sys/types.h> 29 #include <sys/time.h> 30 #include <sys/stat.h> 31 #include <sys/wait.h> 32 33 #include <string.h> 34 #include <errno.h> 35 #include <fcntl.h> 36 #include <unistd.h> 37 #include <stdlib.h> 38 #include <time.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_SYS_WAIT_H 53 # include <sys/wait.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 73 #include "sys-crypto.h" 74 #if defined(USE_OPENSSL_CRYPTO) \ 75 || defined(USE_MBEDTLS_CRYPTO) \ 76 || defined(USE_GNUTLS_CRYPTO) 77 #define TEXT_SSL " (ssl)" 78 #else 79 #define TEXT_SSL 80 #endif 81 82 #ifndef __sgi 83 /* IRIX doesn't like the alarm based time() optimization */ 84 /* #define USE_ALARM */ 85 #endif 86 87 static int oneshot_fd = 0; 88 static volatile int pid_fd = -2; 89 static server_socket_array graceful_sockets; 90 static server_socket_array inherited_sockets; 91 static volatile sig_atomic_t graceful_restart = 0; 92 static volatile sig_atomic_t graceful_shutdown = 0; 93 static volatile sig_atomic_t srv_shutdown = 0; 94 static volatile sig_atomic_t handle_sig_child = 0; 95 static volatile sig_atomic_t handle_sig_alarm = 1; 96 static volatile sig_atomic_t handle_sig_hup = 0; 97 static time_t idle_limit = 0; 98 99 #if defined(HAVE_SIGACTION) && defined(SA_SIGINFO) 100 static volatile siginfo_t last_sigterm_info; 101 static volatile siginfo_t last_sighup_info; 102 103 static void sigaction_handler(int sig, siginfo_t *si, void *context) { 104 static const siginfo_t empty_siginfo; 105 UNUSED(context); 106 107 if (!si) *(const siginfo_t **)&si = &empty_siginfo; 108 109 switch (sig) { 110 case SIGTERM: 111 srv_shutdown = 1; 112 last_sigterm_info = *si; 113 break; 114 case SIGUSR1: 115 if (!graceful_shutdown) { 116 graceful_restart = 1; 117 graceful_shutdown = 1; 118 last_sigterm_info = *si; 119 } 120 break; 121 case SIGINT: 122 if (graceful_shutdown) { 123 if (2 == graceful_restart) 124 graceful_restart = 1; 125 else 126 srv_shutdown = 1; 127 } else { 128 graceful_shutdown = 1; 129 } 130 last_sigterm_info = *si; 131 132 break; 133 case SIGALRM: 134 handle_sig_alarm = 1; 135 break; 136 case SIGHUP: 137 handle_sig_hup = 1; 138 last_sighup_info = *si; 139 break; 140 case SIGCHLD: 141 handle_sig_child = 1; 142 break; 143 } 144 } 145 #elif defined(HAVE_SIGNAL) || defined(HAVE_SIGACTION) 146 static void signal_handler(int sig) { 147 switch (sig) { 148 case SIGTERM: srv_shutdown = 1; break; 149 case SIGUSR1: 150 if (!graceful_shutdown) { 151 graceful_restart = 1; 152 graceful_shutdown = 1; 153 } 154 break; 155 case SIGINT: 156 if (graceful_shutdown) { 157 if (2 == graceful_restart) 158 graceful_restart = 1; 159 else 160 srv_shutdown = 1; 161 } else { 162 graceful_shutdown = 1; 163 } 164 break; 165 case SIGALRM: handle_sig_alarm = 1; break; 166 case SIGHUP: handle_sig_hup = 1; break; 167 case SIGCHLD: handle_sig_child = 1; break; 168 } 169 } 170 #endif 171 172 #ifdef HAVE_FORK 173 static int daemonize(void) { 174 int pipefd[2]; 175 pid_t pid; 176 #ifdef SIGTTOU 177 signal(SIGTTOU, SIG_IGN); 178 #endif 179 #ifdef SIGTTIN 180 signal(SIGTTIN, SIG_IGN); 181 #endif 182 #ifdef SIGTSTP 183 signal(SIGTSTP, SIG_IGN); 184 #endif 185 186 if (pipe(pipefd) < 0) exit(-1); 187 188 if (0 > (pid = fork())) exit(-1); 189 190 if (0 < pid) { 191 char buf; 192 ssize_t bytes; 193 194 close(pipefd[1]); 195 /* parent waits for grandchild to be ready */ 196 do { 197 bytes = read(pipefd[0], &buf, sizeof(buf)); 198 } while (bytes < 0 && EINTR == errno); 199 close(pipefd[0]); 200 201 if (bytes <= 0) { 202 /* closed fd (without writing) == failure in grandchild */ 203 fputs("daemonized server failed to start; check error log for details\n", stderr); 204 exit(-1); 205 } 206 207 exit(0); 208 } 209 210 close(pipefd[0]); 211 212 if (-1 == setsid()) exit(0); 213 214 signal(SIGHUP, SIG_IGN); 215 216 if (0 != fork()) exit(0); 217 218 if (0 != chdir("/")) exit(0); 219 220 fdevent_setfd_cloexec(pipefd[1]); 221 return pipefd[1]; 222 } 223 #endif 224 225 __attribute_cold__ 226 static server *server_init(void) { 227 server *srv = calloc(1, sizeof(*srv)); 228 force_assert(srv); 229 #define CLEAN(x) \ 230 srv->x = buffer_init(); 231 232 CLEAN(tmp_buf); 233 #undef CLEAN 234 235 strftime_cache_reset(); 236 237 li_rand_reseed(); 238 239 srv->startup_ts = log_epoch_secs = time(NULL); 240 241 srv->errh = log_error_st_init(); 242 243 config_init(srv); 244 245 srv->request_env = plugins_call_handle_request_env; 246 247 srv->loadavg[0] = 0.0; 248 srv->loadavg[1] = 0.0; 249 srv->loadavg[2] = 0.0; 250 251 return srv; 252 } 253 254 __attribute_cold__ 255 static void server_free(server *srv) { 256 if (oneshot_fd > 0) { 257 close(oneshot_fd); 258 } 259 260 #define CLEAN(x) \ 261 buffer_free(srv->x); 262 263 CLEAN(tmp_buf); 264 265 #undef CLEAN 266 267 fdevent_free(srv->ev); 268 269 config_free(srv); 270 271 free(srv->joblist.ptr); 272 free(srv->fdwaitqueue.ptr); 273 274 stat_cache_free(); 275 276 li_rand_cleanup(); 277 chunkqueue_chunk_pool_free(); 278 279 log_error_st_free(srv->errh); 280 free(srv); 281 } 282 283 __attribute_cold__ 284 static void remove_pid_file(server *srv) { 285 if (pid_fd <= -2) return; 286 if (!buffer_string_is_empty(srv->srvconf.pid_file) && 0 <= pid_fd) { 287 if (0 != ftruncate(pid_fd, 0)) { 288 log_perror(srv->errh, __FILE__, __LINE__, 289 "ftruncate failed for: %s", srv->srvconf.pid_file->ptr); 290 } 291 } 292 if (0 <= pid_fd) { 293 close(pid_fd); 294 pid_fd = -1; 295 } 296 if (!buffer_string_is_empty(srv->srvconf.pid_file) && 297 buffer_string_is_empty(srv->srvconf.changeroot)) { 298 if (0 != unlink(srv->srvconf.pid_file->ptr)) { 299 if (errno != EACCES && errno != EPERM) { 300 log_perror(srv->errh, __FILE__, __LINE__, 301 "unlink failed for: %s", srv->srvconf.pid_file->ptr); 302 } 303 } 304 } 305 } 306 307 308 __attribute_cold__ 309 static server_socket * server_oneshot_getsock(server *srv, sock_addr *cnt_addr) { 310 server_socket *srv_socket, *srv_socket_wild = NULL; 311 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) { 312 srv_socket = srv->srv_sockets.ptr[i]; 313 if (!sock_addr_is_port_eq(&srv_socket->addr,cnt_addr)) continue; 314 if (sock_addr_is_addr_eq(&srv_socket->addr,cnt_addr)) return srv_socket; 315 316 if (NULL != srv_socket_wild) continue; 317 if (sock_addr_is_addr_wildcard(&srv_socket->addr)) { 318 srv_socket_wild = srv_socket; 319 } 320 } 321 322 if (NULL != srv_socket_wild) { 323 return srv_socket_wild; 324 } else if (srv->srv_sockets.used) { 325 return srv->srv_sockets.ptr[0]; 326 } else { 327 log_error(srv->errh, __FILE__, __LINE__, "no sockets configured"); 328 return NULL; 329 } 330 } 331 332 333 __attribute_cold__ 334 static int server_oneshot_init(server *srv, int fd) { 335 /* Note: does not work with netcat due to requirement that fd be socket. 336 * STDOUT_FILENO was not saved earlier in startup, and that is to where 337 * netcat expects output to be sent. Since lighttpd expects connections 338 * to be sockets, con->fd is where output is sent; separate fds are not 339 * stored for input and output, but netcat has different fds for stdin 340 * and * stdout. To support netcat, would additionally need to avoid 341 * S_ISSOCK(), getsockname(), and getpeername() below, reconstructing 342 * addresses from environment variables: 343 * NCAT_LOCAL_ADDR NCAT_LOCAL_PORT 344 * NCAT_REMOTE_ADDR NCAT_REMOTE_PORT 345 * NCAT_PROTO 346 */ 347 connection *con; 348 server_socket *srv_socket; 349 sock_addr cnt_addr; 350 socklen_t cnt_len; 351 struct stat st; 352 353 if (0 != fstat(fd, &st)) { 354 log_perror(srv->errh, __FILE__, __LINE__, "fstat()"); 355 return 0; 356 } 357 358 if (!S_ISSOCK(st.st_mode)) { 359 /* require that fd is a socket 360 * (modules might expect STDIN_FILENO and STDOUT_FILENO opened to /dev/null) */ 361 log_error(srv->errh, __FILE__, __LINE__, 362 "lighttpd -1 stdin is not a socket"); 363 return 0; 364 } 365 366 cnt_len = sizeof(cnt_addr); 367 if (0 != getsockname(fd, (struct sockaddr *)&cnt_addr, &cnt_len)) { 368 log_perror(srv->errh, __FILE__, __LINE__, "getsockname()"); 369 return 0; 370 } 371 372 srv_socket = server_oneshot_getsock(srv, &cnt_addr); 373 if (NULL == srv_socket) return 0; 374 375 cnt_len = sizeof(cnt_addr); 376 if (0 != getpeername(fd, (struct sockaddr *)&cnt_addr, &cnt_len)) { 377 log_perror(srv->errh, __FILE__, __LINE__, "getpeername()"); 378 return 0; 379 } 380 381 /*(must set flags; fd did not pass through fdevent accept() logic)*/ 382 if (-1 == fdevent_fcntl_set_nb_cloexec(fd)) { 383 log_perror(srv->errh, __FILE__, __LINE__, "fcntl()"); 384 return 0; 385 } 386 387 if (sock_addr_get_family(&cnt_addr) != AF_UNIX) { 388 network_accept_tcp_nagle_disable(fd); 389 } 390 391 con = connection_accepted(srv, srv_socket, &cnt_addr, fd); 392 if (NULL == con) return 0; 393 394 connection_state_machine(con); 395 return 1; 396 } 397 398 399 __attribute_cold__ 400 static void show_version (void) { 401 char *b = PACKAGE_DESC TEXT_SSL \ 402 " - a light and fast webserver\n" 403 #ifdef NONREPRODUCIBLE_BUILD 404 "Build-Date: " __DATE__ " " __TIME__ "\n"; 405 #endif 406 ; 407 write_all(STDOUT_FILENO, b, strlen(b)); 408 } 409 410 __attribute_cold__ 411 static void show_features (void) { 412 static const char features[] = 413 "\nFeatures:\n\n" 414 #ifdef HAVE_IPV6 415 "\t+ IPv6 support\n" 416 #else 417 "\t- IPv6 support\n" 418 #endif 419 #if defined HAVE_ZLIB_H && defined HAVE_LIBZ 420 "\t+ zlib support\n" 421 #else 422 "\t- zlib support\n" 423 #endif 424 #if defined HAVE_BZLIB_H && defined HAVE_LIBBZ2 425 "\t+ bzip2 support\n" 426 #else 427 "\t- bzip2 support\n" 428 #endif 429 #if defined(HAVE_CRYPT) || defined(HAVE_CRYPT_R) || defined(HAVE_LIBCRYPT) 430 "\t+ crypt support\n" 431 #else 432 "\t- crypt support\n" 433 #endif 434 #ifdef USE_OPENSSL_CRYPTO 435 "\t+ OpenSSL support\n" 436 #else 437 "\t- OpenSSL support\n" 438 #endif 439 #ifdef USE_MBEDTLS_CRYPTO 440 "\t+ mbedTLS support\n" 441 #else 442 "\t- mbedTLS support\n" 443 #endif 444 #ifdef USE_GNUTLS_CRYPTO 445 "\t+ GnuTLS support\n" 446 #else 447 "\t- GnuTLS support\n" 448 #endif 449 #ifdef USE_NETTLE_CRYPTO 450 "\t+ Nettle support\n" 451 #else 452 "\t- Nettle support\n" 453 #endif 454 #ifdef HAVE_LIBPCRE 455 "\t+ PCRE support\n" 456 #else 457 "\t- PCRE support\n" 458 #endif 459 #ifdef HAVE_MYSQL 460 "\t+ MySQL support\n" 461 #else 462 "\t- MySQL support\n" 463 #endif 464 #ifdef HAVE_PGSQL 465 "\t+ PgSQL support\n" 466 #else 467 "\t- PgSQL support\n" 468 #endif 469 #ifdef HAVE_DBI 470 "\t+ DBI support\n" 471 #else 472 "\t- DBI support\n" 473 #endif 474 #ifdef HAVE_KRB5 475 "\t+ Kerberos support\n" 476 #else 477 "\t- Kerberos support\n" 478 #endif 479 #if defined(HAVE_LDAP_H) && defined(HAVE_LBER_H) && defined(HAVE_LIBLDAP) && defined(HAVE_LIBLBER) 480 "\t+ LDAP support\n" 481 #else 482 "\t- LDAP support\n" 483 #endif 484 #ifdef HAVE_PAM 485 "\t+ PAM support\n" 486 #else 487 "\t- PAM support\n" 488 #endif 489 #ifdef USE_MEMCACHED 490 "\t+ memcached support\n" 491 #else 492 "\t- memcached support\n" 493 #endif 494 #ifdef HAVE_FAM_H 495 "\t+ FAM support\n" 496 #else 497 "\t- FAM support\n" 498 #endif 499 #ifdef HAVE_LUA_H 500 "\t+ LUA support\n" 501 #else 502 "\t- LUA support\n" 503 #endif 504 #ifdef HAVE_LIBXML_H 505 "\t+ xml support\n" 506 #else 507 "\t- xml support\n" 508 #endif 509 #ifdef HAVE_SQLITE3_H 510 "\t+ SQLite support\n" 511 #else 512 "\t- SQLite support\n" 513 #endif 514 #ifdef HAVE_GDBM_H 515 "\t+ GDBM support\n" 516 #else 517 "\t- GDBM support\n" 518 #endif 519 ; 520 show_version(); 521 printf("%s%s%s\n", fdevent_show_event_handlers(), network_write_show_handlers(), features); 522 } 523 524 __attribute_cold__ 525 static void show_help (void) { 526 char *b = PACKAGE_DESC TEXT_SSL 527 #ifdef NONREPRODUCIBLE_BUILD 528 " ("__DATE__ " " __TIME__ ")" 529 #endif 530 " - a light and fast webserver\n" \ 531 "usage:\n" \ 532 " -f <name> filename of the config-file\n" \ 533 " -m <name> module directory (default: "LIBRARY_DIR")\n" \ 534 " -i <secs> graceful shutdown after <secs> of inactivity\n" \ 535 " -1 process single (one) request on stdin socket, then exit\n" \ 536 " -p print the parsed config-file in internal form, and exit\n" \ 537 " -t test config-file syntax, then exit\n" \ 538 " -tt test config-file syntax, load and init modules, then exit\n" \ 539 " -D don't go to background (default: go to background)\n" \ 540 " -v show version\n" \ 541 " -V show compile-time features\n" \ 542 " -h show this help\n" \ 543 "\n" 544 ; 545 write_all(STDOUT_FILENO, b, strlen(b)); 546 } 547 548 __attribute_cold__ 549 static void server_sockets_save (server *srv) { /* graceful_restart */ 550 memcpy(&graceful_sockets, &srv->srv_sockets, sizeof(server_socket_array)); 551 memset(&srv->srv_sockets, 0, sizeof(server_socket_array)); 552 memcpy(&inherited_sockets, &srv->srv_sockets_inherited, sizeof(server_socket_array)); 553 memset(&srv->srv_sockets_inherited, 0, sizeof(server_socket_array)); 554 } 555 556 __attribute_cold__ 557 static void server_sockets_restore (server *srv) { /* graceful_restart */ 558 memcpy(&srv->srv_sockets, &graceful_sockets, sizeof(server_socket_array)); 559 memset(&graceful_sockets, 0, sizeof(server_socket_array)); 560 memcpy(&srv->srv_sockets_inherited, &inherited_sockets, sizeof(server_socket_array)); 561 memset(&inherited_sockets, 0, sizeof(server_socket_array)); 562 } 563 564 __attribute_cold__ 565 static int server_sockets_set_nb_cloexec (server *srv) { 566 if (srv->sockets_disabled) return 0; /* lighttpd -1 (one-shot mode) */ 567 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) { 568 server_socket *srv_socket = srv->srv_sockets.ptr[i]; 569 if (-1 == fdevent_fcntl_set_nb_cloexec_sock(srv_socket->fd)) { 570 log_perror(srv->errh, __FILE__, __LINE__, "fcntl()"); 571 return -1; 572 } 573 } 574 return 0; 575 } 576 577 __attribute_cold__ 578 static void server_sockets_set_event (server *srv, int event) { 579 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) { 580 server_socket *srv_socket = srv->srv_sockets.ptr[i]; 581 fdevent_fdnode_event_set(srv->ev, srv_socket->fdn, event); 582 } 583 } 584 585 __attribute_cold__ 586 static void server_sockets_unregister (server *srv) { 587 if (2 == srv->sockets_disabled) return; 588 srv->sockets_disabled = 2; 589 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) 590 network_unregister_sock(srv, srv->srv_sockets.ptr[i]); 591 } 592 593 __attribute_cold__ 594 static void server_sockets_close (server *srv) { 595 /* closing socket right away will make it possible for the next lighttpd 596 * to take over (old-style graceful restart), but only if backends 597 * (e.g. fastcgi, scgi, etc) are independent from lighttpd, rather 598 * than started by lighttpd via "bin-path") 599 */ 600 if (3 == srv->sockets_disabled) return; 601 for (uint32_t i = 0; i < srv->srv_sockets.used; ++i) { 602 server_socket *srv_socket = srv->srv_sockets.ptr[i]; 603 if (-1 == srv_socket->fd) continue; 604 if (2 != srv->sockets_disabled) network_unregister_sock(srv,srv_socket); 605 close(srv_socket->fd); 606 srv_socket->fd = -1; 607 /* network_close() will cleanup after us */ 608 } 609 srv->sockets_disabled = 3; 610 } 611 612 __attribute_cold__ 613 static void server_graceful_state (server *srv) { 614 615 if (!srv_shutdown) connection_graceful_shutdown_maint(srv); 616 617 if (!oneshot_fd 618 && (2 == srv->sockets_disabled || 3 == srv->sockets_disabled)) return; 619 620 log_error(srv->errh,__FILE__,__LINE__,"[note] graceful shutdown started"); 621 622 /* no graceful restart if chroot()ed, if oneshot mode, or if idle timeout */ 623 if (!buffer_string_is_empty(srv->srvconf.changeroot) 624 || oneshot_fd || 2 == graceful_shutdown) 625 graceful_restart = 0; 626 627 if (graceful_restart) { 628 server_sockets_unregister(srv); 629 if (pid_fd > 0) pid_fd = -pid_fd; /*(flag to skip removing pid file)*/ 630 } 631 else { 632 server_sockets_close(srv); 633 remove_pid_file(srv); 634 /*(prevent more removal attempts)*/ 635 if (srv->srvconf.pid_file) buffer_clear(srv->srvconf.pid_file); 636 } 637 } 638 639 __attribute_cold__ 640 static void server_sockets_enable (server *srv) { 641 server_sockets_set_event(srv, FDEVENT_IN); 642 srv->sockets_disabled = 0; 643 log_error(srv->errh, __FILE__, __LINE__, "[note] sockets enabled again"); 644 } 645 646 __attribute_cold__ 647 static void server_sockets_disable (server *srv) { 648 server_sockets_set_event(srv, 0); 649 srv->sockets_disabled = 1; 650 log_error(srv->errh, __FILE__, __LINE__, 651 (srv->conns.used >= srv->max_conns) 652 ? "[note] sockets disabled, connection limit reached" 653 : "[note] sockets disabled, out-of-fds"); 654 } 655 656 __attribute_cold__ 657 static void server_overload_check (server *srv) { 658 if (srv->cur_fds + (int)srv->fdwaitqueue.used < srv->max_fds_lowat 659 && srv->conns.used < srv->max_conns) { 660 661 server_sockets_enable(srv); 662 } 663 } 664 665 static void server_load_check (server *srv) { 666 /* check if hit limits for num fds used or num connections */ 667 if (srv->cur_fds > srv->max_fds_hiwat || srv->conns.used >= srv->max_conns) 668 server_sockets_disable(srv); 669 } 670 671 __attribute_cold__ 672 __attribute_noinline__ 673 static void server_process_fdwaitqueue (server *srv) { 674 connections * const fdwaitqueue = &srv->fdwaitqueue; 675 uint32_t i = 0; 676 for (int n = srv->max_fds - srv->cur_fds - 16; n > 0; --n) { 677 if (i == fdwaitqueue->used) break; 678 connection_state_machine(fdwaitqueue->ptr[i++]); 679 } 680 if (i > 0 && 0 != (fdwaitqueue->used -= i)) { 681 memmove(fdwaitqueue->ptr, fdwaitqueue->ptr+i, fdwaitqueue->used * sizeof(*(fdwaitqueue->ptr))); 682 } 683 } 684 685 __attribute_cold__ 686 static int server_main_setup (server * const srv, int argc, char **argv) { 687 int print_config = 0; 688 int test_config = 0; 689 int i_am_root = 0; 690 int o; 691 #ifdef HAVE_FORK 692 int num_childs = 0; 693 #endif 694 uint32_t i; 695 #ifdef HAVE_SIGACTION 696 struct sigaction act; 697 #endif 698 699 #ifdef HAVE_FORK 700 int parent_pipe_fd = -1; 701 #endif 702 int stdin_fd = -1; 703 704 #ifdef HAVE_GETUID 705 i_am_root = (0 == getuid()); 706 #endif 707 708 /* initialize globals (including file-scoped static globals) */ 709 oneshot_fd = 0; 710 srv_shutdown = 0; 711 graceful_shutdown = 0; 712 handle_sig_alarm = 1; 713 handle_sig_hup = 0; 714 idle_limit = 0; 715 chunkqueue_set_tempdirs_default_reset(); 716 http_auth_dumbdata_reset(); 717 http_vhostdb_dumbdata_reset(); 718 /*graceful_restart = 0;*//*(reset below to avoid further daemonizing)*/ 719 /*(intentionally preserved)*/ 720 /*memset(graceful_sockets, 0, sizeof(graceful_sockets));*/ 721 /*memset(inherited_sockets, 0, sizeof(inherited_sockets));*/ 722 /*pid_fd = -1;*/ 723 724 while(-1 != (o = getopt(argc, argv, "f:m:i:hvVD1pt"))) { 725 switch(o) { 726 case 'f': 727 if (srv->config_data_base) { 728 log_error(srv->errh, __FILE__, __LINE__, 729 "Can only read one config file. Use the include command to use multiple config files."); 730 return -1; 731 } 732 if (config_read(srv, optarg)) { 733 return -1; 734 } 735 break; 736 case 'm': 737 buffer_copy_string(srv->srvconf.modules_dir, optarg); 738 break; 739 case 'i': { 740 char *endptr; 741 long timeout = strtol(optarg, &endptr, 0); 742 if (!*optarg || *endptr || timeout < 0) { 743 log_error(srv->errh, __FILE__, __LINE__, 744 "Invalid idle timeout value: %s", optarg); 745 return -1; 746 } 747 idle_limit = (time_t)timeout; 748 break; 749 } 750 case 'p': print_config = 1; break; 751 case 't': ++test_config; break; 752 case '1': if (0 == oneshot_fd) oneshot_fd = dup(STDIN_FILENO); 753 break; 754 case 'D': srv->srvconf.dont_daemonize = 1; break; 755 case 'v': show_version(); return 0; 756 case 'V': show_features(); return 0; 757 case 'h': show_help(); return 0; 758 default: 759 show_help(); 760 return -1; 761 } 762 } 763 764 #ifdef __CYGWIN__ 765 if (!srv->config_data_base && NULL != getenv("NSSM_SERVICE_NAME")) { 766 char *dir = getenv("NSSM_SERVICE_DIR"); 767 if (NULL != dir && 0 != chdir(dir)) { 768 log_perror(srv->errh, __FILE__, __LINE__, "chdir %s failed", dir); 769 return -1; 770 } 771 srv->srvconf.dont_daemonize = 1; 772 buffer_copy_string_len(srv->srvconf.modules_dir, CONST_STR_LEN("modules")); 773 if (config_read(srv, "conf/lighttpd.conf")) return -1; 774 } 775 #endif 776 777 if (!srv->config_data_base) { 778 log_error(srv->errh, __FILE__, __LINE__, 779 "No configuration available. Try using -f option."); 780 return -1; 781 } 782 783 if (print_config) { 784 config_print(srv); 785 fprintf(stdout, "\n"); 786 } 787 788 if (test_config) { 789 if (srv->srvconf.pid_file) buffer_clear(srv->srvconf.pid_file); 790 if (1 == test_config) { 791 printf("Syntax OK\n"); 792 } else { /*(test_config > 1)*/ 793 test_config = 0; 794 srv->srvconf.preflight_check = 1; 795 srv->srvconf.dont_daemonize = 1; 796 } 797 } 798 799 if (test_config || print_config) { 800 return 0; 801 } 802 803 if (oneshot_fd) { 804 if (oneshot_fd <= STDERR_FILENO) { 805 log_error(srv->errh, __FILE__, __LINE__, 806 "Invalid fds at startup with lighttpd -1"); 807 return -1; 808 } 809 graceful_shutdown = 1; 810 srv->sockets_disabled = 1; 811 srv->srvconf.dont_daemonize = 1; 812 if (srv->srvconf.pid_file) buffer_clear(srv->srvconf.pid_file); 813 if (srv->srvconf.max_worker) { 814 srv->srvconf.max_worker = 0; 815 log_error(srv->errh, __FILE__, __LINE__, 816 "server one-shot command line option disables server.max-worker config file option."); 817 } 818 } 819 820 if (srv->srvconf.bindhost && buffer_is_equal_string(srv->srvconf.bindhost, CONST_STR_LEN("/dev/stdin"))) { 821 stdin_fd = dup(STDIN_FILENO); 822 if (stdin_fd <= STDERR_FILENO) { 823 log_error(srv->errh, __FILE__, __LINE__, 824 "Invalid fds at startup"); 825 return -1; 826 } 827 } 828 829 /* close stdin and stdout, as they are not needed */ 830 { 831 struct stat st; 832 int devnull; 833 int errfd; 834 do { 835 /* coverity[overwrite_var : FALSE] */ 836 devnull = fdevent_open_devnull(); 837 #ifdef __COVERITY__ 838 __coverity_escape__(devnull); 839 #endif 840 } while (-1 != devnull && devnull <= STDERR_FILENO); 841 if (-1 == devnull) { 842 log_perror(srv->errh, __FILE__, __LINE__, 843 "opening /dev/null failed"); 844 return -1; 845 } 846 errfd = (0 == fstat(STDERR_FILENO, &st)) ? -1 : devnull; 847 if (0 != fdevent_set_stdin_stdout_stderr(devnull, devnull, errfd)) { 848 log_perror(srv->errh, __FILE__, __LINE__, 849 "setting default fds failed"); 850 #ifdef FD_CLOEXEC 851 if (-1 != errfd) close(errfd); 852 if (devnull != errfd) close(devnull); 853 #endif 854 return -1; 855 } 856 #ifdef FD_CLOEXEC 857 if (-1 != errfd) close(errfd); 858 if (devnull != errfd) close(devnull); 859 #endif 860 } 861 862 if (0 != config_set_defaults(srv)) { 863 log_error(srv->errh, __FILE__, __LINE__, 864 "setting default values failed"); 865 return -1; 866 } 867 868 if (plugins_load(srv)) { 869 log_error(srv->errh, __FILE__, __LINE__, 870 "loading plugins finally failed"); 871 return -1; 872 } 873 874 if (HANDLER_GO_ON != plugins_call_init(srv)) { 875 log_error(srv->errh, __FILE__, __LINE__, 876 "Initialization of plugins failed. Going down."); 877 return -1; 878 } 879 880 /* mod_indexfile should be listed in server.modules prior to dynamic handlers */ 881 i = 0; 882 for (const char *pname = NULL; i < srv->plugins.used; ++i) { 883 plugin *p = ((plugin **)srv->plugins.ptr)[i]; 884 if (NULL != pname && 0 == strcmp(p->name, "indexfile")) { 885 log_error(srv->errh, __FILE__, __LINE__, 886 "Warning: mod_indexfile should be listed in server.modules prior to mod_%s", pname); 887 break; 888 } 889 if (p->handle_subrequest_start && p->handle_subrequest) { 890 if (!pname) pname = p->name; 891 } 892 } 893 894 /* open pid file BEFORE chroot */ 895 if (-2 == pid_fd) pid_fd = -1; /*(initial startup state)*/ 896 if (-1 == pid_fd && !buffer_string_is_empty(srv->srvconf.pid_file)) { 897 const char *pidfile = srv->srvconf.pid_file->ptr; 898 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))) { 899 struct stat st; 900 if (errno != EEXIST) { 901 log_perror(srv->errh, __FILE__, __LINE__, 902 "opening pid-file failed: %s", pidfile); 903 return -1; 904 } 905 906 if (0 != stat(pidfile, &st)) { 907 log_perror(srv->errh, __FILE__, __LINE__, 908 "stating existing pid-file failed: %s", pidfile); 909 } 910 911 if (!S_ISREG(st.st_mode)) { 912 log_error(srv->errh, __FILE__, __LINE__, 913 "pid-file exists and isn't regular file: %s", pidfile); 914 return -1; 915 } 916 917 if (-1 == (pid_fd = fdevent_open_cloexec(pidfile, 0, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) { 918 log_perror(srv->errh, __FILE__, __LINE__, 919 "opening pid-file failed: %s", pidfile); 920 return -1; 921 } 922 } 923 } 924 925 { 926 #ifdef HAVE_GETRLIMIT 927 struct rlimit rlim; 928 int use_rlimit = 1; 929 #ifdef HAVE_VALGRIND_VALGRIND_H 930 if (RUNNING_ON_VALGRIND) use_rlimit = 0; 931 #endif 932 933 if (0 != getrlimit(RLIMIT_NOFILE, &rlim)) { 934 log_perror(srv->errh, __FILE__, __LINE__, "getrlimit()"); 935 return -1; 936 } 937 938 /** 939 * if we are not root can can't increase the fd-limit above rlim_max, but we can reduce it 940 */ 941 if (use_rlimit && srv->srvconf.max_fds 942 && (i_am_root || srv->srvconf.max_fds <= rlim.rlim_max)) { 943 /* set rlimits */ 944 945 rlim.rlim_cur = srv->srvconf.max_fds; 946 if (i_am_root) rlim.rlim_max = srv->srvconf.max_fds; 947 948 if (0 != setrlimit(RLIMIT_NOFILE, &rlim)) { 949 log_perror(srv->errh, __FILE__, __LINE__, "setrlimit()"); 950 return -1; 951 } 952 } 953 954 /*(default upper limit of 4k if server.max-fds not specified)*/ 955 if (0 == srv->srvconf.max_fds) 956 srv->srvconf.max_fds = (rlim.rlim_cur <= 4096) 957 ? (unsigned short)rlim.rlim_cur 958 : 4096; 959 960 /* set core file rlimit, if enable_cores is set */ 961 if (use_rlimit && srv->srvconf.enable_cores && getrlimit(RLIMIT_CORE, &rlim) == 0) { 962 rlim.rlim_cur = rlim.rlim_max; 963 setrlimit(RLIMIT_CORE, &rlim); 964 } 965 #endif 966 } 967 968 /* we need root-perms for port < 1024 */ 969 if (0 != network_init(srv, stdin_fd)) { 970 return -1; 971 } 972 973 if (i_am_root) { 974 #ifdef HAVE_PWD_H 975 /* set user and group */ 976 struct group *grp = NULL; 977 struct passwd *pwd = NULL; 978 979 if (!buffer_string_is_empty(srv->srvconf.groupname)) { 980 if (NULL == (grp = getgrnam(srv->srvconf.groupname->ptr))) { 981 log_error(srv->errh, __FILE__, __LINE__, 982 "can't find groupname %s", srv->srvconf.groupname->ptr); 983 return -1; 984 } 985 } 986 987 if (!buffer_string_is_empty(srv->srvconf.username)) { 988 if (NULL == (pwd = getpwnam(srv->srvconf.username->ptr))) { 989 log_error(srv->errh, __FILE__, __LINE__, 990 "can't find username %s", srv->srvconf.username->ptr); 991 return -1; 992 } 993 994 if (pwd->pw_uid == 0) { 995 log_error(srv->errh, __FILE__, __LINE__, 996 "I will not set uid to 0\n"); 997 return -1; 998 } 999 1000 if (NULL == grp && NULL == (grp = getgrgid(pwd->pw_gid))) { 1001 log_error(srv->errh, __FILE__, __LINE__, 1002 "can't find group id %d", (int)pwd->pw_gid); 1003 return -1; 1004 } 1005 } 1006 1007 if (NULL != grp) { 1008 if (grp->gr_gid == 0) { 1009 log_error(srv->errh, __FILE__, __LINE__, 1010 "I will not set gid to 0\n"); 1011 return -1; 1012 } 1013 } 1014 1015 /* 1016 * Change group before chroot, when we have access 1017 * to /etc/group 1018 * */ 1019 if (NULL != grp) { 1020 if (-1 == setgid(grp->gr_gid)) { 1021 log_perror(srv->errh, __FILE__, __LINE__, "setgid()"); 1022 return -1; 1023 } 1024 if (-1 == setgroups(0, NULL)) { 1025 log_perror(srv->errh, __FILE__, __LINE__, "setgroups()"); 1026 return -1; 1027 } 1028 if (!buffer_string_is_empty(srv->srvconf.username)) { 1029 initgroups(srv->srvconf.username->ptr, grp->gr_gid); 1030 } 1031 } 1032 #endif 1033 #ifdef HAVE_CHROOT 1034 if (!buffer_string_is_empty(srv->srvconf.changeroot)) { 1035 tzset(); 1036 1037 if (-1 == chroot(srv->srvconf.changeroot->ptr)) { 1038 log_perror(srv->errh, __FILE__, __LINE__, "chroot()"); 1039 return -1; 1040 } 1041 if (-1 == chdir("/")) { 1042 log_perror(srv->errh, __FILE__, __LINE__, "chdir()"); 1043 return -1; 1044 } 1045 } 1046 #endif 1047 #ifdef HAVE_PWD_H 1048 /* drop root privs */ 1049 if (NULL != pwd) { 1050 if (-1 == setuid(pwd->pw_uid)) { 1051 log_perror(srv->errh, __FILE__, __LINE__, "setuid()"); 1052 return -1; 1053 } 1054 } 1055 #endif 1056 #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE) 1057 /** 1058 * on IRIX 6.5.30 they have prctl() but no DUMPABLE 1059 */ 1060 if (srv->srvconf.enable_cores) { 1061 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0); 1062 } 1063 #endif 1064 } 1065 1066 #ifdef HAVE_FORK 1067 /* network is up, let's daemonize ourself */ 1068 if (0 == srv->srvconf.dont_daemonize && 0 == graceful_restart) { 1069 parent_pipe_fd = daemonize(); 1070 } 1071 #endif 1072 graceful_restart = 0;/*(reset here after avoiding further daemonizing)*/ 1073 if (0 == oneshot_fd) graceful_shutdown = 0; 1074 1075 1076 #ifdef HAVE_SIGACTION 1077 memset(&act, 0, sizeof(act)); 1078 act.sa_handler = SIG_IGN; 1079 sigaction(SIGPIPE, &act, NULL); 1080 # if defined(SA_SIGINFO) 1081 last_sighup_info.si_uid = 0, 1082 last_sighup_info.si_pid = 0; 1083 last_sigterm_info.si_uid = 0, 1084 last_sigterm_info.si_pid = 0; 1085 act.sa_sigaction = sigaction_handler; 1086 sigemptyset(&act.sa_mask); 1087 act.sa_flags = SA_SIGINFO; 1088 # else 1089 act.sa_handler = signal_handler; 1090 sigemptyset(&act.sa_mask); 1091 act.sa_flags = 0; 1092 # endif 1093 sigaction(SIGINT, &act, NULL); 1094 sigaction(SIGTERM, &act, NULL); 1095 sigaction(SIGHUP, &act, NULL); 1096 sigaction(SIGALRM, &act, NULL); 1097 sigaction(SIGUSR1, &act, NULL); 1098 1099 /* it should be safe to restart syscalls after SIGCHLD */ 1100 act.sa_flags |= SA_RESTART | SA_NOCLDSTOP; 1101 sigaction(SIGCHLD, &act, NULL); 1102 1103 #elif defined(HAVE_SIGNAL) 1104 /* ignore the SIGPIPE from sendfile() */ 1105 signal(SIGPIPE, SIG_IGN); 1106 signal(SIGALRM, signal_handler); 1107 signal(SIGTERM, signal_handler); 1108 signal(SIGHUP, signal_handler); 1109 signal(SIGCHLD, signal_handler); 1110 signal(SIGINT, signal_handler); 1111 signal(SIGUSR1, signal_handler); 1112 #endif 1113 1114 1115 srv->gid = getgid(); 1116 srv->uid = getuid(); 1117 srv->pid = getpid(); 1118 1119 /* write pid file */ 1120 if (pid_fd > 2) { 1121 buffer * const tb = srv->tmp_buf; 1122 buffer_clear(tb); 1123 buffer_append_int(tb, srv->pid); 1124 buffer_append_string_len(tb, CONST_STR_LEN("\n")); 1125 if (-1 == write_all(pid_fd, CONST_BUF_LEN(tb))) { 1126 log_perror(srv->errh, __FILE__, __LINE__, "Couldn't write pid file"); 1127 close(pid_fd); 1128 pid_fd = -1; 1129 return -1; 1130 } 1131 } else if (pid_fd < -2) { 1132 pid_fd = -pid_fd; 1133 } 1134 1135 /* Close stderr ASAP in the child process to make sure that nothing 1136 * is being written to that fd which may not be valid anymore. */ 1137 if (!srv->srvconf.preflight_check) { 1138 if (-1 == config_log_error_open(srv)) { 1139 log_error(srv->errh, __FILE__, __LINE__, "Opening errorlog failed. Going down."); 1140 return -1; 1141 } 1142 log_error(srv->errh, __FILE__, __LINE__, "server started (" PACKAGE_DESC ")"); 1143 } 1144 1145 if (HANDLER_GO_ON != plugins_call_set_defaults(srv)) { 1146 log_error(srv->errh, __FILE__, __LINE__, "Configuration of plugins failed. Going down."); 1147 return -1; 1148 } 1149 1150 if (!config_finalize(srv, &default_server_tag)) { 1151 return -1; 1152 } 1153 1154 if (srv->srvconf.preflight_check) { 1155 /*printf("Preflight OK");*//*(stdout reopened to /dev/null)*/ 1156 return 0; 1157 } 1158 1159 1160 #ifdef HAVE_FORK 1161 /** 1162 * notify daemonize-grandparent of successful startup 1163 * do this before any further forking is done (workers) 1164 */ 1165 if (0 == srv->srvconf.dont_daemonize && -1 != parent_pipe_fd) { 1166 if (0 > write(parent_pipe_fd, "", 1)) return -1; 1167 close(parent_pipe_fd); 1168 } 1169 1170 if (idle_limit && srv->srvconf.max_worker) { 1171 srv->srvconf.max_worker = 0; 1172 log_error(srv->errh, __FILE__, __LINE__, 1173 "server idle time limit command line option disables server.max-worker config file option."); 1174 } 1175 1176 /* start watcher and workers */ 1177 num_childs = srv->srvconf.max_worker; 1178 if (num_childs > 0) { 1179 pid_t pids[num_childs]; 1180 pid_t pid; 1181 const int npids = num_childs; 1182 int child = 0; 1183 unsigned int timer = 0; 1184 for (int n = 0; n < npids; ++n) pids[n] = -1; 1185 while (!child && !srv_shutdown && !graceful_shutdown) { 1186 if (num_childs > 0) { 1187 switch ((pid = fork())) { 1188 case -1: 1189 return -1; 1190 case 0: 1191 child = 1; 1192 alarm(0); 1193 break; 1194 default: 1195 num_childs--; 1196 for (int n = 0; n < npids; ++n) { 1197 if (-1 == pids[n]) { 1198 pids[n] = pid; 1199 break; 1200 } 1201 } 1202 break; 1203 } 1204 } else { 1205 int status; 1206 1207 if (-1 != (pid = wait(&status))) { 1208 log_epoch_secs = time(NULL); 1209 if (plugins_call_handle_waitpid(srv, pid, status) != HANDLER_GO_ON) { 1210 if (!timer) alarm((timer = 5)); 1211 continue; 1212 } 1213 switch (fdevent_reaped_logger_pipe(pid)) { 1214 default: break; 1215 case -1: if (!timer) alarm((timer = 5)); 1216 /* fall through */ 1217 case 1: continue; 1218 } 1219 /** 1220 * check if one of our workers went away 1221 */ 1222 for (int n = 0; n < npids; ++n) { 1223 if (pid == pids[n]) { 1224 pids[n] = -1; 1225 num_childs++; 1226 break; 1227 } 1228 } 1229 } else { 1230 switch (errno) { 1231 case EINTR: 1232 log_epoch_secs = time(NULL); 1233 /** 1234 * if we receive a SIGHUP we have to close our logs ourself as we don't 1235 * have the mainloop who can help us here 1236 */ 1237 if (handle_sig_hup) { 1238 handle_sig_hup = 0; 1239 1240 config_log_error_cycle(srv); 1241 1242 /* forward SIGHUP to workers */ 1243 for (int n = 0; n < npids; ++n) { 1244 if (pids[n] > 0) kill(pids[n], SIGHUP); 1245 } 1246 } 1247 if (handle_sig_alarm) { 1248 handle_sig_alarm = 0; 1249 timer = 0; 1250 plugins_call_handle_trigger(srv); 1251 fdevent_restart_logger_pipes(log_epoch_secs); 1252 } 1253 break; 1254 default: 1255 break; 1256 } 1257 } 1258 } 1259 } 1260 1261 /** 1262 * for the parent this is the exit-point 1263 */ 1264 if (!child) { 1265 /** 1266 * kill all children too 1267 */ 1268 if (graceful_shutdown || graceful_restart) { 1269 /* flag to ignore one SIGINT if graceful_restart */ 1270 if (graceful_restart) graceful_restart = 2; 1271 kill(0, SIGINT); 1272 server_graceful_state(srv); 1273 } else if (srv_shutdown) { 1274 kill(0, SIGTERM); 1275 } 1276 1277 return 0; 1278 } 1279 1280 /* ignore SIGUSR1 in workers; only parent directs graceful restart */ 1281 #ifdef HAVE_SIGACTION 1282 { 1283 struct sigaction actignore; 1284 memset(&actignore, 0, sizeof(actignore)); 1285 actignore.sa_handler = SIG_IGN; 1286 sigaction(SIGUSR1, &actignore, NULL); 1287 } 1288 #elif defined(HAVE_SIGNAL) 1289 signal(SIGUSR1, SIG_IGN); 1290 #endif 1291 1292 /** 1293 * make sure workers do not muck with pid-file 1294 */ 1295 if (0 <= pid_fd) { 1296 close(pid_fd); 1297 pid_fd = -1; 1298 } 1299 if (srv->srvconf.pid_file) buffer_clear(srv->srvconf.pid_file); 1300 1301 fdevent_clr_logger_pipe_pids(); 1302 srv->pid = getpid(); 1303 li_rand_reseed(); 1304 } 1305 #endif 1306 1307 srv->max_fds = (int)srv->srvconf.max_fds; 1308 srv->ev = fdevent_init(srv->srvconf.event_handler, &srv->max_fds, &srv->cur_fds, srv->errh); 1309 if (NULL == srv->ev) { 1310 log_error(srv->errh, __FILE__, __LINE__, "fdevent_init failed"); 1311 return -1; 1312 } 1313 1314 srv->max_fds_lowat = srv->max_fds * 8 / 10; 1315 srv->max_fds_hiwat = srv->max_fds * 9 / 10; 1316 1317 /* set max-conns */ 1318 if (srv->srvconf.max_conns > srv->max_fds/2) { 1319 /* we can't have more connections than max-fds/2 */ 1320 log_error(srv->errh, __FILE__, __LINE__, 1321 "can't have more connections than fds/2: %hu %d", 1322 srv->srvconf.max_conns, srv->max_fds); 1323 srv->max_conns = srv->max_fds/2; 1324 } else if (srv->srvconf.max_conns) { 1325 /* otherwise respect the wishes of the user */ 1326 srv->max_conns = srv->srvconf.max_conns; 1327 } else { 1328 /* or use the default: we really don't want to hit max-fds */ 1329 srv->max_conns = srv->max_fds/3; 1330 } 1331 1332 /* libev backend overwrites our SIGCHLD handler and calls waitpid on SIGCHLD; we want our own SIGCHLD handling. */ 1333 #ifdef HAVE_SIGACTION 1334 sigaction(SIGCHLD, &act, NULL); 1335 #elif defined(HAVE_SIGNAL) 1336 signal(SIGCHLD, signal_handler); 1337 #endif 1338 1339 /* 1340 * kqueue() is called here, select resets its internals, 1341 * all server sockets get their handlers 1342 * 1343 * */ 1344 if (0 != network_register_fdevents(srv)) { 1345 return -1; 1346 } 1347 1348 /* might fail if user is using fam (not gamin) and famd isn't running */ 1349 if (!stat_cache_init(srv->ev, srv->errh)) { 1350 log_error(srv->errh, __FILE__, __LINE__, 1351 "stat-cache could not be setup, dying."); 1352 return -1; 1353 } 1354 1355 #ifdef USE_ALARM 1356 { 1357 /* setup periodic timer (1 second) */ 1358 struct itimerval interval; 1359 interval.it_interval.tv_sec = 1; 1360 interval.it_interval.tv_usec = 0; 1361 interval.it_value.tv_sec = 1; 1362 interval.it_value.tv_usec = 0; 1363 if (setitimer(ITIMER_REAL, &interval, NULL)) { 1364 log_perror(srv->errh, __FILE__, __LINE__, "setitimer()"); 1365 return -1; 1366 } 1367 } 1368 #endif 1369 1370 /* get the current number of FDs */ 1371 { 1372 int fd = fdevent_open_devnull(); 1373 if (fd >= 0) { 1374 srv->cur_fds = fd; 1375 close(fd); 1376 } 1377 } 1378 1379 if (0 != server_sockets_set_nb_cloexec(srv)) { 1380 return -1; 1381 } 1382 1383 /* plugin hook for worker_init */ 1384 if (HANDLER_GO_ON != plugins_call_worker_init(srv)) 1385 return -1; 1386 1387 if (oneshot_fd && server_oneshot_init(srv, oneshot_fd)) { 1388 oneshot_fd = -1; 1389 } 1390 1391 return 1; 1392 } 1393 1394 __attribute_cold__ 1395 __attribute_noinline__ 1396 static void server_handle_sighup (server * const srv) { 1397 1398 /* cycle logfiles */ 1399 1400 plugins_call_handle_sighup(srv); 1401 1402 config_log_error_cycle(srv); 1403 #ifdef HAVE_SIGACTION 1404 log_error(srv->errh, __FILE__, __LINE__, 1405 "logfiles cycled UID = %d PID = %d", 1406 (int)last_sighup_info.si_uid, 1407 (int)last_sighup_info.si_pid); 1408 #else 1409 log_error(srv->errh, __FILE__, __LINE__, 1410 "logfiles cycled"); 1411 #endif 1412 } 1413 1414 __attribute_noinline__ 1415 static void server_handle_sigalrm (server * const srv, time_t min_ts, time_t last_active_ts) { 1416 1417 plugins_call_handle_trigger(srv); 1418 1419 log_epoch_secs = min_ts; 1420 1421 /* check idle time limit, if enabled */ 1422 if (idle_limit && idle_limit < min_ts - last_active_ts && !graceful_shutdown) { 1423 log_error(srv->errh, __FILE__, __LINE__, 1424 "[note] idle timeout %ds exceeded, " 1425 "initiating graceful shutdown", (int)idle_limit); 1426 graceful_shutdown = 2; /* value 2 indicates idle timeout */ 1427 if (graceful_restart) { 1428 graceful_restart = 0; 1429 if (pid_fd < -2) pid_fd = -pid_fd; 1430 server_sockets_close(srv); 1431 } 1432 } 1433 1434 #ifdef HAVE_GETLOADAVG 1435 /* refresh loadavg data every 30 seconds */ 1436 if (srv->loadts + 30 < min_ts) { 1437 if (-1 != getloadavg(srv->loadavg, 3)) { 1438 srv->loadts = min_ts; 1439 } 1440 } 1441 #endif 1442 1443 if (0 == (min_ts & 0x3f)) { /*(once every 64 secs)*/ 1444 /* free excess chunkqueue buffers every 64 secs */ 1445 chunkqueue_chunk_pool_clear(); 1446 /* attempt to restart dead piped loggers every 64 secs */ 1447 if (0 == srv->srvconf.max_worker) 1448 fdevent_restart_logger_pipes(min_ts); 1449 } 1450 /* cleanup stat-cache */ 1451 stat_cache_trigger_cleanup(); 1452 /* reset global/aggregate rate limit counters */ 1453 config_reset_config_bytes_sec(srv->config_data_base); 1454 /* if graceful_shutdown, accelerate cleanup of recently completed request/responses */ 1455 if (graceful_shutdown && !srv_shutdown) connection_graceful_shutdown_maint(srv); 1456 connection_periodic_maint(srv, min_ts); 1457 } 1458 1459 __attribute_noinline__ 1460 static void server_handle_sigchld (server * const srv) { 1461 pid_t pid; 1462 do { 1463 int status; 1464 pid = waitpid(-1, &status, WNOHANG); 1465 if (pid > 0) { 1466 if (plugins_call_handle_waitpid(srv, pid, status) != HANDLER_GO_ON) { 1467 continue; 1468 } 1469 if (0 == srv->srvconf.max_worker) { 1470 /* check piped-loggers and restart, even if shutting down */ 1471 if (fdevent_waitpid_logger_pipe_pid(pid, log_epoch_secs)) { 1472 continue; 1473 } 1474 } 1475 } 1476 } while (pid > 0 || (-1 == pid && errno == EINTR)); 1477 } 1478 1479 __attribute_hot__ 1480 __attribute_noinline__ 1481 static void server_main_loop (server * const srv) { 1482 connections * const joblist = &srv->joblist; 1483 time_t last_active_ts = time(NULL); 1484 1485 while (!srv_shutdown) { 1486 1487 if (handle_sig_hup) { 1488 handle_sig_hup = 0; 1489 server_handle_sighup(srv); 1490 } 1491 1492 /*(USE_ALARM not used; fdevent_poll() is effective periodic timer)*/ 1493 #ifdef USE_ALARM 1494 if (handle_sig_alarm) { 1495 handle_sig_alarm = 0; 1496 #endif 1497 time_t min_ts = time(NULL); 1498 if (min_ts != log_epoch_secs) { 1499 server_handle_sigalrm(srv, min_ts, last_active_ts); 1500 } 1501 #ifdef USE_ALARM 1502 } 1503 #endif 1504 1505 if (handle_sig_child) { 1506 handle_sig_child = 0; 1507 server_handle_sigchld(srv); 1508 } 1509 1510 if (graceful_shutdown) { 1511 server_graceful_state(srv); 1512 if (0 == srv->conns.used) { 1513 /* we are in graceful shutdown phase and all connections are closed 1514 * we are ready to terminate without harming anyone */ 1515 srv_shutdown = 1; 1516 break; 1517 } 1518 } else if (srv->sockets_disabled) { 1519 server_overload_check(srv); 1520 } else { 1521 server_load_check(srv); 1522 } 1523 1524 if (srv->fdwaitqueue.used) { 1525 server_process_fdwaitqueue(srv); 1526 } 1527 1528 if (fdevent_poll(srv->ev, 1000) > 0) { 1529 last_active_ts = log_epoch_secs; 1530 } 1531 1532 for (uint32_t ndx = 0; ndx < joblist->used; ++ndx) { 1533 connection *con = joblist->ptr[ndx]; 1534 connection_state_machine(con); 1535 } 1536 joblist->used = 0; 1537 } 1538 } 1539 1540 __attribute_cold__ 1541 int main (int argc, char **argv) { 1542 int rc; 1543 1544 #ifdef HAVE_GETUID 1545 #ifndef HAVE_ISSETUGID 1546 #define issetugid() (geteuid() != getuid() || getegid() != getgid()) 1547 #endif 1548 if (0 != getuid() && issetugid()) { /*check as early as possible in main()*/ 1549 fprintf(stderr, 1550 "Are you nuts ? Don't apply a SUID bit to this binary\n"); 1551 return -1; 1552 } 1553 #endif 1554 1555 /* for nice %b handling in strftime() */ 1556 setlocale(LC_TIME, "C"); 1557 1558 do { 1559 server * const srv = server_init(); 1560 1561 if (graceful_restart) { 1562 server_sockets_restore(srv); 1563 optind = 1; 1564 } 1565 1566 rc = server_main_setup(srv, argc, argv); 1567 if (rc > 0) { 1568 1569 server_main_loop(srv); 1570 1571 if (graceful_shutdown || graceful_restart) { 1572 server_graceful_state(srv); 1573 } 1574 1575 if (2 == graceful_shutdown) { /* value 2 indicates idle timeout */ 1576 log_error(srv->errh, __FILE__, __LINE__, 1577 "server stopped after idle timeout"); 1578 } else { 1579 #ifdef HAVE_SIGACTION 1580 log_error(srv->errh, __FILE__, __LINE__, 1581 "server stopped by UID = %d PID = %d", 1582 (int)last_sigterm_info.si_uid, 1583 (int)last_sigterm_info.si_pid); 1584 #else 1585 log_error(srv->errh, __FILE__, __LINE__, 1586 "server stopped"); 1587 #endif 1588 } 1589 } 1590 1591 /* clean-up */ 1592 remove_pid_file(srv); 1593 config_log_error_close(srv); 1594 if (graceful_restart) 1595 server_sockets_save(srv); 1596 else 1597 network_close(srv); 1598 connections_free(srv); 1599 plugins_free(srv); 1600 server_free(srv); 1601 1602 if (rc < 0 || !graceful_restart) break; 1603 1604 /* wait for all children to exit before graceful restart */ 1605 while (waitpid(-1, NULL, 0) > 0) ; 1606 } while (graceful_restart); 1607 1608 return rc; 1609 } 1610