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