daemon.c (333530B)
1 /* 2 This file is part of libmicrohttpd 3 Copyright (C) 2007-2018 Daniel Pittman and Christian Grothoff 4 Copyright (C) 2015-2024 Evgeny Grin (Karlson2k) 5 6 This library is free software; you can redistribute it and/or 7 modify it under the terms of the GNU Lesser General Public 8 License as published by the Free Software Foundation; either 9 version 2.1 of the License, or (at your option) any later version. 10 11 This library is distributed in the hope that it will be useful, 12 but WITHOUT ANY WARRANTY; without even the implied warranty of 13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 Lesser General Public License for more details. 15 16 You should have received a copy of the GNU Lesser General Public 17 License along with this library; if not, write to the Free Software 18 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 19 20 */ 21 22 /** 23 * @file microhttpd/daemon.c 24 * @brief A minimal-HTTP server library 25 * @author Daniel Pittman 26 * @author Christian Grothoff 27 * @author Karlson2k (Evgeny Grin) 28 */ 29 #include "platform.h" 30 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 31 #include "mhd_threads.h" 32 #endif 33 #include "internal.h" 34 #include "response.h" 35 #include "connection.h" 36 #include "memorypool.h" 37 #include "mhd_limits.h" 38 #include "autoinit_funcs.h" 39 #include "mhd_mono_clock.h" 40 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 41 #include "mhd_locks.h" 42 #endif 43 #include "mhd_sockets.h" 44 #include "mhd_itc.h" 45 #include "mhd_compat.h" 46 #include "mhd_send.h" 47 #include "mhd_align.h" 48 #include "mhd_str.h" 49 50 #ifdef MHD_USE_SYS_TSEARCH 51 #include <search.h> 52 #else /* ! MHD_USE_SYS_TSEARCH */ 53 #include "tsearch.h" 54 #endif /* ! MHD_USE_SYS_TSEARCH */ 55 56 #ifdef HTTPS_SUPPORT 57 #include "connection_https.h" 58 #ifdef MHD_HTTPS_REQUIRE_GCRYPT 59 #include <gcrypt.h> 60 #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ 61 #endif /* HTTPS_SUPPORT */ 62 63 #if defined(_WIN32) && ! defined(__CYGWIN__) 64 #ifndef WIN32_LEAN_AND_MEAN 65 #define WIN32_LEAN_AND_MEAN 1 66 #endif /* !WIN32_LEAN_AND_MEAN */ 67 #include <windows.h> 68 #endif 69 70 #ifdef MHD_USE_POSIX_THREADS 71 #ifdef HAVE_SIGNAL_H 72 #include <signal.h> 73 #endif /* HAVE_SIGNAL_H */ 74 #endif /* MHD_USE_POSIX_THREADS */ 75 76 /** 77 * Default connection limit. 78 */ 79 #ifdef MHD_POSIX_SOCKETS 80 #define MHD_MAX_CONNECTIONS_DEFAULT (FD_SETSIZE - 3 - 1 - MHD_ITC_NUM_FDS_) 81 #else 82 #define MHD_MAX_CONNECTIONS_DEFAULT (FD_SETSIZE - 2) 83 #endif 84 85 /** 86 * Default memory allowed per connection. 87 */ 88 #define MHD_POOL_SIZE_DEFAULT (32 * 1024) 89 90 91 /* Forward declarations. */ 92 93 94 /** 95 * Global initialisation function. 96 */ 97 void 98 MHD_init (void); 99 100 /** 101 * Global deinitialisation function. 102 */ 103 void 104 MHD_fini (void); 105 106 /** 107 * Close all connections for the daemon. 108 * Must only be called when MHD_Daemon::shutdown was set to true. 109 * @remark To be called only from thread that process 110 * daemon's select()/poll()/etc. 111 * 112 * @param daemon daemon to close down 113 */ 114 static void 115 close_all_connections (struct MHD_Daemon *daemon); 116 117 #ifdef EPOLL_SUPPORT 118 119 /** 120 * Do epoll()-based processing. 121 * 122 * @param daemon daemon to run poll loop for 123 * @param millisec the maximum time in milliseconds to wait for events, 124 * set to '0' for non-blocking processing, 125 * set to '-1' to wait indefinitely. 126 * @return #MHD_NO on serious errors, #MHD_YES on success 127 */ 128 static enum MHD_Result 129 MHD_epoll (struct MHD_Daemon *daemon, 130 int32_t millisec); 131 132 #endif /* EPOLL_SUPPORT */ 133 134 #ifdef _AUTOINIT_FUNCS_ARE_SUPPORTED 135 /** 136 * Do nothing - global initialisation is 137 * performed by library constructor. 138 */ 139 #define MHD_check_global_init_() (void) 0 140 #else /* ! _AUTOINIT_FUNCS_ARE_SUPPORTED */ 141 /** 142 * Track global initialisation 143 */ 144 volatile int global_init_count = 0; 145 146 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 147 #ifdef MHD_MUTEX_STATIC_DEFN_INIT_ 148 /** 149 * Global initialisation mutex 150 */ 151 MHD_MUTEX_STATIC_DEFN_INIT_ (global_init_mutex_); 152 #endif /* MHD_MUTEX_STATIC_DEFN_INIT_ */ 153 #endif 154 155 156 /** 157 * Check whether global initialisation was performed 158 * and call initialiser if necessary. 159 */ 160 void 161 MHD_check_global_init_ (void) 162 { 163 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 164 #ifdef MHD_MUTEX_STATIC_DEFN_INIT_ 165 MHD_mutex_lock_chk_ (&global_init_mutex_); 166 #endif /* MHD_MUTEX_STATIC_DEFN_INIT_ */ 167 #endif 168 if (0 == global_init_count++) 169 MHD_init (); 170 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 171 #ifdef MHD_MUTEX_STATIC_DEFN_INIT_ 172 MHD_mutex_unlock_chk_ (&global_init_mutex_); 173 #endif /* MHD_MUTEX_STATIC_DEFN_INIT_ */ 174 #endif 175 } 176 177 178 #endif /* ! _AUTOINIT_FUNCS_ARE_SUPPORTED */ 179 180 #ifdef HAVE_MESSAGES 181 /** 182 * Default logger function 183 */ 184 static void 185 MHD_default_logger_ (void *cls, 186 const char *fm, 187 va_list ap) 188 { 189 vfprintf ((FILE *) cls, fm, ap); 190 #ifdef _DEBUG 191 fflush ((FILE *) cls); 192 #endif /* _DEBUG */ 193 } 194 195 196 #endif /* HAVE_MESSAGES */ 197 198 199 /** 200 * Free the memory allocated by MHD. 201 * 202 * If any MHD function explicitly mentions that returned pointer must be 203 * freed by this function, then no other method must be used to free 204 * the memory. 205 * 206 * @param ptr the pointer to free. 207 * @sa #MHD_digest_auth_get_username(), #MHD_basic_auth_get_username_password3() 208 * @sa #MHD_basic_auth_get_username_password() 209 * @note Available since #MHD_VERSION 0x00095600 210 * @ingroup specialized 211 */ 212 _MHD_EXTERN void 213 MHD_free (void *ptr) 214 { 215 free (ptr); 216 } 217 218 219 /** 220 * Maintain connection count for single address. 221 */ 222 struct MHD_IPCount 223 { 224 /** 225 * Address family. AF_INET or AF_INET6 for now. 226 */ 227 int family; 228 229 /** 230 * Actual address. 231 */ 232 union 233 { 234 /** 235 * IPv4 address. 236 */ 237 struct in_addr ipv4; 238 #ifdef HAVE_INET6 239 /** 240 * IPv6 address. 241 */ 242 struct in6_addr ipv6; 243 #endif 244 } addr; 245 246 /** 247 * Counter. 248 */ 249 unsigned int count; 250 }; 251 252 253 /** 254 * Lock shared structure for IP connection counts and connection DLLs. 255 * 256 * @param daemon handle to daemon where lock is 257 */ 258 static void 259 MHD_ip_count_lock (struct MHD_Daemon *daemon) 260 { 261 mhd_assert (NULL == daemon->master); 262 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 263 MHD_mutex_lock_chk_ (&daemon->per_ip_connection_mutex); 264 #else 265 (void) daemon; 266 #endif 267 } 268 269 270 /** 271 * Unlock shared structure for IP connection counts and connection DLLs. 272 * 273 * @param daemon handle to daemon where lock is 274 */ 275 static void 276 MHD_ip_count_unlock (struct MHD_Daemon *daemon) 277 { 278 mhd_assert (NULL == daemon->master); 279 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 280 MHD_mutex_unlock_chk_ (&daemon->per_ip_connection_mutex); 281 #else 282 (void) daemon; 283 #endif 284 } 285 286 287 /** 288 * Tree comparison function for IP addresses (supplied to tsearch() family). 289 * We compare everything in the struct up through the beginning of the 290 * 'count' field. 291 * 292 * @param a1 first address to compare 293 * @param a2 second address to compare 294 * @return -1, 0 or 1 depending on result of compare 295 */ 296 static int 297 MHD_ip_addr_compare (const void *a1, 298 const void *a2) 299 { 300 return memcmp (a1, 301 a2, 302 offsetof (struct MHD_IPCount, 303 count)); 304 } 305 306 307 /** 308 * Parse address and initialize @a key using the address. 309 * 310 * @param addr address to parse 311 * @param addrlen number of bytes in @a addr 312 * @param key where to store the parsed address 313 * @return #MHD_YES on success and #MHD_NO otherwise (e.g., invalid address type) 314 */ 315 static enum MHD_Result 316 MHD_ip_addr_to_key (const struct sockaddr_storage *addr, 317 socklen_t addrlen, 318 struct MHD_IPCount *key) 319 { 320 memset (key, 321 0, 322 sizeof(*key)); 323 324 /* IPv4 addresses */ 325 if (sizeof (struct sockaddr_in) <= (size_t) addrlen) 326 { 327 if (AF_INET == addr->ss_family) 328 { 329 key->family = AF_INET; 330 memcpy (&key->addr.ipv4, 331 &((const struct sockaddr_in *) addr)->sin_addr, 332 sizeof(((const struct sockaddr_in *) NULL)->sin_addr)); 333 return MHD_YES; 334 } 335 } 336 337 #ifdef HAVE_INET6 338 if (sizeof (struct sockaddr_in6) <= (size_t) addrlen) 339 { 340 /* IPv6 addresses */ 341 if (AF_INET6 == addr->ss_family) 342 { 343 key->family = AF_INET6; 344 memcpy (&key->addr.ipv6, 345 &((const struct sockaddr_in6 *) addr)->sin6_addr, 346 sizeof(((const struct sockaddr_in6 *) NULL)->sin6_addr)); 347 return MHD_YES; 348 } 349 } 350 #endif 351 352 /* Some other address */ 353 return MHD_NO; 354 } 355 356 357 /** 358 * Check if IP address is over its limit in terms of the number 359 * of allowed concurrent connections. If the IP is still allowed, 360 * increments the connection counter. 361 * 362 * @param daemon handle to daemon where connection counts are tracked 363 * @param addr address to add (or increment counter) 364 * @param addrlen number of bytes in @a addr 365 * @return Return #MHD_YES if IP below limit, #MHD_NO if IP has surpassed limit. 366 * Also returns #MHD_NO if fails to allocate memory. 367 */ 368 static enum MHD_Result 369 MHD_ip_limit_add (struct MHD_Daemon *daemon, 370 const struct sockaddr_storage *addr, 371 socklen_t addrlen) 372 { 373 struct MHD_IPCount *newkeyp; 374 struct MHD_IPCount *keyp; 375 struct MHD_IPCount **nodep; 376 enum MHD_Result result; 377 378 daemon = MHD_get_master (daemon); 379 /* Ignore if no connection limit assigned */ 380 if (0 == daemon->per_ip_connection_limit) 381 return MHD_YES; 382 383 newkeyp = (struct MHD_IPCount *) malloc (sizeof(struct MHD_IPCount)); 384 if (NULL == newkeyp) 385 return MHD_NO; 386 387 /* Initialize key */ 388 if (MHD_NO == MHD_ip_addr_to_key (addr, 389 addrlen, 390 newkeyp)) 391 { 392 free (newkeyp); 393 return MHD_YES; /* Allow unhandled address types through */ 394 } 395 396 MHD_ip_count_lock (daemon); 397 398 /* Search for the IP address */ 399 nodep = (struct MHD_IPCount **) tsearch (newkeyp, 400 &daemon->per_ip_connection_count, 401 &MHD_ip_addr_compare); 402 if (NULL == nodep) 403 { 404 MHD_ip_count_unlock (daemon); 405 free (newkeyp); 406 #ifdef HAVE_MESSAGES 407 MHD_DLOG (daemon, 408 _ ("Failed to add IP connection count node.\n")); 409 #endif 410 return MHD_NO; 411 } 412 keyp = *nodep; 413 /* Test if there is room for another connection; if so, 414 * increment count */ 415 result = (keyp->count < daemon->per_ip_connection_limit) ? MHD_YES : MHD_NO; 416 if (MHD_NO != result) 417 ++keyp->count; 418 MHD_ip_count_unlock (daemon); 419 420 /* If we got an existing node back, free the one we created */ 421 if (keyp != newkeyp) 422 free (newkeyp); 423 424 return result; 425 } 426 427 428 /** 429 * Decrement connection count for IP address, removing from table 430 * count reaches 0. 431 * 432 * @param daemon handle to daemon where connection counts are tracked 433 * @param addr address to remove (or decrement counter) 434 * @param addrlen number of bytes in @a addr 435 */ 436 static void 437 MHD_ip_limit_del (struct MHD_Daemon *daemon, 438 const struct sockaddr_storage *addr, 439 socklen_t addrlen) 440 { 441 struct MHD_IPCount search_key; 442 struct MHD_IPCount *found_key; 443 void **nodep; 444 445 daemon = MHD_get_master (daemon); 446 /* Ignore if no connection limit assigned */ 447 if (0 == daemon->per_ip_connection_limit) 448 return; 449 /* Initialize search key */ 450 if (MHD_NO == MHD_ip_addr_to_key (addr, 451 addrlen, 452 &search_key)) 453 return; 454 455 MHD_ip_count_lock (daemon); 456 457 /* Search for the IP address */ 458 if (NULL == (nodep = tfind (&search_key, 459 &daemon->per_ip_connection_count, 460 &MHD_ip_addr_compare))) 461 { 462 /* Something's wrong if we couldn't find an IP address 463 * that was previously added */ 464 MHD_PANIC (_ ("Failed to find previously-added IP address.\n")); 465 } 466 found_key = (struct MHD_IPCount *) *nodep; 467 /* Validate existing count for IP address */ 468 if (0 == found_key->count) 469 { 470 MHD_PANIC (_ ("Previously-added IP address had counter of zero.\n")); 471 } 472 /* Remove the node entirely if count reduces to 0 */ 473 if (0 == --found_key->count) 474 { 475 tdelete (found_key, 476 &daemon->per_ip_connection_count, 477 &MHD_ip_addr_compare); 478 MHD_ip_count_unlock (daemon); 479 free (found_key); 480 } 481 else 482 MHD_ip_count_unlock (daemon); 483 } 484 485 486 #ifdef HTTPS_SUPPORT 487 /** 488 * Read and setup our certificate and key. 489 * 490 * @param daemon handle to daemon to initialize 491 * @return 0 on success 492 */ 493 static int 494 MHD_init_daemon_certificate (struct MHD_Daemon *daemon) 495 { 496 gnutls_datum_t key; 497 gnutls_datum_t cert; 498 int ret; 499 500 #if GNUTLS_VERSION_MAJOR >= 3 501 if (NULL != daemon->cert_callback) 502 { 503 gnutls_certificate_set_retrieve_function2 (daemon->x509_cred, 504 daemon->cert_callback); 505 } 506 #endif 507 #if GNUTLS_VERSION_NUMBER >= 0x030603 508 else if (NULL != daemon->cert_callback2) 509 { 510 gnutls_certificate_set_retrieve_function3 (daemon->x509_cred, 511 daemon->cert_callback2); 512 } 513 #endif 514 515 if (NULL != daemon->https_mem_trust) 516 { 517 size_t paramlen; 518 paramlen = strlen (daemon->https_mem_trust); 519 if (UINT_MAX < paramlen) 520 { 521 #ifdef HAVE_MESSAGES 522 MHD_DLOG (daemon, 523 _ ("Too long trust certificate.\n")); 524 #endif 525 return -1; 526 } 527 cert.data = (unsigned char *) _MHD_DROP_CONST (daemon->https_mem_trust); 528 cert.size = (unsigned int) paramlen; 529 if (gnutls_certificate_set_x509_trust_mem (daemon->x509_cred, 530 &cert, 531 GNUTLS_X509_FMT_PEM) < 0) 532 { 533 #ifdef HAVE_MESSAGES 534 MHD_DLOG (daemon, 535 _ ("Bad trust certificate format.\n")); 536 #endif 537 return -1; 538 } 539 } 540 541 if (daemon->have_dhparams) 542 { 543 gnutls_certificate_set_dh_params (daemon->x509_cred, 544 daemon->https_mem_dhparams); 545 } 546 /* certificate & key loaded from memory */ 547 if ( (NULL != daemon->https_mem_cert) && 548 (NULL != daemon->https_mem_key) ) 549 { 550 size_t param1len; 551 size_t param2len; 552 553 param1len = strlen (daemon->https_mem_key); 554 param2len = strlen (daemon->https_mem_cert); 555 if ( (UINT_MAX < param1len) || 556 (UINT_MAX < param2len) ) 557 { 558 #ifdef HAVE_MESSAGES 559 MHD_DLOG (daemon, 560 _ ("Too long key or certificate.\n")); 561 #endif 562 return -1; 563 } 564 key.data = (unsigned char *) _MHD_DROP_CONST (daemon->https_mem_key); 565 key.size = (unsigned int) param1len; 566 cert.data = (unsigned char *) _MHD_DROP_CONST (daemon->https_mem_cert); 567 cert.size = (unsigned int) param2len; 568 569 if (NULL != daemon->https_key_password) 570 { 571 #if GNUTLS_VERSION_NUMBER >= 0x030111 572 ret = gnutls_certificate_set_x509_key_mem2 (daemon->x509_cred, 573 &cert, 574 &key, 575 GNUTLS_X509_FMT_PEM, 576 daemon->https_key_password, 577 0); 578 #else 579 #ifdef HAVE_MESSAGES 580 MHD_DLOG (daemon, 581 _ ("Failed to setup x509 certificate/key: pre 3.X.X version " \ 582 "of GnuTLS does not support setting key password.\n")); 583 #endif 584 return -1; 585 #endif 586 } 587 else 588 ret = gnutls_certificate_set_x509_key_mem (daemon->x509_cred, 589 &cert, 590 &key, 591 GNUTLS_X509_FMT_PEM); 592 #ifdef HAVE_MESSAGES 593 if (0 != ret) 594 MHD_DLOG (daemon, 595 _ ("GnuTLS failed to setup x509 certificate/key: %s\n"), 596 gnutls_strerror (ret)); 597 #endif 598 return ret; 599 } 600 #if GNUTLS_VERSION_MAJOR >= 3 601 if (NULL != daemon->cert_callback) 602 return 0; 603 #endif 604 #if GNUTLS_VERSION_NUMBER >= 0x030603 605 else if (NULL != daemon->cert_callback2) 606 return 0; 607 #endif 608 #ifdef HAVE_MESSAGES 609 MHD_DLOG (daemon, 610 _ ("You need to specify a certificate and key location.\n")); 611 #endif 612 return -1; 613 } 614 615 616 /** 617 * Initialize security aspects of the HTTPS daemon 618 * 619 * @param daemon handle to daemon to initialize 620 * @return 0 on success 621 */ 622 static int 623 MHD_TLS_init (struct MHD_Daemon *daemon) 624 { 625 switch (daemon->cred_type) 626 { 627 case GNUTLS_CRD_CERTIFICATE: 628 if (0 != 629 gnutls_certificate_allocate_credentials (&daemon->x509_cred)) 630 return GNUTLS_E_MEMORY_ERROR; 631 return MHD_init_daemon_certificate (daemon); 632 case GNUTLS_CRD_PSK: 633 if (0 != 634 gnutls_psk_allocate_server_credentials (&daemon->psk_cred)) 635 return GNUTLS_E_MEMORY_ERROR; 636 return 0; 637 case GNUTLS_CRD_ANON: 638 case GNUTLS_CRD_SRP: 639 case GNUTLS_CRD_IA: 640 default: 641 #ifdef HAVE_MESSAGES 642 MHD_DLOG (daemon, 643 _ ("Error: invalid credentials type %d specified.\n"), 644 daemon->cred_type); 645 #endif 646 return -1; 647 } 648 } 649 650 651 /** 652 * Release the TLS resources that #MHD_start_daemon_va() may already have 653 * allocated when it decides to fail. 654 * 655 * The daemon object is not usable at that point, so #MHD_stop_daemon() 656 * (which is what frees these on the success path) cannot be called; each 657 * failure exit therefore has to do it, and every one of them used to 658 * forget the Diffie-Hellman parameters. Those are created by MHD itself 659 * from the PEM blob of #MHD_OPTION_HTTPS_MEM_DHPARAMS, so the 660 * application has no handle to free either. 661 * 662 * @param[in,out] daemon the half-initialised daemon 663 */ 664 static void 665 tls_cleanup_failed_start (struct MHD_Daemon *daemon) 666 { 667 if (daemon->have_dhparams) 668 { 669 gnutls_dh_params_deinit (daemon->https_mem_dhparams); 670 daemon->have_dhparams = false; 671 } 672 if (NULL != daemon->priority_cache) 673 { 674 gnutls_priority_deinit (daemon->priority_cache); 675 daemon->priority_cache = NULL; 676 } 677 if (NULL != daemon->x509_cred) 678 { 679 gnutls_certificate_free_credentials (daemon->x509_cred); 680 daemon->x509_cred = NULL; 681 } 682 if (NULL != daemon->psk_cred) 683 { 684 gnutls_psk_free_server_credentials (daemon->psk_cred); 685 daemon->psk_cred = NULL; 686 } 687 } 688 689 690 #endif /* HTTPS_SUPPORT */ 691 692 693 #undef MHD_get_fdset 694 695 /** 696 * Obtain the `select()` sets for this daemon. 697 * Daemon's FDs will be added to fd_sets. To get only 698 * daemon FDs in fd_sets, call FD_ZERO for each fd_set 699 * before calling this function. FD_SETSIZE is assumed 700 * to be platform's default. 701 * 702 * This function should be called only when MHD is configured to 703 * use "external" sockets polling with 'select()' or with 'epoll'. 704 * In the latter case, it will only add the single 'epoll' file 705 * descriptor used by MHD to the sets. 706 * It's necessary to use #MHD_get_timeout() to get maximum timeout 707 * value for `select()`. Usage of `select()` with indefinite timeout 708 * (or timeout larger than returned by #MHD_get_timeout()) will 709 * violate MHD API and may results in pending unprocessed data. 710 * 711 * This function must be called only for daemon started 712 * without #MHD_USE_INTERNAL_POLLING_THREAD flag. 713 * 714 * @param daemon daemon to get sets from 715 * @param read_fd_set read set 716 * @param write_fd_set write set 717 * @param except_fd_set except set 718 * @param max_fd increased to largest FD added (if larger 719 * than existing value); can be NULL 720 * @return #MHD_YES on success, #MHD_NO if this 721 * daemon was not started with the right 722 * options for this call or any FD didn't 723 * fit fd_set. 724 * @ingroup event 725 */ 726 _MHD_EXTERN enum MHD_Result 727 MHD_get_fdset (struct MHD_Daemon *daemon, 728 fd_set *read_fd_set, 729 fd_set *write_fd_set, 730 fd_set *except_fd_set, 731 MHD_socket *max_fd) 732 { 733 return MHD_get_fdset2 (daemon, 734 read_fd_set, 735 write_fd_set, 736 except_fd_set, 737 max_fd, 738 #ifdef HAS_FD_SETSIZE_OVERRIDABLE 739 daemon->fdset_size_set_by_app ? 740 ((unsigned int) daemon->fdset_size) : 741 ((unsigned int) _MHD_SYS_DEFAULT_FD_SETSIZE) 742 #else /* ! HAS_FD_SETSIZE_OVERRIDABLE */ 743 ((unsigned int) _MHD_SYS_DEFAULT_FD_SETSIZE) 744 #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ 745 ); 746 } 747 748 749 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) 750 /** 751 * Obtain the select() file descriptor sets for the 752 * given @a urh. 753 * 754 * @param urh upgrade handle to wait for 755 * @param[out] rs read set to initialize 756 * @param[out] ws write set to initialize 757 * @param[out] es except set to initialize 758 * @param[out] max_fd maximum FD to update 759 * @param fd_setsize value of FD_SETSIZE 760 * @return true on success, false on error 761 */ 762 static bool 763 urh_to_fdset (struct MHD_UpgradeResponseHandle *urh, 764 fd_set *rs, 765 fd_set *ws, 766 fd_set *es, 767 MHD_socket *max_fd, 768 int fd_setsize) 769 { 770 const MHD_socket conn_sckt = urh->connection->socket_fd; 771 const MHD_socket mhd_sckt = urh->mhd.socket; 772 bool res = true; 773 774 #ifndef HAS_FD_SETSIZE_OVERRIDABLE 775 (void) fd_setsize; /* Mute compiler warning */ 776 fd_setsize = (int) FD_SETSIZE; /* Help compiler to optimise */ 777 #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ 778 779 /* Do not add to 'es' only if socket is closed 780 * or not used anymore. */ 781 if (MHD_INVALID_SOCKET != conn_sckt) 782 { 783 if ( (urh->in_buffer_used < urh->in_buffer_size) && 784 (! MHD_add_to_fd_set_ (conn_sckt, 785 rs, 786 max_fd, 787 fd_setsize)) ) 788 res = false; 789 if ( (0 != urh->out_buffer_used) && 790 (! MHD_add_to_fd_set_ (conn_sckt, 791 ws, 792 max_fd, 793 fd_setsize)) ) 794 res = false; 795 /* Do not monitor again for errors if error was detected before as 796 * error state is remembered. */ 797 if ((0 == (urh->app.celi & MHD_EPOLL_STATE_ERROR)) && 798 ((0 != urh->in_buffer_size) || 799 (0 != urh->out_buffer_size) || 800 (0 != urh->out_buffer_used)) 801 && (NULL != es)) 802 (void) MHD_add_to_fd_set_ (conn_sckt, 803 es, 804 max_fd, 805 fd_setsize); 806 } 807 if (MHD_INVALID_SOCKET != mhd_sckt) 808 { 809 if ( (urh->out_buffer_used < urh->out_buffer_size) && 810 (! MHD_add_to_fd_set_ (mhd_sckt, 811 rs, 812 max_fd, 813 fd_setsize)) ) 814 res = false; 815 if ( (0 != urh->in_buffer_used) && 816 (! MHD_add_to_fd_set_ (mhd_sckt, 817 ws, 818 max_fd, 819 fd_setsize)) ) 820 res = false; 821 /* Do not monitor again for errors if error was detected before as 822 * error state is remembered. */ 823 if ((0 == (urh->mhd.celi & MHD_EPOLL_STATE_ERROR)) && 824 ((0 != urh->out_buffer_size) || 825 (0 != urh->in_buffer_size) || 826 (0 != urh->in_buffer_used)) 827 && (NULL != es)) 828 MHD_add_to_fd_set_ (mhd_sckt, 829 es, 830 max_fd, 831 fd_setsize); 832 } 833 834 return res; 835 } 836 837 838 /** 839 * Update the @a urh based on the ready FDs in 840 * the @a rs, @a ws, and @a es. 841 * 842 * @param urh upgrade handle to update 843 * @param rs read result from select() 844 * @param ws write result from select() 845 * @param es except result from select() 846 * @param fd_setsize value of FD_SETSIZE used when fd_sets were created 847 */ 848 static void 849 urh_from_fdset (struct MHD_UpgradeResponseHandle *urh, 850 const fd_set *rs, 851 const fd_set *ws, 852 const fd_set *es, 853 int fd_setsize) 854 { 855 const MHD_socket conn_sckt = urh->connection->socket_fd; 856 const MHD_socket mhd_sckt = urh->mhd.socket; 857 858 /* Reset read/write ready, preserve error state. */ 859 urh->app.celi &= (~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY) 860 & ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY)); 861 urh->mhd.celi &= (~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY) 862 & ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY)); 863 864 mhd_assert (urh->connection->sk_nonblck); 865 866 #ifndef HAS_FD_SETSIZE_OVERRIDABLE 867 (void) fd_setsize; /* Mute compiler warning */ 868 mhd_assert (((int) FD_SETSIZE) <= fd_setsize); 869 fd_setsize = FD_SETSIZE; /* Help compiler to optimise */ 870 #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ 871 872 if (MHD_INVALID_SOCKET != conn_sckt) 873 { 874 if (MHD_SCKT_FD_FITS_FDSET_SETSIZE_ (conn_sckt, NULL, fd_setsize)) 875 { 876 if (FD_ISSET (conn_sckt, (fd_set *) _MHD_DROP_CONST (rs))) 877 urh->app.celi |= MHD_EPOLL_STATE_READ_READY; 878 if (FD_ISSET (conn_sckt, (fd_set *) _MHD_DROP_CONST (ws))) 879 urh->app.celi |= MHD_EPOLL_STATE_WRITE_READY; 880 if ((NULL != es) && 881 FD_ISSET (conn_sckt, (fd_set *) _MHD_DROP_CONST (es))) 882 urh->app.celi |= MHD_EPOLL_STATE_ERROR; 883 } 884 else 885 { /* Cannot check readiness. Force ready state is safe as socket is non-blocking */ 886 urh->app.celi |= MHD_EPOLL_STATE_READ_READY; 887 urh->app.celi |= MHD_EPOLL_STATE_WRITE_READY; 888 } 889 } 890 if ((MHD_INVALID_SOCKET != mhd_sckt)) 891 { 892 if (MHD_SCKT_FD_FITS_FDSET_SETSIZE_ (mhd_sckt, NULL, fd_setsize)) 893 { 894 if (FD_ISSET (mhd_sckt, (fd_set *) _MHD_DROP_CONST (rs))) 895 urh->mhd.celi |= MHD_EPOLL_STATE_READ_READY; 896 if (FD_ISSET (mhd_sckt, (fd_set *) _MHD_DROP_CONST (ws))) 897 urh->mhd.celi |= MHD_EPOLL_STATE_WRITE_READY; 898 if ((NULL != es) && 899 FD_ISSET (mhd_sckt, (fd_set *) _MHD_DROP_CONST (es))) 900 urh->mhd.celi |= MHD_EPOLL_STATE_ERROR; 901 } 902 else 903 { /* Cannot check readiness. Force ready state is safe as socket is non-blocking */ 904 urh->mhd.celi |= MHD_EPOLL_STATE_READ_READY; 905 urh->mhd.celi |= MHD_EPOLL_STATE_WRITE_READY; 906 } 907 } 908 } 909 910 911 #ifdef HAVE_POLL 912 913 /** 914 * Set required 'event' members in 'pollfd' elements, 915 * assuming that @a p[0].fd is MHD side of socketpair 916 * and @a p[1].fd is TLS connected socket. 917 * 918 * @param urh upgrade handle to watch for 919 * @param p pollfd array to update 920 */ 921 static void 922 urh_update_pollfd (struct MHD_UpgradeResponseHandle *urh, 923 struct pollfd p[2]) 924 { 925 p[0].events = 0; 926 p[1].events = 0; 927 928 if (urh->in_buffer_used < urh->in_buffer_size) 929 p[0].events |= POLLIN; 930 if (0 != urh->out_buffer_used) 931 p[0].events |= POLLOUT; 932 933 /* Do not monitor again for errors if error was detected before as 934 * error state is remembered. */ 935 if ((0 == (urh->app.celi & MHD_EPOLL_STATE_ERROR)) && 936 ((0 != urh->in_buffer_size) || 937 (0 != urh->out_buffer_size) || 938 (0 != urh->out_buffer_used))) 939 p[0].events |= MHD_POLL_EVENTS_ERR_DISC; 940 941 if (urh->out_buffer_used < urh->out_buffer_size) 942 p[1].events |= POLLIN; 943 if (0 != urh->in_buffer_used) 944 p[1].events |= POLLOUT; 945 946 /* Do not monitor again for errors if error was detected before as 947 * error state is remembered. */ 948 if ((0 == (urh->mhd.celi & MHD_EPOLL_STATE_ERROR)) && 949 ((0 != urh->out_buffer_size) || 950 (0 != urh->in_buffer_size) || 951 (0 != urh->in_buffer_used))) 952 p[1].events |= MHD_POLL_EVENTS_ERR_DISC; 953 } 954 955 956 /** 957 * Set @a p to watch for @a urh. 958 * 959 * @param urh upgrade handle to watch for 960 * @param p pollfd array to set 961 */ 962 static void 963 urh_to_pollfd (struct MHD_UpgradeResponseHandle *urh, 964 struct pollfd p[2]) 965 { 966 p[0].fd = urh->connection->socket_fd; 967 p[1].fd = urh->mhd.socket; 968 urh_update_pollfd (urh, 969 p); 970 } 971 972 973 /** 974 * Update ready state in @a urh based on pollfd. 975 * @param urh upgrade handle to update 976 * @param p 'poll()' processed pollfd. 977 */ 978 static void 979 urh_from_pollfd (struct MHD_UpgradeResponseHandle *urh, 980 struct pollfd p[2]) 981 { 982 /* Reset read/write ready, preserve error state. */ 983 urh->app.celi &= (~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY) 984 & ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY)); 985 urh->mhd.celi &= (~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY) 986 & ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY)); 987 988 if (0 != (p[0].revents & POLLIN)) 989 urh->app.celi |= MHD_EPOLL_STATE_READ_READY; 990 if (0 != (p[0].revents & POLLOUT)) 991 urh->app.celi |= MHD_EPOLL_STATE_WRITE_READY; 992 if (0 != (p[0].revents & POLLHUP)) 993 urh->app.celi |= MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_WRITE_READY; 994 if (0 != (p[0].revents & MHD_POLL_REVENTS_ERRROR)) 995 urh->app.celi |= MHD_EPOLL_STATE_ERROR; 996 if (0 != (p[1].revents & POLLIN)) 997 urh->mhd.celi |= MHD_EPOLL_STATE_READ_READY; 998 if (0 != (p[1].revents & POLLOUT)) 999 urh->mhd.celi |= MHD_EPOLL_STATE_WRITE_READY; 1000 if (0 != (p[1].revents & POLLHUP)) 1001 urh->mhd.celi |= MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_WRITE_READY; 1002 if (0 != (p[1].revents & MHD_POLL_REVENTS_ERRROR)) 1003 urh->mhd.celi |= MHD_EPOLL_STATE_ERROR; 1004 } 1005 1006 1007 #endif /* HAVE_POLL */ 1008 #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ 1009 1010 1011 /** 1012 * Internal version of #MHD_get_fdset2(). 1013 * 1014 * @param daemon daemon to get sets from 1015 * @param read_fd_set read set 1016 * @param write_fd_set write set 1017 * @param except_fd_set except set 1018 * @param max_fd increased to largest FD added (if larger 1019 * than existing value); can be NULL 1020 * @param fd_setsize value of FD_SETSIZE 1021 * @return #MHD_YES on success, #MHD_NO if any FD didn't 1022 * fit fd_set. 1023 * @ingroup event 1024 */ 1025 static enum MHD_Result 1026 internal_get_fdset2 (struct MHD_Daemon *daemon, 1027 fd_set *read_fd_set, 1028 fd_set *write_fd_set, 1029 fd_set *except_fd_set, 1030 MHD_socket *max_fd, 1031 int fd_setsize) 1032 { 1033 struct MHD_Connection *pos; 1034 struct MHD_Connection *posn; 1035 enum MHD_Result result = MHD_YES; 1036 MHD_socket ls; 1037 bool itc_added; 1038 1039 #ifndef HAS_FD_SETSIZE_OVERRIDABLE 1040 (void) fd_setsize; /* Mute compiler warning */ 1041 fd_setsize = (int) FD_SETSIZE; /* Help compiler to optimise */ 1042 #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ 1043 1044 if (daemon->shutdown) 1045 return MHD_YES; 1046 1047 /* The order of FDs added is important for W32 sockets as W32 fd_set has 1048 limits for number of added FDs instead of the limit for the higher 1049 FD value. */ 1050 1051 /* Add ITC FD first. The daemon must be able to respond on application 1052 commands issued in other threads. */ 1053 itc_added = false; 1054 if (MHD_ITC_IS_VALID_ (daemon->itc)) 1055 { 1056 itc_added = MHD_add_to_fd_set_ (MHD_itc_r_fd_ (daemon->itc), 1057 read_fd_set, 1058 max_fd, 1059 fd_setsize); 1060 if (! itc_added) 1061 result = MHD_NO; 1062 } 1063 1064 ls = daemon->was_quiesced ? MHD_INVALID_SOCKET : daemon->listen_fd; 1065 if (! itc_added && 1066 (MHD_INVALID_SOCKET != ls)) 1067 { 1068 /* Add listen FD if ITC was not added. Listen FD could be used to signal 1069 the daemon shutdown. */ 1070 if (MHD_add_to_fd_set_ (ls, 1071 read_fd_set, 1072 max_fd, 1073 fd_setsize)) 1074 ls = MHD_INVALID_SOCKET; /* Already added */ 1075 else 1076 result = MHD_NO; 1077 } 1078 1079 /* Add all sockets to 'except_fd_set' as well to watch for 1080 * out-of-band data. However, ignore errors if INFO_READ 1081 * or INFO_WRITE sockets will not fit 'except_fd_set'. */ 1082 /* Start from oldest connections. Make sense for W32 FDSETs. */ 1083 for (pos = daemon->connections_tail; NULL != pos; pos = posn) 1084 { 1085 posn = pos->prev; 1086 1087 switch (pos->event_loop_info) 1088 { 1089 case MHD_EVENT_LOOP_INFO_READ: 1090 case MHD_EVENT_LOOP_INFO_PROCESS_READ: 1091 if (! MHD_add_to_fd_set_ (pos->socket_fd, 1092 read_fd_set, 1093 max_fd, 1094 fd_setsize)) 1095 result = MHD_NO; 1096 #ifdef MHD_POSIX_SOCKETS 1097 if (NULL != except_fd_set) 1098 (void) MHD_add_to_fd_set_ (pos->socket_fd, 1099 except_fd_set, 1100 max_fd, 1101 fd_setsize); 1102 #endif /* MHD_POSIX_SOCKETS */ 1103 break; 1104 case MHD_EVENT_LOOP_INFO_WRITE: 1105 if (! MHD_add_to_fd_set_ (pos->socket_fd, 1106 write_fd_set, 1107 max_fd, 1108 fd_setsize)) 1109 result = MHD_NO; 1110 #ifdef MHD_POSIX_SOCKETS 1111 if (NULL != except_fd_set) 1112 (void) MHD_add_to_fd_set_ (pos->socket_fd, 1113 except_fd_set, 1114 max_fd, 1115 fd_setsize); 1116 #endif /* MHD_POSIX_SOCKETS */ 1117 break; 1118 case MHD_EVENT_LOOP_INFO_PROCESS: 1119 if ( (NULL == except_fd_set) || 1120 ! MHD_add_to_fd_set_ (pos->socket_fd, 1121 except_fd_set, 1122 max_fd, 1123 fd_setsize)) 1124 result = MHD_NO; 1125 break; 1126 case MHD_EVENT_LOOP_INFO_CLEANUP: 1127 /* this should never happen */ 1128 break; 1129 } 1130 } 1131 #ifdef MHD_WINSOCK_SOCKETS 1132 /* W32 use limited array for fd_set so add INFO_READ/INFO_WRITE sockets 1133 * only after INFO_BLOCK sockets to ensure that INFO_BLOCK sockets will 1134 * not be pushed out. */ 1135 if (NULL != except_fd_set) 1136 { 1137 for (pos = daemon->connections_tail; NULL != pos; pos = posn) 1138 { 1139 posn = pos->prev; 1140 MHD_add_to_fd_set_ (pos->socket_fd, 1141 except_fd_set, 1142 max_fd, 1143 fd_setsize); 1144 } 1145 } 1146 #endif /* MHD_WINSOCK_SOCKETS */ 1147 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) 1148 if (1) 1149 { 1150 struct MHD_UpgradeResponseHandle *urh; 1151 1152 for (urh = daemon->urh_tail; NULL != urh; urh = urh->prev) 1153 { 1154 if (MHD_NO == 1155 urh_to_fdset (urh, 1156 read_fd_set, 1157 write_fd_set, 1158 except_fd_set, 1159 max_fd, 1160 fd_setsize)) 1161 result = MHD_NO; 1162 } 1163 } 1164 #endif 1165 1166 if (MHD_INVALID_SOCKET != ls) 1167 { 1168 /* The listen socket is present and hasn't been added */ 1169 if ((daemon->connections < daemon->connection_limit) && 1170 ! daemon->at_limit) 1171 { 1172 if (! MHD_add_to_fd_set_ (ls, 1173 read_fd_set, 1174 max_fd, 1175 fd_setsize)) 1176 result = MHD_NO; 1177 } 1178 } 1179 1180 #if _MHD_DEBUG_CONNECT 1181 #ifdef HAVE_MESSAGES 1182 if (NULL != max_fd) 1183 MHD_DLOG (daemon, 1184 _ ("Maximum socket in select set: %d\n"), 1185 *max_fd); 1186 #endif 1187 #endif 1188 return result; 1189 } 1190 1191 1192 /** 1193 * Obtain the `select()` sets for this daemon. 1194 * Daemon's FDs will be added to fd_sets. To get only 1195 * daemon FDs in fd_sets, call FD_ZERO for each fd_set 1196 * before calling this function. 1197 * 1198 * Passing custom FD_SETSIZE as @a fd_setsize allow usage of 1199 * larger/smaller than platform's default fd_sets. 1200 * 1201 * This function should be called only when MHD is configured to 1202 * use "external" sockets polling with 'select()' or with 'epoll'. 1203 * In the latter case, it will only add the single 'epoll' file 1204 * descriptor used by MHD to the sets. 1205 * It's necessary to use #MHD_get_timeout() to get maximum timeout 1206 * value for `select()`. Usage of `select()` with indefinite timeout 1207 * (or timeout larger than returned by #MHD_get_timeout()) will 1208 * violate MHD API and may results in pending unprocessed data. 1209 * 1210 * This function must be called only for daemon started 1211 * without #MHD_USE_INTERNAL_POLLING_THREAD flag. 1212 * 1213 * @param daemon daemon to get sets from 1214 * @param read_fd_set read set 1215 * @param write_fd_set write set 1216 * @param except_fd_set except set 1217 * @param max_fd increased to largest FD added (if larger 1218 * than existing value); can be NULL 1219 * @param fd_setsize value of FD_SETSIZE 1220 * @return #MHD_YES on success, #MHD_NO if this 1221 * daemon was not started with the right 1222 * options for this call or any FD didn't 1223 * fit fd_set. 1224 * @ingroup event 1225 */ 1226 _MHD_EXTERN enum MHD_Result 1227 MHD_get_fdset2 (struct MHD_Daemon *daemon, 1228 fd_set *read_fd_set, 1229 fd_set *write_fd_set, 1230 fd_set *except_fd_set, 1231 MHD_socket *max_fd, 1232 unsigned int fd_setsize) 1233 { 1234 if ( (NULL == daemon) || 1235 (NULL == read_fd_set) || 1236 (NULL == write_fd_set) || 1237 MHD_D_IS_USING_THREADS_ (daemon) || 1238 MHD_D_IS_USING_POLL_ (daemon)) 1239 return MHD_NO; 1240 1241 #ifdef HAVE_MESSAGES 1242 if (NULL == except_fd_set) 1243 { 1244 MHD_DLOG (daemon, 1245 _ ("MHD_get_fdset2() called with except_fd_set " 1246 "set to NULL. Such behavior is unsupported.\n")); 1247 } 1248 #endif 1249 1250 #ifdef HAS_FD_SETSIZE_OVERRIDABLE 1251 if (0 == fd_setsize) 1252 return MHD_NO; 1253 else if (((unsigned int) INT_MAX) < fd_setsize) 1254 fd_setsize = (unsigned int) INT_MAX; 1255 #ifdef HAVE_MESSAGES 1256 else if (daemon->fdset_size > ((int) fd_setsize)) 1257 { 1258 if (daemon->fdset_size_set_by_app) 1259 { 1260 MHD_DLOG (daemon, 1261 _ ("%s() called with fd_setsize (%u) " \ 1262 "less than value set by MHD_OPTION_APP_FD_SETSIZE (%d). " \ 1263 "Some socket FDs may be not processed. " \ 1264 "Use MHD_OPTION_APP_FD_SETSIZE with the correct value.\n"), 1265 "MHD_get_fdset2", fd_setsize, daemon->fdset_size); 1266 } 1267 else 1268 { 1269 MHD_DLOG (daemon, 1270 _ ("%s() called with fd_setsize (%u) " \ 1271 "less than FD_SETSIZE used by MHD (%d). " \ 1272 "Some socket FDs may be not processed. " \ 1273 "Consider using MHD_OPTION_APP_FD_SETSIZE option.\n"), 1274 "MHD_get_fdset2", fd_setsize, daemon->fdset_size); 1275 } 1276 } 1277 #endif /* HAVE_MESSAGES */ 1278 #else /* ! HAS_FD_SETSIZE_OVERRIDABLE */ 1279 if (((unsigned int) FD_SETSIZE) > fd_setsize) 1280 { 1281 #ifdef HAVE_MESSAGES 1282 MHD_DLOG (daemon, 1283 _ ("%s() called with fd_setsize (%u) " \ 1284 "less than fixed FD_SETSIZE value (%d) used on the " \ 1285 "platform.\n"), 1286 "MHD_get_fdset2", fd_setsize, (int) FD_SETSIZE); 1287 #endif /* HAVE_MESSAGES */ 1288 return MHD_NO; 1289 } 1290 fd_setsize = (int) FD_SETSIZE; /* Help compiler to optimise */ 1291 #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ 1292 1293 #ifdef EPOLL_SUPPORT 1294 if (MHD_D_IS_USING_EPOLL_ (daemon)) 1295 { 1296 if (daemon->shutdown) 1297 return MHD_YES; 1298 1299 /* we're in epoll mode, use the epoll FD as a stand-in for 1300 the entire event set */ 1301 1302 return MHD_add_to_fd_set_ (daemon->epoll_fd, 1303 read_fd_set, 1304 max_fd, 1305 (int) fd_setsize) ? MHD_YES : MHD_NO; 1306 } 1307 #endif 1308 1309 return internal_get_fdset2 (daemon, 1310 read_fd_set, 1311 write_fd_set, 1312 except_fd_set, 1313 max_fd, 1314 (int) fd_setsize); 1315 } 1316 1317 1318 /** 1319 * Call the handlers for a connection in the appropriate order based 1320 * on the readiness as detected by the event loop. 1321 * 1322 * @param con connection to handle 1323 * @param read_ready set if the socket is ready for reading 1324 * @param write_ready set if the socket is ready for writing 1325 * @param force_close set if a hard error was detected on the socket; 1326 * if this information is not available, simply pass #MHD_NO 1327 * @return #MHD_YES to continue normally, 1328 * #MHD_NO if a serious error was encountered and the 1329 * connection is to be closed. 1330 */ 1331 static enum MHD_Result 1332 call_handlers (struct MHD_Connection *con, 1333 bool read_ready, 1334 bool write_ready, 1335 bool force_close) 1336 { 1337 enum MHD_Result ret; 1338 bool states_info_processed = false; 1339 /* Fast track flag */ 1340 bool on_fasttrack = (con->state == MHD_CONNECTION_INIT); 1341 ret = MHD_YES; 1342 1343 mhd_assert ((0 == (con->daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ 1344 (MHD_thread_handle_ID_is_valid_ID_ (con->tid))); 1345 mhd_assert ((0 != (con->daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ 1346 (! MHD_thread_handle_ID_is_valid_ID_ (con->tid))); 1347 mhd_assert ((0 == (con->daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ 1348 (MHD_thread_handle_ID_is_current_thread_ (con->tid))); 1349 1350 #ifdef HTTPS_SUPPORT 1351 if (con->tls_read_ready) 1352 read_ready = true; 1353 #endif /* HTTPS_SUPPORT */ 1354 if (con->resumed) 1355 { 1356 /* The connection was resumed since its states were last updated, 1357 so 'con->event_loop_info' still describes the state the 1358 connection was in before it was suspended -- see the field's 1359 description. Dispatching on it would, for instance, call 1360 MHD_connection_handle_write() on a connection whose content 1361 reader has just reported that it has no data yet, which is not a 1362 state the write handler has an action for. */ 1363 con->resumed = false; 1364 ret = MHD_connection_handle_idle (con); 1365 if (MHD_NO == ret) 1366 return ret; /* Connection died and was cleaned up. */ 1367 states_info_processed = true; 1368 } 1369 if ( (0 != (MHD_EVENT_LOOP_INFO_READ & con->event_loop_info)) && 1370 (read_ready || (force_close && con->sk_nonblck)) ) 1371 { 1372 MHD_connection_handle_read (con, force_close); 1373 /* MHD_connection_handle_read() closes the connection when 1374 @a force_close is set, but only once it gets far enough to try. 1375 It returns early, leaving 'con->state' untouched, in three cases, 1376 and all three are reachable from here: 1377 - the connection is suspended, 1378 - a TLS handshake is still in progress, 1379 - the read buffer has no free space at all. */ 1380 #ifdef HTTPS_SUPPORT 1381 mhd_assert ((! force_close) || \ 1382 (MHD_CONNECTION_CLOSED == con->state) || \ 1383 (con->suspended) || \ 1384 ( (MHD_TLS_CONN_NO_TLS != con->tls_state) && \ 1385 (MHD_TLS_CONN_CONNECTED > con->tls_state) ) || \ 1386 (con->read_buffer_size == con->read_buffer_offset)); 1387 #else /* ! HTTPS_SUPPORT */ 1388 mhd_assert ((! force_close) || \ 1389 (MHD_CONNECTION_CLOSED == con->state) || \ 1390 (con->suspended) || \ 1391 (con->read_buffer_size == con->read_buffer_offset)); 1392 #endif /* ! HTTPS_SUPPORT */ 1393 ret = MHD_connection_handle_idle (con); 1394 if (force_close) 1395 return ret; 1396 states_info_processed = true; 1397 } 1398 if (! force_close) 1399 { 1400 /* No need to check value of 'ret' here as closed connection 1401 * cannot be in MHD_EVENT_LOOP_INFO_WRITE state. */ 1402 if ( (MHD_EVENT_LOOP_INFO_WRITE == con->event_loop_info) && 1403 write_ready) 1404 { 1405 MHD_connection_handle_write (con); 1406 ret = MHD_connection_handle_idle (con); 1407 states_info_processed = true; 1408 } 1409 } 1410 else 1411 { 1412 MHD_connection_close_ (con, 1413 MHD_REQUEST_TERMINATED_WITH_ERROR); 1414 return MHD_connection_handle_idle (con); 1415 } 1416 1417 if (! states_info_processed) 1418 { /* Connection is not read or write ready, but external conditions 1419 * may be changed and need to be processed. */ 1420 ret = MHD_connection_handle_idle (con); 1421 } 1422 /* Fast track for fast connections. */ 1423 /* If full request was read by single read_handler() invocation 1424 and headers were completely prepared by single MHD_connection_handle_idle() 1425 then try not to wait for next sockets polling and send response 1426 immediately. 1427 As writeability of socket was not checked and it may have 1428 some data pending in system buffers, use this optimization 1429 only for non-blocking sockets. */ 1430 /* No need to check 'ret' as connection is always in 1431 * MHD_CONNECTION_CLOSED state if 'ret' is equal 'MHD_NO'. */ 1432 else if (on_fasttrack && con->sk_nonblck) 1433 { 1434 if (MHD_CONNECTION_HEADERS_SENDING == con->state) 1435 { 1436 MHD_connection_handle_write (con); 1437 /* Always call 'MHD_connection_handle_idle()' after each read/write. */ 1438 ret = MHD_connection_handle_idle (con); 1439 } 1440 /* If all headers were sent by single write_handler() and 1441 * response body is prepared by single MHD_connection_handle_idle() 1442 * call - continue. */ 1443 if ((MHD_CONNECTION_NORMAL_BODY_READY == con->state) || 1444 (MHD_CONNECTION_CHUNKED_BODY_READY == con->state)) 1445 { 1446 MHD_connection_handle_write (con); 1447 ret = MHD_connection_handle_idle (con); 1448 } 1449 } 1450 1451 /* All connection's data and states are processed for this turn. 1452 * If connection already has more data to be processed - use 1453 * zero timeout for next select()/poll(). */ 1454 /* Thread-per-connection do not need global zero timeout as 1455 * connections are processed individually. */ 1456 /* Note: no need to check for read buffer availability for 1457 * TLS read-ready connection in 'read info' state as connection 1458 * without space in read buffer will be marked as 'info block'. */ 1459 if ( (! con->daemon->data_already_pending) && 1460 (! MHD_D_IS_USING_THREAD_PER_CONN_ (con->daemon)) ) 1461 { 1462 if (0 != (MHD_EVENT_LOOP_INFO_PROCESS & con->event_loop_info)) 1463 con->daemon->data_already_pending = true; 1464 #ifdef HTTPS_SUPPORT 1465 else if ( (con->tls_read_ready) && 1466 (0 != (MHD_EVENT_LOOP_INFO_READ & con->event_loop_info)) ) 1467 con->daemon->data_already_pending = true; 1468 #endif /* HTTPS_SUPPORT */ 1469 } 1470 return ret; 1471 } 1472 1473 1474 #ifdef UPGRADE_SUPPORT 1475 /** 1476 * Finally cleanup upgrade-related resources. It should 1477 * be called when TLS buffers have been drained and 1478 * application signaled MHD by #MHD_UPGRADE_ACTION_CLOSE. 1479 * 1480 * @param connection handle to the upgraded connection to clean 1481 */ 1482 static void 1483 cleanup_upgraded_connection (struct MHD_Connection *connection) 1484 { 1485 struct MHD_UpgradeResponseHandle *urh = connection->urh; 1486 1487 if (NULL == urh) 1488 return; 1489 #ifdef HTTPS_SUPPORT 1490 /* Signal remote client the end of TLS connection by 1491 * gracefully closing TLS session. */ 1492 if (0 != (connection->daemon->options & MHD_USE_TLS)) 1493 gnutls_bye (connection->tls_session, 1494 GNUTLS_SHUT_WR); 1495 1496 if (MHD_INVALID_SOCKET != urh->mhd.socket) 1497 MHD_socket_close_chk_ (urh->mhd.socket); 1498 1499 if (MHD_INVALID_SOCKET != urh->app.socket) 1500 MHD_socket_close_chk_ (urh->app.socket); 1501 #endif /* HTTPS_SUPPORT */ 1502 connection->urh = NULL; 1503 free (urh); 1504 } 1505 1506 1507 #endif /* UPGRADE_SUPPORT */ 1508 1509 1510 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) 1511 /** 1512 * Performs bi-directional forwarding on upgraded HTTPS connections 1513 * based on the readiness state stored in the @a urh handle. 1514 * @remark To be called only from thread that processes 1515 * connection's recv(), send() and response. 1516 * 1517 * @param urh handle to process 1518 */ 1519 static void 1520 process_urh (struct MHD_UpgradeResponseHandle *urh) 1521 { 1522 /* Help compiler to optimize: 1523 * pointers to 'connection' and 'daemon' are not changed 1524 * during this processing, so no need to chain dereference 1525 * each time. */ 1526 struct MHD_Connection *const connection = urh->connection; 1527 struct MHD_Daemon *const daemon = connection->daemon; 1528 /* Prevent data races: use same value of 'was_closed' throughout 1529 * this function. If 'was_closed' changed externally in the middle 1530 * of processing - it will be processed on next iteration. */ 1531 bool was_closed; 1532 1533 #ifdef MHD_USE_THREADS 1534 mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ 1535 MHD_thread_handle_ID_is_current_thread_ (connection->tid) ); 1536 #endif /* MHD_USE_THREADS */ 1537 1538 mhd_assert (0 != (daemon->options & MHD_USE_TLS)); 1539 1540 if (daemon->shutdown) 1541 { 1542 /* Daemon shutting down, application will not receive any more data. */ 1543 #ifdef HAVE_MESSAGES 1544 if (! urh->was_closed) 1545 { 1546 MHD_DLOG (daemon, 1547 _ ("Initiated daemon shutdown while \"upgraded\" " \ 1548 "connection was not closed.\n")); 1549 } 1550 #endif 1551 urh->was_closed = true; 1552 } 1553 was_closed = urh->was_closed; 1554 if (was_closed) 1555 { 1556 /* Application was closed connections: no more data 1557 * can be forwarded to application socket. */ 1558 if (0 < urh->in_buffer_used) 1559 { 1560 #ifdef HAVE_MESSAGES 1561 MHD_DLOG (daemon, 1562 _ ("Failed to forward to application %" PRIu64 \ 1563 " bytes of data received from remote side: " \ 1564 "application closed data forwarding.\n"), 1565 (uint64_t) urh->in_buffer_used); 1566 #endif 1567 1568 } 1569 /* Discard any data received form remote. */ 1570 urh->in_buffer_used = 0; 1571 /* Do not try to push data to application. */ 1572 urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); 1573 /* Reading from remote client is not required anymore. */ 1574 urh->in_buffer_size = 0; 1575 urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); 1576 connection->tls_read_ready = false; 1577 } 1578 1579 /* On some platforms (W32, possibly Darwin) failed send() (send() will 1580 * always fail after remote disconnect was detected) may discard data in 1581 * system buffers received by system but not yet read by recv(). So, before 1582 * trying send() on any socket, recv() must be performed at first otherwise 1583 * last part of incoming data may be lost. If disconnect or error was 1584 * detected - try to read from socket to dry data possibly pending is system 1585 * buffers. */ 1586 1587 /* 1588 * handle reading from remote TLS client 1589 */ 1590 if (((0 != ((MHD_EPOLL_STATE_ERROR | MHD_EPOLL_STATE_READ_READY) 1591 & urh->app.celi)) || 1592 (connection->tls_read_ready)) && 1593 (urh->in_buffer_used < urh->in_buffer_size)) 1594 { 1595 ssize_t res; 1596 size_t buf_size; 1597 1598 buf_size = urh->in_buffer_size - urh->in_buffer_used; 1599 if (buf_size > SSIZE_MAX) 1600 buf_size = SSIZE_MAX; 1601 1602 res = gnutls_record_recv (connection->tls_session, 1603 &urh->in_buffer[urh->in_buffer_used], 1604 buf_size); 1605 if (0 >= res) 1606 { 1607 connection->tls_read_ready = false; 1608 if (GNUTLS_E_INTERRUPTED != res) 1609 { 1610 urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); 1611 if ((GNUTLS_E_AGAIN != res) || 1612 (0 != (MHD_EPOLL_STATE_ERROR & urh->app.celi))) 1613 { 1614 /* TLS unrecoverable error has been detected, 1615 socket error was detected and all data has been read, 1616 or socket was disconnected/shut down. */ 1617 /* Stop trying to read from this TLS socket. */ 1618 urh->in_buffer_size = 0; 1619 } 1620 } 1621 } 1622 else /* 0 < res */ 1623 { 1624 urh->in_buffer_used += (size_t) res; 1625 connection->tls_read_ready = 1626 (0 < gnutls_record_check_pending (connection->tls_session)); 1627 } 1628 } 1629 1630 /* 1631 * handle reading from application 1632 */ 1633 /* If application signalled MHD about socket closure then 1634 * check for any pending data even if socket is not marked 1635 * as 'ready' (signal may arrive after poll()/select()). 1636 * Socketpair for forwarding is always in non-blocking mode 1637 * so no risk that recv() will block the thread. */ 1638 if (((0 != ((MHD_EPOLL_STATE_ERROR | MHD_EPOLL_STATE_READ_READY) 1639 & urh->mhd.celi)) 1640 || was_closed) /* Force last reading from app if app has closed the connection */ 1641 && (urh->out_buffer_used < urh->out_buffer_size)) 1642 { 1643 ssize_t res; 1644 size_t buf_size; 1645 1646 buf_size = urh->out_buffer_size - urh->out_buffer_used; 1647 if (buf_size > MHD_SCKT_SEND_MAX_SIZE_) 1648 buf_size = MHD_SCKT_SEND_MAX_SIZE_; 1649 1650 res = MHD_recv_ (urh->mhd.socket, 1651 &urh->out_buffer[urh->out_buffer_used], 1652 buf_size); 1653 if (0 >= res) 1654 { 1655 const int err = MHD_socket_get_error_ (); 1656 if ((0 == res) || 1657 ((! MHD_SCKT_ERR_IS_EINTR_ (err)) && 1658 (! MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err)))) 1659 { 1660 urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); 1661 if ((0 == res) || 1662 (was_closed) || 1663 (0 != (MHD_EPOLL_STATE_ERROR & urh->mhd.celi)) || 1664 (! MHD_SCKT_ERR_IS_EAGAIN_ (err))) 1665 { 1666 /* Socket disconnect/shutdown was detected; 1667 * Application signalled about closure of 'upgraded' socket and 1668 * all data has been read from application; 1669 * or persistent / unrecoverable error. */ 1670 /* Do not try to pull more data from application. */ 1671 urh->out_buffer_size = 0; 1672 } 1673 } 1674 } 1675 else /* 0 < res */ 1676 { 1677 urh->out_buffer_used += (size_t) res; 1678 if (buf_size > (size_t) res) 1679 urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); 1680 } 1681 } 1682 1683 /* 1684 * handle writing to remote HTTPS client 1685 */ 1686 if ( (0 != (MHD_EPOLL_STATE_WRITE_READY & urh->app.celi)) && 1687 (urh->out_buffer_used > 0) ) 1688 { 1689 ssize_t res; 1690 size_t data_size; 1691 1692 data_size = urh->out_buffer_used; 1693 if (data_size > SSIZE_MAX) 1694 data_size = SSIZE_MAX; 1695 1696 res = gnutls_record_send (connection->tls_session, 1697 urh->out_buffer, 1698 data_size); 1699 if (0 >= res) 1700 { 1701 if (GNUTLS_E_INTERRUPTED != res) 1702 { 1703 urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); 1704 if (GNUTLS_E_AGAIN != res) 1705 { 1706 /* TLS connection shut down or 1707 * persistent / unrecoverable error. */ 1708 #ifdef HAVE_MESSAGES 1709 MHD_DLOG (daemon, 1710 _ ("Failed to forward to remote client %" PRIu64 \ 1711 " bytes of data received from application: %s\n"), 1712 (uint64_t) urh->out_buffer_used, 1713 gnutls_strerror ((int) res)); 1714 #endif 1715 /* Discard any data unsent to remote. */ 1716 urh->out_buffer_used = 0; 1717 /* Do not try to pull more data from application. */ 1718 urh->out_buffer_size = 0; 1719 urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); 1720 } 1721 } 1722 } 1723 else /* 0 < res */ 1724 { 1725 const size_t next_out_buffer_used = urh->out_buffer_used - (size_t) res; 1726 if (0 != next_out_buffer_used) 1727 { 1728 memmove (urh->out_buffer, 1729 &urh->out_buffer[res], 1730 next_out_buffer_used); 1731 } 1732 urh->out_buffer_used = next_out_buffer_used; 1733 } 1734 if ( (0 == urh->out_buffer_used) && 1735 (0 != (MHD_EPOLL_STATE_ERROR & urh->app.celi)) ) 1736 { 1737 /* Unrecoverable error on socket was detected and all 1738 * pending data was sent to remote. */ 1739 /* Do not try to send to remote anymore. */ 1740 urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); 1741 /* Do not try to pull more data from application. */ 1742 urh->out_buffer_size = 0; 1743 urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); 1744 } 1745 } 1746 1747 /* 1748 * handle writing to application 1749 */ 1750 if ( (0 != (MHD_EPOLL_STATE_WRITE_READY & urh->mhd.celi)) && 1751 (urh->in_buffer_used > 0) ) 1752 { 1753 ssize_t res; 1754 size_t data_size; 1755 1756 data_size = urh->in_buffer_used; 1757 if (data_size > MHD_SCKT_SEND_MAX_SIZE_) 1758 data_size = MHD_SCKT_SEND_MAX_SIZE_; 1759 1760 res = MHD_send_ (urh->mhd.socket, 1761 urh->in_buffer, 1762 data_size); 1763 if (0 >= res) 1764 { 1765 const int err = MHD_socket_get_error_ (); 1766 if ( (! MHD_SCKT_ERR_IS_EINTR_ (err)) && 1767 (! MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err)) ) 1768 { 1769 urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); 1770 if (! MHD_SCKT_ERR_IS_EAGAIN_ (err)) 1771 { 1772 /* Socketpair connection shut down or 1773 * persistent / unrecoverable error. */ 1774 #ifdef HAVE_MESSAGES 1775 MHD_DLOG (daemon, 1776 _ ("Failed to forward to application %" PRIu64 \ 1777 " bytes of data received from remote side: %s\n"), 1778 (uint64_t) urh->in_buffer_used, 1779 MHD_socket_strerr_ (err)); 1780 #endif 1781 /* Discard any data received from remote. */ 1782 urh->in_buffer_used = 0; 1783 /* Reading from remote client is not required anymore. */ 1784 urh->in_buffer_size = 0; 1785 urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); 1786 connection->tls_read_ready = false; 1787 } 1788 } 1789 } 1790 else /* 0 < res */ 1791 { 1792 const size_t next_in_buffer_used = urh->in_buffer_used - (size_t) res; 1793 if (0 != next_in_buffer_used) 1794 { 1795 memmove (urh->in_buffer, 1796 &urh->in_buffer[res], 1797 next_in_buffer_used); 1798 if (data_size > (size_t) res) 1799 urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); 1800 } 1801 urh->in_buffer_used = next_in_buffer_used; 1802 } 1803 if ( (0 == urh->in_buffer_used) && 1804 (0 != (MHD_EPOLL_STATE_ERROR & urh->mhd.celi)) ) 1805 { 1806 /* Do not try to push data to application. */ 1807 urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); 1808 /* Reading from remote client is not required anymore. */ 1809 urh->in_buffer_size = 0; 1810 urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); 1811 connection->tls_read_ready = false; 1812 } 1813 } 1814 1815 /* Check whether data is present in TLS buffers 1816 * and incoming forward buffer have some space. */ 1817 if ( (connection->tls_read_ready) && 1818 (urh->in_buffer_used < urh->in_buffer_size) && 1819 (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) ) 1820 daemon->data_already_pending = true; 1821 1822 if ( (daemon->shutdown) && 1823 ( (0 != urh->out_buffer_size) || 1824 (0 != urh->out_buffer_used) ) ) 1825 { 1826 /* Daemon shutting down, discard any remaining forward data. */ 1827 #ifdef HAVE_MESSAGES 1828 if (0 < urh->out_buffer_used) 1829 MHD_DLOG (daemon, 1830 _ ("Failed to forward to remote client %" PRIu64 \ 1831 " bytes of data received from application: daemon shut down.\n"), 1832 (uint64_t) urh->out_buffer_used); 1833 #endif 1834 /* Discard any data unsent to remote. */ 1835 urh->out_buffer_used = 0; 1836 /* Do not try to sent to remote anymore. */ 1837 urh->app.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_WRITE_READY); 1838 /* Do not try to pull more data from application. */ 1839 urh->out_buffer_size = 0; 1840 urh->mhd.celi &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_READY); 1841 } 1842 1843 if (! was_closed && urh->was_closed) 1844 daemon->data_already_pending = true; /* Force processing again */ 1845 } 1846 1847 1848 #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ 1849 1850 1851 /** 1852 * Get maximum wait period for the connection (the amount of time left before 1853 * connection time out) 1854 * @param c the connection to check 1855 * @return the maximum number of millisecond before the connection must be 1856 * processed again. 1857 */ 1858 static uint64_t 1859 connection_get_wait (struct MHD_Connection *c) 1860 { 1861 const uint64_t now = MHD_monotonic_msec_counter (); 1862 const uint64_t since_actv = now - c->last_activity; 1863 const uint64_t timeout = c->connection_timeout_ms; 1864 uint64_t mseconds_left; 1865 1866 mhd_assert (0 != timeout); 1867 /* Keep the next lines in sync with #connection_check_timedout() to avoid 1868 * undesired side-effects like busy-waiting. */ 1869 if (timeout < since_actv) 1870 { 1871 if (UINT64_MAX / 2 < since_actv) 1872 { 1873 const uint64_t jump_back = c->last_activity - now; 1874 /* Very unlikely that it is more than quarter-million years pause. 1875 * More likely that system clock jumps back. */ 1876 if (5000 >= jump_back) 1877 { /* Jump back is less than 5 seconds, try to recover. */ 1878 return 100; /* Set wait time to 0.1 seconds */ 1879 } 1880 /* Too large jump back */ 1881 } 1882 return 0; /* Connection has timed out */ 1883 } 1884 else if (since_actv == timeout) 1885 { 1886 /* Exact match for timeout and time from last activity. 1887 * Maybe this is just a precise match or this happens because the timer 1888 * resolution is too low. 1889 * Set wait time to 0.1 seconds to avoid busy-waiting with low 1890 * timer resolution as connection is not timed-out yet. */ 1891 return 100; 1892 } 1893 mseconds_left = timeout - since_actv; 1894 1895 return mseconds_left; 1896 } 1897 1898 1899 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 1900 #ifdef UPGRADE_SUPPORT 1901 /** 1902 * Main function of the thread that handles an individual connection 1903 * after it was "upgraded" when #MHD_USE_THREAD_PER_CONNECTION is set. 1904 * @remark To be called only from thread that process 1905 * connection's recv(), send() and response. 1906 * 1907 * @param con the connection this thread will handle 1908 */ 1909 static void 1910 thread_main_connection_upgrade (struct MHD_Connection *con) 1911 { 1912 #ifdef HTTPS_SUPPORT 1913 struct MHD_UpgradeResponseHandle *urh = con->urh; 1914 struct MHD_Daemon *daemon = con->daemon; 1915 1916 mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ 1917 MHD_thread_handle_ID_is_current_thread_ (con->tid) ); 1918 /* Here, we need to bi-directionally forward 1919 until the application tells us that it is done 1920 with the socket; */ 1921 if ( (0 != (daemon->options & MHD_USE_TLS)) && 1922 MHD_D_IS_USING_SELECT_ (daemon)) 1923 { 1924 while ( (0 != urh->in_buffer_size) || 1925 (0 != urh->out_buffer_size) || 1926 (0 != urh->in_buffer_used) || 1927 (0 != urh->out_buffer_used) ) 1928 { 1929 /* use select */ 1930 fd_set rs; 1931 fd_set ws; 1932 fd_set es; 1933 MHD_socket max_fd; 1934 int num_ready; 1935 bool result; 1936 1937 FD_ZERO (&rs); 1938 FD_ZERO (&ws); 1939 FD_ZERO (&es); 1940 max_fd = MHD_INVALID_SOCKET; 1941 result = urh_to_fdset (urh, 1942 &rs, 1943 &ws, 1944 &es, 1945 &max_fd, 1946 FD_SETSIZE); 1947 if (! result) 1948 { 1949 #ifdef HAVE_MESSAGES 1950 MHD_DLOG (con->daemon, 1951 _ ("Error preparing select.\n")); 1952 #endif 1953 break; 1954 } 1955 /* FIXME: does this check really needed? */ 1956 if (MHD_INVALID_SOCKET != max_fd) 1957 { 1958 struct timeval *tvp; 1959 struct timeval tv; 1960 if (((con->tls_read_ready) && 1961 (urh->in_buffer_used < urh->in_buffer_size)) || 1962 (daemon->shutdown)) 1963 { /* No need to wait if incoming data is already pending in TLS buffers. */ 1964 tv.tv_sec = 0; 1965 tv.tv_usec = 0; 1966 tvp = &tv; 1967 } 1968 else 1969 tvp = NULL; 1970 num_ready = MHD_SYS_select_ (max_fd + 1, 1971 &rs, 1972 &ws, 1973 &es, 1974 tvp); 1975 } 1976 else 1977 num_ready = 0; 1978 if (num_ready < 0) 1979 { 1980 const int err = MHD_socket_get_error_ (); 1981 1982 if (MHD_SCKT_ERR_IS_EINTR_ (err)) 1983 continue; 1984 #ifdef HAVE_MESSAGES 1985 MHD_DLOG (con->daemon, 1986 _ ("Error during select (%d): `%s'\n"), 1987 err, 1988 MHD_socket_strerr_ (err)); 1989 #endif 1990 break; 1991 } 1992 urh_from_fdset (urh, 1993 &rs, 1994 &ws, 1995 &es, 1996 (int) FD_SETSIZE); 1997 process_urh (urh); 1998 } 1999 } 2000 #ifdef HAVE_POLL 2001 else if (0 != (daemon->options & MHD_USE_TLS)) 2002 { 2003 /* use poll() */ 2004 struct pollfd p[2]; 2005 memset (p, 2006 0, 2007 sizeof (p)); 2008 p[0].fd = urh->connection->socket_fd; 2009 p[1].fd = urh->mhd.socket; 2010 2011 while ( (0 != urh->in_buffer_size) || 2012 (0 != urh->out_buffer_size) || 2013 (0 != urh->in_buffer_used) || 2014 (0 != urh->out_buffer_used) ) 2015 { 2016 int timeout; 2017 2018 urh_update_pollfd (urh, p); 2019 2020 if (((con->tls_read_ready) && 2021 (urh->in_buffer_used < urh->in_buffer_size)) || 2022 (daemon->shutdown)) 2023 timeout = 0; /* No need to wait if incoming data is already pending in TLS buffers. */ 2024 else 2025 timeout = -1; 2026 2027 if (MHD_sys_poll_ (p, 2028 2, 2029 timeout) < 0) 2030 { 2031 const int err = MHD_socket_get_error_ (); 2032 2033 if (MHD_SCKT_ERR_IS_EINTR_ (err)) 2034 continue; 2035 #ifdef HAVE_MESSAGES 2036 MHD_DLOG (con->daemon, 2037 _ ("Error during poll: `%s'\n"), 2038 MHD_socket_strerr_ (err)); 2039 #endif 2040 break; 2041 } 2042 urh_from_pollfd (urh, 2043 p); 2044 process_urh (urh); 2045 } 2046 } 2047 /* end POLL */ 2048 #endif 2049 /* end HTTPS */ 2050 #endif /* HTTPS_SUPPORT */ 2051 /* TLS forwarding was finished. Cleanup socketpair. */ 2052 MHD_connection_finish_forward_ (con); 2053 /* Do not set 'urh->clean_ready' yet as 'urh' will be used 2054 * in connection thread for a little while. */ 2055 } 2056 2057 2058 #endif /* UPGRADE_SUPPORT */ 2059 2060 2061 /** 2062 * Complete the resume of a connection that has its own thread. 2063 * 2064 * This is the thread-per-connection counterpart of 2065 * resume_suspended_connections(): the connection's own thread does the 2066 * bookkeeping for itself instead of waiting for the daemon's thread to 2067 * do it. That is what makes the wake-up reliable -- the notification 2068 * is sent to the connection's own ITC and is acted upon by the only 2069 * thread that reads it, so it can neither be consumed by the daemon's 2070 * thread nor be missed between the check of @e resuming and the wait. 2071 * 2072 * @param connection the suspended connection that is to be resumed, 2073 * must have @e resuming set 2074 */ 2075 static void 2076 resume_connection_own_thread_ (struct MHD_Connection *connection) 2077 { 2078 struct MHD_Daemon *const daemon = connection->daemon; 2079 2080 mhd_assert (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)); 2081 mhd_assert (! MHD_D_IS_USING_EPOLL_ (daemon)); 2082 #ifdef UPGRADE_SUPPORT 2083 mhd_assert (NULL == connection->urh); 2084 #endif /* UPGRADE_SUPPORT */ 2085 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 2086 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); 2087 #endif 2088 mhd_assert (connection->suspended); 2089 mhd_assert (connection->resuming); 2090 DLL_remove (daemon->suspended_connections_head, 2091 daemon->suspended_connections_tail, 2092 connection); 2093 connection->suspended = false; 2094 DLL_insert (daemon->connections_head, 2095 daemon->connections_tail, 2096 connection); 2097 connection->resuming = false; 2098 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 2099 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); 2100 #endif 2101 /* Drop the notification that led here, as well as any notification 2102 left over from a resume that was undone by a suspend before this 2103 thread got to see it. */ 2104 MHD_itc_clear_ (connection->resume_itc); 2105 } 2106 2107 2108 /** 2109 * Main function of the thread that handles an individual 2110 * connection when #MHD_USE_THREAD_PER_CONNECTION is set. 2111 * 2112 * @param data the `struct MHD_Connection` this thread will handle 2113 * @return always 0 2114 */ 2115 static MHD_THRD_RTRN_TYPE_ MHD_THRD_CALL_SPEC_ 2116 thread_main_handle_connection (void *data) 2117 { 2118 struct MHD_Connection *con = data; 2119 struct MHD_Daemon *daemon = con->daemon; 2120 int num_ready; 2121 fd_set rs; 2122 fd_set ws; 2123 fd_set es; 2124 MHD_socket maxsock; 2125 #ifdef WINDOWS 2126 #ifdef HAVE_POLL 2127 unsigned int extra_slot; 2128 #endif /* HAVE_POLL */ 2129 #define EXTRA_SLOTS 1 2130 #else /* !WINDOWS */ 2131 #define EXTRA_SLOTS 0 2132 #endif /* !WINDOWS */ 2133 #ifdef HAVE_POLL 2134 struct pollfd p[1 + EXTRA_SLOTS]; 2135 #endif 2136 #undef EXTRA_SLOTS 2137 #ifdef HAVE_POLL 2138 const bool use_poll = MHD_D_IS_USING_POLL_ (daemon); 2139 #else /* ! HAVE_POLL */ 2140 const bool use_poll = 0; 2141 #endif /* ! HAVE_POLL */ 2142 bool was_suspended = false; 2143 MHD_thread_handle_ID_set_current_thread_ID_ (&(con->tid)); 2144 2145 while ( (! daemon->shutdown) && 2146 (MHD_CONNECTION_CLOSED != con->state) ) 2147 { 2148 bool use_zero_timeout; 2149 #ifdef UPGRADE_SUPPORT 2150 struct MHD_UpgradeResponseHandle *const urh = con->urh; 2151 #else /* ! UPGRADE_SUPPORT */ 2152 static const void *const urh = NULL; 2153 #endif /* ! UPGRADE_SUPPORT */ 2154 2155 if ( (con->suspended) && 2156 (NULL == urh) ) 2157 { 2158 /* Connection was suspended, wait for resume. */ 2159 was_suspended = true; 2160 if (con->resuming) 2161 { 2162 /* The application resumed this connection. Complete the resume 2163 right here: this thread is the only one that handles this 2164 connection, and doing it here is what keeps the wake-up below 2165 free of lost-notification races. */ 2166 resume_connection_own_thread_ (con); 2167 continue; 2168 } 2169 mhd_assert (MHD_ITC_IS_VALID_ (con->resume_itc)); 2170 if (! use_poll) 2171 { 2172 FD_ZERO (&rs); 2173 if (! MHD_add_to_fd_set_ (MHD_itc_r_fd_ (con->resume_itc), 2174 &rs, 2175 NULL, 2176 FD_SETSIZE)) 2177 { 2178 #ifdef HAVE_MESSAGES 2179 MHD_DLOG (con->daemon, 2180 _ ("Failed to add FD to fd_set.\n")); 2181 #endif 2182 goto exit; 2183 } 2184 if (0 > MHD_SYS_select_ (MHD_itc_r_fd_ (con->resume_itc) + 1, 2185 &rs, 2186 NULL, 2187 NULL, 2188 NULL)) 2189 { 2190 const int err = MHD_socket_get_error_ (); 2191 2192 if (MHD_SCKT_ERR_IS_EINTR_ (err)) 2193 continue; 2194 #ifdef HAVE_MESSAGES 2195 MHD_DLOG (con->daemon, 2196 _ ("Error during select (%d): `%s'\n"), 2197 err, 2198 MHD_socket_strerr_ (err)); 2199 #endif 2200 break; 2201 } 2202 } 2203 #ifdef HAVE_POLL 2204 else /* use_poll */ 2205 { 2206 p[0].events = POLLIN; 2207 p[0].fd = MHD_itc_r_fd_ (con->resume_itc); 2208 p[0].revents = 0; 2209 if (0 > MHD_sys_poll_ (p, 2210 1, 2211 -1)) 2212 { 2213 if (MHD_SCKT_LAST_ERR_IS_ (MHD_SCKT_EINTR_)) 2214 continue; 2215 #ifdef HAVE_MESSAGES 2216 MHD_DLOG (con->daemon, 2217 _ ("Error during poll: `%s'\n"), 2218 MHD_socket_last_strerr_ ()); 2219 #endif 2220 break; 2221 } 2222 } 2223 #endif /* HAVE_POLL */ 2224 MHD_itc_clear_ (con->resume_itc); 2225 continue; /* Check again for resume. */ 2226 } /* End of "suspended" branch. */ 2227 2228 if (was_suspended) 2229 { 2230 MHD_update_last_activity_ (con); /* Reset timeout timer. */ 2231 /* Process response queued during suspend and update states. */ 2232 MHD_connection_handle_idle (con); 2233 was_suspended = false; 2234 } 2235 2236 use_zero_timeout = 2237 (0 != (MHD_EVENT_LOOP_INFO_PROCESS & con->event_loop_info) 2238 #ifdef HTTPS_SUPPORT 2239 || ( (con->tls_read_ready) && 2240 (0 != (MHD_EVENT_LOOP_INFO_READ & con->event_loop_info)) ) 2241 #endif /* HTTPS_SUPPORT */ 2242 ); 2243 if (! use_poll) 2244 { 2245 /* use select */ 2246 bool err_state = false; 2247 struct timeval tv; 2248 struct timeval *tvp; 2249 if (use_zero_timeout) 2250 { 2251 tv.tv_sec = 0; 2252 tv.tv_usec = 0; 2253 tvp = &tv; 2254 } 2255 else if (con->connection_timeout_ms > 0) 2256 { 2257 const uint64_t mseconds_left = connection_get_wait (con); 2258 #if (SIZEOF_UINT64_T - 2) >= SIZEOF_STRUCT_TIMEVAL_TV_SEC 2259 if (mseconds_left / 1000 > TIMEVAL_TV_SEC_MAX) 2260 tv.tv_sec = TIMEVAL_TV_SEC_MAX; 2261 else 2262 #endif /* (SIZEOF_UINT64_T - 2) >= SIZEOF_STRUCT_TIMEVAL_TV_SEC */ 2263 tv.tv_sec = (_MHD_TIMEVAL_TV_SEC_TYPE) mseconds_left / 1000; 2264 2265 tv.tv_usec = ((uint16_t) (mseconds_left % 1000)) * ((int32_t) 1000); 2266 tvp = &tv; 2267 } 2268 else 2269 tvp = NULL; 2270 2271 FD_ZERO (&rs); 2272 FD_ZERO (&ws); 2273 FD_ZERO (&es); 2274 maxsock = MHD_INVALID_SOCKET; 2275 switch (con->event_loop_info) 2276 { 2277 case MHD_EVENT_LOOP_INFO_READ: 2278 case MHD_EVENT_LOOP_INFO_PROCESS_READ: 2279 if (! MHD_add_to_fd_set_ (con->socket_fd, 2280 &rs, 2281 &maxsock, 2282 FD_SETSIZE)) 2283 err_state = true; 2284 break; 2285 case MHD_EVENT_LOOP_INFO_WRITE: 2286 if (! MHD_add_to_fd_set_ (con->socket_fd, 2287 &ws, 2288 &maxsock, 2289 FD_SETSIZE)) 2290 err_state = true; 2291 break; 2292 case MHD_EVENT_LOOP_INFO_PROCESS: 2293 if (! MHD_add_to_fd_set_ (con->socket_fd, 2294 &es, 2295 &maxsock, 2296 FD_SETSIZE)) 2297 err_state = true; 2298 break; 2299 case MHD_EVENT_LOOP_INFO_CLEANUP: 2300 /* how did we get here!? */ 2301 goto exit; 2302 } 2303 #ifdef WINDOWS 2304 if (MHD_ITC_IS_VALID_ (daemon->itc) ) 2305 { 2306 if (! MHD_add_to_fd_set_ (MHD_itc_r_fd_ (daemon->itc), 2307 &rs, 2308 &maxsock, 2309 FD_SETSIZE)) 2310 err_state = 1; 2311 } 2312 #endif 2313 if (err_state) 2314 { 2315 #ifdef HAVE_MESSAGES 2316 MHD_DLOG (con->daemon, 2317 _ ("Failed to add FD to fd_set.\n")); 2318 #endif 2319 goto exit; 2320 } 2321 2322 num_ready = MHD_SYS_select_ (maxsock + 1, 2323 &rs, 2324 &ws, 2325 &es, 2326 tvp); 2327 if (num_ready < 0) 2328 { 2329 const int err = MHD_socket_get_error_ (); 2330 2331 if (MHD_SCKT_ERR_IS_EINTR_ (err)) 2332 continue; 2333 #ifdef HAVE_MESSAGES 2334 MHD_DLOG (con->daemon, 2335 _ ("Error during select (%d): `%s'\n"), 2336 err, 2337 MHD_socket_strerr_ (err)); 2338 #endif 2339 break; 2340 } 2341 #ifdef WINDOWS 2342 /* Clear ITC before other processing so additional 2343 * signals will trigger select() again */ 2344 if ( (MHD_ITC_IS_VALID_ (daemon->itc)) && 2345 (FD_ISSET (MHD_itc_r_fd_ (daemon->itc), 2346 &rs)) ) 2347 MHD_itc_clear_ (daemon->itc); 2348 #endif 2349 if (MHD_NO == 2350 call_handlers (con, 2351 FD_ISSET (con->socket_fd, 2352 &rs), 2353 FD_ISSET (con->socket_fd, 2354 &ws), 2355 FD_ISSET (con->socket_fd, 2356 &es)) ) 2357 goto exit; 2358 } 2359 #ifdef HAVE_POLL 2360 else 2361 { 2362 int timeout_val; 2363 /* use poll */ 2364 if (use_zero_timeout) 2365 timeout_val = 0; 2366 else if (con->connection_timeout_ms > 0) 2367 { 2368 const uint64_t mseconds_left = connection_get_wait (con); 2369 #if SIZEOF_UINT64_T >= SIZEOF_INT 2370 if (mseconds_left >= INT_MAX) 2371 timeout_val = INT_MAX; 2372 else 2373 #endif /* SIZEOF_UINT64_T >= SIZEOF_INT */ 2374 timeout_val = (int) mseconds_left; 2375 } 2376 else 2377 timeout_val = -1; 2378 memset (&p, 2379 0, 2380 sizeof (p)); 2381 p[0].fd = con->socket_fd; 2382 switch (con->event_loop_info) 2383 { 2384 case MHD_EVENT_LOOP_INFO_READ: 2385 case MHD_EVENT_LOOP_INFO_PROCESS_READ: 2386 p[0].events |= POLLIN | MHD_POLL_EVENTS_ERR_DISC; 2387 break; 2388 case MHD_EVENT_LOOP_INFO_WRITE: 2389 p[0].events |= POLLOUT | MHD_POLL_EVENTS_ERR_DISC; 2390 break; 2391 case MHD_EVENT_LOOP_INFO_PROCESS: 2392 p[0].events |= MHD_POLL_EVENTS_ERR_DISC; 2393 break; 2394 case MHD_EVENT_LOOP_INFO_CLEANUP: 2395 /* how did we get here!? */ 2396 goto exit; 2397 } 2398 #ifdef WINDOWS 2399 extra_slot = 0; 2400 if (MHD_ITC_IS_VALID_ (daemon->itc)) 2401 { 2402 p[1].events |= POLLIN; 2403 p[1].fd = MHD_itc_r_fd_ (daemon->itc); 2404 p[1].revents = 0; 2405 extra_slot = 1; 2406 } 2407 #endif 2408 if (MHD_sys_poll_ (p, 2409 #ifdef WINDOWS 2410 1 + extra_slot, 2411 #else 2412 1, 2413 #endif 2414 timeout_val) < 0) 2415 { 2416 if (MHD_SCKT_LAST_ERR_IS_ (MHD_SCKT_EINTR_)) 2417 continue; 2418 #ifdef HAVE_MESSAGES 2419 MHD_DLOG (con->daemon, 2420 _ ("Error during poll: `%s'\n"), 2421 MHD_socket_last_strerr_ ()); 2422 #endif 2423 break; 2424 } 2425 #ifdef WINDOWS 2426 /* Clear ITC before other processing so additional 2427 * signals will trigger poll() again */ 2428 if ( (MHD_ITC_IS_VALID_ (daemon->itc)) && 2429 (0 != (p[1].revents & (POLLERR | POLLHUP | POLLIN))) ) 2430 MHD_itc_clear_ (daemon->itc); 2431 #endif 2432 if (MHD_NO == 2433 call_handlers (con, 2434 (0 != (p[0].revents & POLLIN)), 2435 (0 != (p[0].revents & POLLOUT)), 2436 (0 != (p[0].revents & MHD_POLL_REVENTS_ERR_DISC)) )) 2437 goto exit; 2438 } 2439 #endif 2440 #ifdef UPGRADE_SUPPORT 2441 if (MHD_CONNECTION_UPGRADE == con->state) 2442 { 2443 /* Normal HTTP processing is finished, 2444 * notify application. */ 2445 if ( (NULL != daemon->notify_completed) && 2446 (con->rq.client_aware) ) 2447 daemon->notify_completed (daemon->notify_completed_cls, 2448 con, 2449 &con->rq.client_context, 2450 MHD_REQUEST_TERMINATED_COMPLETED_OK); 2451 con->rq.client_aware = false; 2452 2453 thread_main_connection_upgrade (con); 2454 /* MHD_connection_finish_forward_() was called by thread_main_connection_upgrade(). */ 2455 2456 /* "Upgraded" data will not be used in this thread from this point. */ 2457 con->urh->clean_ready = true; 2458 /* If 'urh->was_closed' set to true, connection will be 2459 * moved immediately to cleanup list. Otherwise connection 2460 * will stay in suspended list until 'urh' will be marked 2461 * with 'was_closed' by application. */ 2462 MHD_resume_connection (con); 2463 2464 /* skip usual clean up */ 2465 return (MHD_THRD_RTRN_TYPE_) 0; 2466 } 2467 #endif /* UPGRADE_SUPPORT */ 2468 } 2469 #if _MHD_DEBUG_CLOSE 2470 #ifdef HAVE_MESSAGES 2471 MHD_DLOG (con->daemon, 2472 _ ("Processing thread terminating. Closing connection.\n")); 2473 #endif 2474 #endif 2475 if (MHD_CONNECTION_CLOSED != con->state) 2476 MHD_connection_close_ (con, 2477 (daemon->shutdown) ? 2478 MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN : 2479 MHD_REQUEST_TERMINATED_WITH_ERROR); 2480 MHD_connection_handle_idle (con); 2481 exit: 2482 if (NULL != con->rp.response) 2483 { 2484 MHD_destroy_response (con->rp.response); 2485 con->rp.response = NULL; 2486 } 2487 2488 if (MHD_INVALID_SOCKET != con->socket_fd) 2489 { 2490 shutdown (con->socket_fd, 2491 SHUT_WR); 2492 /* 'socket_fd' can be used in other thread to signal shutdown. 2493 * To avoid data races, do not close socket here. Daemon will 2494 * use more connections only after cleanup anyway. */ 2495 } 2496 if ( (MHD_ITC_IS_VALID_ (daemon->itc)) && 2497 (! MHD_itc_activate_ (daemon->itc, "t")) ) 2498 { 2499 #ifdef HAVE_MESSAGES 2500 MHD_DLOG (daemon, 2501 _ ("Failed to signal thread termination via inter-thread " \ 2502 "communication channel.\n")); 2503 #endif 2504 } 2505 return (MHD_THRD_RTRN_TYPE_) 0; 2506 } 2507 2508 2509 #endif 2510 2511 2512 /** 2513 * Free resources associated with all closed connections. 2514 * (destroy responses, free buffers, etc.). All closed 2515 * connections are kept in the "cleanup" doubly-linked list. 2516 * 2517 * @param daemon daemon to clean up 2518 */ 2519 static void 2520 MHD_cleanup_connections (struct MHD_Daemon *daemon); 2521 2522 #if defined(HTTPS_SUPPORT) 2523 #if defined(MHD_SEND_SPIPE_SUPPRESS_NEEDED) && \ 2524 defined(MHD_SEND_SPIPE_SUPPRESS_POSSIBLE) && \ 2525 ! defined(MHD_socket_nosignal_) && \ 2526 (GNUTLS_VERSION_NUMBER + 0 < 0x030402) && defined(MSG_NOSIGNAL) 2527 /** 2528 * Older version of GnuTLS do not support suppressing of SIGPIPE signal. 2529 * Use push function replacement with suppressing SIGPIPE signal where necessary 2530 * and if possible. 2531 */ 2532 #define MHD_TLSLIB_NEED_PUSH_FUNC 1 2533 #endif /* MHD_SEND_SPIPE_SUPPRESS_NEEDED && 2534 MHD_SEND_SPIPE_SUPPRESS_POSSIBLE && 2535 ! MHD_socket_nosignal_ && (GNUTLS_VERSION_NUMBER+0 < 0x030402) && 2536 MSG_NOSIGNAL */ 2537 2538 #ifdef MHD_TLSLIB_NEED_PUSH_FUNC 2539 /** 2540 * Data push function replacement with suppressing SIGPIPE signal 2541 * for TLS library. 2542 */ 2543 static ssize_t 2544 MHD_tls_push_func_ (gnutls_transport_ptr_t trnsp, 2545 const void *data, 2546 size_t data_size) 2547 { 2548 #if (MHD_SCKT_SEND_MAX_SIZE_ < SSIZE_MAX) || (0 == SSIZE_MAX) 2549 if (data_size > MHD_SCKT_SEND_MAX_SIZE_) 2550 data_size = MHD_SCKT_SEND_MAX_SIZE_; 2551 #endif /* (MHD_SCKT_SEND_MAX_SIZE_ < SSIZE_MAX) || (0 == SSIZE_MAX) */ 2552 return MHD_send_ ((MHD_socket) (intptr_t) (trnsp), data, data_size); 2553 } 2554 2555 2556 #endif /* MHD_TLSLIB_DONT_SUPPRESS_SIGPIPE */ 2557 2558 2559 /** 2560 * The shortest pre-shared key #MHD_OPTION_GNUTLS_PSK_CRED_HANDLER may 2561 * hand back, in bytes. RFC 4279 section 7.1 requires at least 16 bytes 2562 * of entropy in a PSK and recommends the length of the hash of the 2563 * negotiated cipher suite; anything shorter is brute-forceable offline 2564 * from a single recorded handshake, so MHD refuses it rather than let 2565 * the application weaken the connection by accident. 2566 */ 2567 #define MHD_PSK_MIN_SIZE 16 2568 2569 /** 2570 * Function called by GNUtls to obtain the PSK for a given session. 2571 * 2572 * @param session the session to lookup PSK for 2573 * @param username username to lookup PSK for 2574 * @param[out] key where to write PSK 2575 * @return 0 on success, -1 on error 2576 */ 2577 static int 2578 psk_gnutls_adapter (gnutls_session_t session, 2579 const char *username, 2580 gnutls_datum_t *key) 2581 { 2582 struct MHD_Connection *connection; 2583 struct MHD_Daemon *daemon; 2584 #if GNUTLS_VERSION_MAJOR >= 3 2585 void *app_psk; 2586 size_t app_psk_size; 2587 #endif /* GNUTLS_VERSION_MAJOR >= 3 */ 2588 2589 connection = gnutls_session_get_ptr (session); 2590 if (NULL == connection) 2591 { 2592 #ifdef HAVE_MESSAGES 2593 /* Cannot use our logger, we don't even have "daemon" */ 2594 MHD_PANIC (_ ("Internal server error. This should be impossible.\n")); 2595 #endif 2596 return -1; 2597 } 2598 daemon = connection->daemon; 2599 #if GNUTLS_VERSION_MAJOR >= 3 2600 if (NULL == daemon->cred_callback) 2601 { 2602 #ifdef HAVE_MESSAGES 2603 MHD_DLOG (daemon, 2604 _ ("PSK not supported by this server.\n")); 2605 #endif 2606 return -1; 2607 } 2608 if (0 != daemon->cred_callback (daemon->cred_callback_cls, 2609 connection, 2610 username, 2611 &app_psk, 2612 &app_psk_size)) 2613 return -1; 2614 if (MHD_PSK_MIN_SIZE > app_psk_size) 2615 { 2616 #ifdef HAVE_MESSAGES 2617 MHD_DLOG (daemon, 2618 _ ("PSK authentication failed: PSK too short.\n")); 2619 #endif 2620 free (app_psk); 2621 return -1; 2622 } 2623 if (UINT_MAX < app_psk_size) 2624 { 2625 #ifdef HAVE_MESSAGES 2626 MHD_DLOG (daemon, 2627 _ ("PSK authentication failed: PSK too long.\n")); 2628 #endif 2629 free (app_psk); 2630 return -1; 2631 } 2632 /* @a app_psk_size is at least MHD_PSK_MIN_SIZE here, so this is never 2633 gnutls_malloc(0) -- whose result is implementation defined and would 2634 be reported below as an allocation failure. */ 2635 if (NULL == (key->data = gnutls_malloc (app_psk_size))) 2636 { 2637 #ifdef HAVE_MESSAGES 2638 MHD_DLOG (daemon, 2639 _ ("PSK authentication failed: gnutls_malloc failed to " \ 2640 "allocate memory.\n")); 2641 #endif 2642 free (app_psk); 2643 return -1; 2644 } 2645 key->size = (unsigned int) app_psk_size; 2646 memcpy (key->data, 2647 app_psk, 2648 app_psk_size); 2649 free (app_psk); 2650 return 0; 2651 #else 2652 (void) username; (void) key; /* Mute compiler warning */ 2653 #ifdef HAVE_MESSAGES 2654 MHD_DLOG (daemon, 2655 _ ("PSK not supported by this server.\n")); 2656 #endif 2657 return -1; 2658 #endif 2659 } 2660 2661 2662 #endif /* HTTPS_SUPPORT */ 2663 2664 2665 /** 2666 * Do basic preparation work on the new incoming connection. 2667 * 2668 * This function do all preparation that is possible outside main daemon 2669 * thread. 2670 * @remark Could be called from any thread. 2671 * 2672 * @param daemon daemon that manages the connection 2673 * @param client_socket socket to manage (MHD will expect 2674 * to receive an HTTP request from this socket next). 2675 * @param addr IP address of the client 2676 * @param addrlen number of bytes in @a addr 2677 * @param external_add indicate that socket has been added externally 2678 * @param non_blck indicate that socket in non-blocking mode 2679 * @param sk_spipe_supprs indicate that the @a client_socket has 2680 * set SIGPIPE suppression 2681 * @param sk_is_nonip _MHD_YES if this is not a TCP/IP socket 2682 * @return pointer to the connection on success, NULL if this daemon could 2683 * not handle the connection (i.e. malloc failed, etc). 2684 * The socket will be closed in case of error; 'errno' is 2685 * set to indicate further details about the error. 2686 */ 2687 static struct MHD_Connection * 2688 new_connection_prepare_ (struct MHD_Daemon *daemon, 2689 MHD_socket client_socket, 2690 const struct sockaddr_storage *addr, 2691 socklen_t addrlen, 2692 bool external_add, 2693 bool non_blck, 2694 bool sk_spipe_supprs, 2695 enum MHD_tristate sk_is_nonip) 2696 { 2697 struct MHD_Connection *connection; 2698 int eno = 0; 2699 2700 #ifdef HAVE_MESSAGES 2701 #if _MHD_DEBUG_CONNECT 2702 MHD_DLOG (daemon, 2703 _ ("Accepted connection on socket %d.\n"), 2704 client_socket); 2705 #endif 2706 #endif 2707 if ( (daemon->connections == daemon->connection_limit) || 2708 (MHD_NO == MHD_ip_limit_add (daemon, 2709 addr, 2710 addrlen)) ) 2711 { 2712 /* above connection limit - reject */ 2713 #ifdef HAVE_MESSAGES 2714 MHD_DLOG (daemon, 2715 _ ("Server reached connection limit. " \ 2716 "Closing inbound connection.\n")); 2717 #endif 2718 MHD_socket_close_chk_ (client_socket); 2719 #if defined(ENFILE) && (ENFILE + 0 != 0) 2720 errno = ENFILE; 2721 #endif 2722 return NULL; 2723 } 2724 2725 /* apply connection acceptance policy if present */ 2726 if ( (NULL != daemon->apc) && 2727 (MHD_NO == daemon->apc (daemon->apc_cls, 2728 (const struct sockaddr *) addr, 2729 addrlen)) ) 2730 { 2731 #if _MHD_DEBUG_CLOSE 2732 #ifdef HAVE_MESSAGES 2733 MHD_DLOG (daemon, 2734 _ ("Connection rejected by application. Closing connection.\n")); 2735 #endif 2736 #endif 2737 MHD_socket_close_chk_ (client_socket); 2738 MHD_ip_limit_del (daemon, 2739 addr, 2740 addrlen); 2741 #if defined(EACCESS) && (EACCESS + 0 != 0) 2742 errno = EACCESS; 2743 #endif 2744 return NULL; 2745 } 2746 2747 if (NULL == (connection = MHD_calloc_ (1, sizeof (struct MHD_Connection)))) 2748 { 2749 eno = errno; 2750 #ifdef HAVE_MESSAGES 2751 MHD_DLOG (daemon, 2752 _ ("Error allocating memory: %s\n"), 2753 MHD_strerror_ (errno)); 2754 #endif 2755 MHD_socket_close_chk_ (client_socket); 2756 MHD_ip_limit_del (daemon, 2757 addr, 2758 addrlen); 2759 errno = eno; 2760 return NULL; 2761 } 2762 2763 if (! external_add) 2764 { 2765 connection->sk_corked = _MHD_OFF; 2766 connection->sk_nodelay = _MHD_OFF; 2767 } 2768 else 2769 { 2770 connection->sk_corked = _MHD_UNKNOWN; 2771 connection->sk_nodelay = _MHD_UNKNOWN; 2772 } 2773 2774 if (0 < addrlen) 2775 { 2776 if (NULL == (connection->addr = malloc ((size_t) addrlen))) 2777 { 2778 eno = errno; 2779 #ifdef HAVE_MESSAGES 2780 MHD_DLOG (daemon, 2781 _ ("Error allocating memory: %s\n"), 2782 MHD_strerror_ (errno)); 2783 #endif 2784 MHD_socket_close_chk_ (client_socket); 2785 MHD_ip_limit_del (daemon, 2786 addr, 2787 addrlen); 2788 free (connection); 2789 errno = eno; 2790 return NULL; 2791 } 2792 memcpy (connection->addr, 2793 addr, 2794 (size_t) addrlen); 2795 } 2796 else 2797 connection->addr = NULL; 2798 connection->addr_len = addrlen; 2799 connection->socket_fd = client_socket; 2800 connection->sk_nonblck = non_blck; 2801 connection->is_nonip = sk_is_nonip; 2802 connection->sk_spipe_suppress = sk_spipe_supprs; 2803 #ifdef MHD_USE_THREADS 2804 MHD_thread_handle_ID_set_invalid_ (&connection->tid); 2805 #endif /* MHD_USE_THREADS */ 2806 connection->daemon = daemon; 2807 connection->connection_timeout_ms = daemon->connection_timeout_ms; 2808 connection->event_loop_info = MHD_EVENT_LOOP_INFO_READ; 2809 if (0 != connection->connection_timeout_ms) 2810 connection->last_activity = MHD_monotonic_msec_counter (); 2811 2812 MHD_itc_set_invalid_ (connection->resume_itc); 2813 if ( (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) && 2814 (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) && 2815 (! MHD_itc_init_ (connection->resume_itc)) ) 2816 { 2817 eno = errno; 2818 #ifdef HAVE_MESSAGES 2819 MHD_DLOG (daemon, 2820 _ ("Failed to create inter-thread communication channel " \ 2821 "for the connection: %s\n"), 2822 MHD_itc_last_strerror_ ()); 2823 #endif 2824 MHD_socket_close_chk_ (client_socket); 2825 MHD_ip_limit_del (daemon, 2826 addr, 2827 addrlen); 2828 if (NULL != connection->addr) 2829 free (connection->addr); 2830 free (connection); 2831 errno = eno; 2832 return NULL; 2833 } 2834 2835 if (0 == (daemon->options & MHD_USE_TLS)) 2836 { 2837 /* set default connection handlers */ 2838 MHD_set_http_callbacks_ (connection); 2839 } 2840 else 2841 { 2842 #ifdef HTTPS_SUPPORT 2843 #if (GNUTLS_VERSION_NUMBER + 0 >= 0x030500) 2844 gnutls_init_flags_t 2845 #else 2846 unsigned int 2847 #endif 2848 flags; 2849 2850 flags = GNUTLS_SERVER; 2851 #if (GNUTLS_VERSION_NUMBER + 0 >= 0x030402) 2852 flags |= GNUTLS_NO_SIGNAL; 2853 #endif /* GNUTLS_VERSION_NUMBER >= 0x030402 */ 2854 #if GNUTLS_VERSION_MAJOR >= 3 2855 flags |= GNUTLS_NONBLOCK; 2856 #endif /* GNUTLS_VERSION_MAJOR >= 3*/ 2857 #if (GNUTLS_VERSION_NUMBER + 0 >= 0x030603) 2858 if (0 != (daemon->options & MHD_USE_POST_HANDSHAKE_AUTH_SUPPORT)) 2859 flags |= GNUTLS_POST_HANDSHAKE_AUTH; 2860 #endif 2861 #if (GNUTLS_VERSION_NUMBER + 0 >= 0x030605) 2862 if (0 != (daemon->options & MHD_USE_INSECURE_TLS_EARLY_DATA)) 2863 flags |= GNUTLS_ENABLE_EARLY_DATA; 2864 #endif 2865 connection->tls_state = MHD_TLS_CONN_INIT; 2866 MHD_set_https_callbacks (connection); 2867 if ((GNUTLS_E_SUCCESS != gnutls_init (&connection->tls_session, flags)) || 2868 (GNUTLS_E_SUCCESS != gnutls_priority_set (connection->tls_session, 2869 daemon->priority_cache))) 2870 { 2871 if (NULL != connection->tls_session) 2872 gnutls_deinit (connection->tls_session); 2873 MHD_socket_close_chk_ (client_socket); 2874 MHD_ip_limit_del (daemon, 2875 addr, 2876 addrlen); 2877 if (NULL != connection->addr) 2878 free (connection->addr); 2879 free (connection); 2880 #ifdef HAVE_MESSAGES 2881 MHD_DLOG (daemon, 2882 _ ("Failed to initialise TLS session.\n")); 2883 #endif 2884 #if defined(EPROTO) && (EPROTO + 0 != 0) 2885 errno = EPROTO; 2886 #endif 2887 return NULL; 2888 } 2889 #if (GNUTLS_VERSION_NUMBER + 0 >= 0x030200) 2890 if (! daemon->disable_alpn) 2891 { 2892 static const char prt1[] = "http/1.1"; /* Registered code for HTTP/1.1 */ 2893 static const char prt2[] = "http/1.0"; /* Registered code for HTTP/1.0 */ 2894 static const gnutls_datum_t prts[2] = 2895 { {_MHD_DROP_CONST (prt1), MHD_STATICSTR_LEN_ (prt1)}, 2896 {_MHD_DROP_CONST (prt2), MHD_STATICSTR_LEN_ (prt2)} }; 2897 2898 if (GNUTLS_E_SUCCESS != 2899 gnutls_alpn_set_protocols (connection->tls_session, 2900 prts, 2901 sizeof(prts) / sizeof(prts[0]), 2902 0 /* | GNUTLS_ALPN_SERVER_PRECEDENCE */)) 2903 { 2904 #ifdef HAVE_MESSAGES 2905 MHD_DLOG (daemon, 2906 _ ("Failed to set ALPN protocols.\n")); 2907 #else /* ! HAVE_MESSAGES */ 2908 (void) 0; /* Mute compiler warning */ 2909 #endif /* ! HAVE_MESSAGES */ 2910 } 2911 } 2912 #endif /* GNUTLS_VERSION_NUMBER >= 0x030200 */ 2913 gnutls_session_set_ptr (connection->tls_session, 2914 connection); 2915 switch (daemon->cred_type) 2916 { 2917 /* set needed credentials for certificate authentication. */ 2918 case GNUTLS_CRD_CERTIFICATE: 2919 gnutls_credentials_set (connection->tls_session, 2920 GNUTLS_CRD_CERTIFICATE, 2921 daemon->x509_cred); 2922 break; 2923 case GNUTLS_CRD_PSK: 2924 gnutls_credentials_set (connection->tls_session, 2925 GNUTLS_CRD_PSK, 2926 daemon->psk_cred); 2927 gnutls_psk_set_server_credentials_function (daemon->psk_cred, 2928 &psk_gnutls_adapter); 2929 break; 2930 case GNUTLS_CRD_ANON: 2931 case GNUTLS_CRD_SRP: 2932 case GNUTLS_CRD_IA: 2933 default: 2934 #ifdef HAVE_MESSAGES 2935 MHD_DLOG (daemon, 2936 _ ("Failed to setup TLS credentials: " \ 2937 "unknown credential type %d.\n"), 2938 daemon->cred_type); 2939 #endif 2940 gnutls_deinit (connection->tls_session); 2941 MHD_socket_close_chk_ (client_socket); 2942 MHD_ip_limit_del (daemon, 2943 addr, 2944 addrlen); 2945 if (NULL != connection->addr) 2946 free (connection->addr); 2947 free (connection); 2948 MHD_PANIC (_ ("Unknown credential type.\n")); 2949 #if defined(EINVAL) && (EINVAL + 0 != 0) 2950 errno = EINVAL; 2951 #endif 2952 return NULL; 2953 } 2954 #if (GNUTLS_VERSION_NUMBER + 0 >= 0x030109) && ! defined(_WIN64) 2955 gnutls_transport_set_int (connection->tls_session, 2956 (int) (client_socket)); 2957 #else /* GnuTLS before 3.1.9 or Win x64 */ 2958 gnutls_transport_set_ptr (connection->tls_session, 2959 (gnutls_transport_ptr_t) \ 2960 (intptr_t) client_socket); 2961 #endif /* GnuTLS before 3.1.9 or Win x64 */ 2962 #ifdef MHD_TLSLIB_NEED_PUSH_FUNC 2963 gnutls_transport_set_push_function (connection->tls_session, 2964 MHD_tls_push_func_); 2965 #endif /* MHD_TLSLIB_NEED_PUSH_FUNC */ 2966 if (daemon->https_mem_trust) 2967 gnutls_certificate_server_set_request (connection->tls_session, 2968 GNUTLS_CERT_REQUEST); 2969 #else /* ! HTTPS_SUPPORT */ 2970 MHD_socket_close_chk_ (client_socket); 2971 MHD_ip_limit_del (daemon, 2972 addr, 2973 addrlen); 2974 free (connection->addr); 2975 free (connection); 2976 MHD_PANIC (_ ("TLS connection on non-TLS daemon.\n")); 2977 #if 0 2978 /* Unreachable code */ 2979 eno = EINVAL; 2980 return NULL; 2981 #endif 2982 #endif /* ! HTTPS_SUPPORT */ 2983 } 2984 2985 return connection; 2986 } 2987 2988 2989 #ifdef MHD_USE_THREADS 2990 /** 2991 * Close prepared, but not yet processed connection. 2992 * @param daemon the daemon 2993 * @param connection the connection to close 2994 */ 2995 static void 2996 new_connection_close_ (struct MHD_Daemon *daemon, 2997 struct MHD_Connection *connection) 2998 { 2999 mhd_assert (connection->daemon == daemon); 3000 mhd_assert (! connection->in_cleanup); 3001 mhd_assert (NULL == connection->next); 3002 mhd_assert (NULL == connection->nextX); 3003 #ifdef EPOLL_SUPPORT 3004 mhd_assert (NULL == connection->nextE); 3005 #endif /* EPOLL_SUPPORT */ 3006 3007 #ifdef HTTPS_SUPPORT 3008 if (NULL != connection->tls_session) 3009 { 3010 mhd_assert (0 != (daemon->options & MHD_USE_TLS)); 3011 gnutls_deinit (connection->tls_session); 3012 } 3013 #endif /* HTTPS_SUPPORT */ 3014 MHD_socket_close_chk_ (connection->socket_fd); 3015 if (MHD_ITC_IS_VALID_ (connection->resume_itc)) 3016 MHD_itc_destroy_chk_ (connection->resume_itc); 3017 MHD_ip_limit_del (daemon, 3018 connection->addr, 3019 connection->addr_len); 3020 if (NULL != connection->addr) 3021 free (connection->addr); 3022 free (connection); 3023 } 3024 3025 3026 #endif /* MHD_USE_THREADS */ 3027 3028 3029 /** 3030 * Finally insert the new connection to the list of connections 3031 * served by the daemon and start processing. 3032 * @remark To be called only from thread that process 3033 * daemon's select()/poll()/etc. 3034 * 3035 * @param daemon daemon that manages the connection 3036 * @param connection the newly created connection 3037 * @return #MHD_YES on success, #MHD_NO on error 3038 */ 3039 static enum MHD_Result 3040 new_connection_process_ (struct MHD_Daemon *daemon, 3041 struct MHD_Connection *connection) 3042 { 3043 int eno = 0; 3044 3045 mhd_assert (connection->daemon == daemon); 3046 3047 #ifdef MHD_USE_THREADS 3048 /* Function manipulate connection and timeout DL-lists, 3049 * must be called only within daemon thread. */ 3050 mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ 3051 MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); 3052 mhd_assert (NULL == daemon->worker_pool); 3053 #endif /* MHD_USE_THREADS */ 3054 3055 /* Allocate memory pool in the processing thread so 3056 * intensively used memory area is allocated in "good" 3057 * (for the thread) memory region. It is important with 3058 * NUMA and/or complex cache hierarchy. */ 3059 connection->pool = MHD_pool_create (daemon->pool_size); 3060 if (NULL == connection->pool) 3061 { /* 'pool' creation failed */ 3062 #ifdef HAVE_MESSAGES 3063 MHD_DLOG (daemon, 3064 _ ("Error allocating memory: %s\n"), 3065 MHD_strerror_ (errno)); 3066 #endif 3067 #if defined(ENOMEM) && (ENOMEM + 0 != 0) 3068 eno = ENOMEM; 3069 #endif 3070 (void) 0; /* Mute possible compiler warning */ 3071 } 3072 else 3073 { /* 'pool' creation succeed */ 3074 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); 3075 /* Firm check under lock. */ 3076 if (daemon->connections >= daemon->connection_limit) 3077 { /* Connections limit */ 3078 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); 3079 #ifdef HAVE_MESSAGES 3080 MHD_DLOG (daemon, 3081 _ ("Server reached connection limit. " 3082 "Closing inbound connection.\n")); 3083 #endif 3084 #if defined(ENFILE) && (ENFILE + 0 != 0) 3085 eno = ENFILE; 3086 #endif 3087 (void) 0; /* Mute possible compiler warning */ 3088 } 3089 else 3090 { /* Have space for new connection */ 3091 daemon->connections++; 3092 DLL_insert (daemon->connections_head, 3093 daemon->connections_tail, 3094 connection); 3095 if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) 3096 { 3097 XDLL_insert (daemon->normal_timeout_head, 3098 daemon->normal_timeout_tail, 3099 connection); 3100 } 3101 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); 3102 3103 MHD_connection_set_initial_state_ (connection); 3104 3105 if (NULL != daemon->notify_connection) 3106 daemon->notify_connection (daemon->notify_connection_cls, 3107 connection, 3108 &connection->socket_context, 3109 MHD_CONNECTION_NOTIFY_STARTED); 3110 #ifdef MHD_USE_THREADS 3111 if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) 3112 { 3113 mhd_assert (! MHD_D_IS_USING_EPOLL_ (daemon)); 3114 if (! MHD_create_named_thread_ (&connection->tid, 3115 "MHD-connection", 3116 daemon->thread_stack_size, 3117 &thread_main_handle_connection, 3118 connection)) 3119 { 3120 eno = errno; 3121 #ifdef HAVE_MESSAGES 3122 #ifdef EAGAIN 3123 if (EAGAIN == eno) 3124 MHD_DLOG (daemon, 3125 _ ("Failed to create a new thread because it would " 3126 "have exceeded the system limit on the number of " 3127 "threads or no system resources available.\n")); 3128 else 3129 #endif /* EAGAIN */ 3130 MHD_DLOG (daemon, 3131 _ ("Failed to create a thread: %s\n"), 3132 MHD_strerror_ (eno)); 3133 #endif /* HAVE_MESSAGES */ 3134 } 3135 else /* New thread has been created successfully */ 3136 return MHD_YES; /* *** Function success exit point *** */ 3137 } 3138 else 3139 #else /* ! MHD_USE_THREADS */ 3140 if (1) 3141 #endif /* ! MHD_USE_THREADS */ 3142 { /* No 'thread-per-connection' */ 3143 #ifdef MHD_USE_THREADS 3144 connection->tid = daemon->tid; 3145 #endif /* MHD_USE_THREADS */ 3146 #ifdef EPOLL_SUPPORT 3147 if (MHD_D_IS_USING_EPOLL_ (daemon)) 3148 { 3149 if (0 == (daemon->options & MHD_USE_TURBO)) 3150 { 3151 struct epoll_event event; 3152 3153 event.events = EPOLLIN | EPOLLOUT | EPOLLPRI | EPOLLET | EPOLLRDHUP; 3154 event.data.ptr = connection; 3155 if (0 != epoll_ctl (daemon->epoll_fd, 3156 EPOLL_CTL_ADD, 3157 connection->socket_fd, 3158 &event)) 3159 { 3160 eno = errno; 3161 #ifdef HAVE_MESSAGES 3162 MHD_DLOG (daemon, 3163 _ ("Call to epoll_ctl failed: %s\n"), 3164 MHD_socket_last_strerr_ ()); 3165 #endif 3166 } 3167 else 3168 { /* 'socket_fd' has been added to 'epool' */ 3169 connection->epoll_state |= MHD_EPOLL_STATE_IN_EPOLL_SET; 3170 3171 return MHD_YES; /* *** Function success exit point *** */ 3172 } 3173 } 3174 else 3175 { 3176 connection->epoll_state |= MHD_EPOLL_STATE_READ_READY 3177 | MHD_EPOLL_STATE_WRITE_READY 3178 | MHD_EPOLL_STATE_IN_EREADY_EDLL; 3179 EDLL_insert (daemon->eready_head, 3180 daemon->eready_tail, 3181 connection); 3182 3183 return MHD_YES; /* *** Function success exit point *** */ 3184 } 3185 } 3186 else /* No 'epoll' */ 3187 #endif /* EPOLL_SUPPORT */ 3188 return MHD_YES; /* *** Function success exit point *** */ 3189 } 3190 3191 /* ** Below is a cleanup path ** */ 3192 if (NULL != daemon->notify_connection) 3193 daemon->notify_connection (daemon->notify_connection_cls, 3194 connection, 3195 &connection->socket_context, 3196 MHD_CONNECTION_NOTIFY_CLOSED); 3197 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); 3198 if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) 3199 { 3200 XDLL_remove (daemon->normal_timeout_head, 3201 daemon->normal_timeout_tail, 3202 connection); 3203 } 3204 DLL_remove (daemon->connections_head, 3205 daemon->connections_tail, 3206 connection); 3207 daemon->connections--; 3208 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); 3209 } 3210 MHD_pool_destroy (connection->pool); 3211 } 3212 /* Free resources allocated before the call of this functions */ 3213 #ifdef HTTPS_SUPPORT 3214 if (NULL != connection->tls_session) 3215 gnutls_deinit (connection->tls_session); 3216 #endif /* HTTPS_SUPPORT */ 3217 MHD_ip_limit_del (daemon, 3218 connection->addr, 3219 connection->addr_len); 3220 if (NULL != connection->addr) 3221 free (connection->addr); 3222 MHD_socket_close_chk_ (connection->socket_fd); 3223 free (connection); 3224 if (0 != eno) 3225 errno = eno; 3226 #ifdef EINVAL 3227 else 3228 errno = EINVAL; 3229 #endif /* EINVAL */ 3230 return MHD_NO; /* *** Function failure exit point *** */ 3231 } 3232 3233 3234 /** 3235 * Add another client connection to the set of connections 3236 * managed by MHD. This API is usually not needed (since 3237 * MHD will accept inbound connections on the server socket). 3238 * Use this API in special cases, for example if your HTTP 3239 * server is behind NAT and needs to connect out to the 3240 * HTTP client. 3241 * 3242 * The given client socket will be managed (and closed!) by MHD after 3243 * this call and must no longer be used directly by the application 3244 * afterwards. 3245 * 3246 * @param daemon daemon that manages the connection 3247 * @param client_socket socket to manage (MHD will expect 3248 * to receive an HTTP request from this socket next). 3249 * @param addr IP address of the client 3250 * @param addrlen number of bytes in @a addr 3251 * @param external_add perform additional operations needed due 3252 * to the application calling us directly 3253 * @param non_blck indicate that socket in non-blocking mode 3254 * @param sk_spipe_supprs indicate that the @a client_socket has 3255 * set SIGPIPE suppression 3256 * @param sk_is_nonip _MHD_YES if this is not a TCP/IP socket 3257 * @return #MHD_YES on success, #MHD_NO if this daemon could 3258 * not handle the connection (i.e. malloc failed, etc). 3259 * The socket will be closed in any case; 'errno' is 3260 * set to indicate further details about the error. 3261 */ 3262 static enum MHD_Result 3263 internal_add_connection (struct MHD_Daemon *daemon, 3264 MHD_socket client_socket, 3265 const struct sockaddr_storage *addr, 3266 socklen_t addrlen, 3267 bool external_add, 3268 bool non_blck, 3269 bool sk_spipe_supprs, 3270 enum MHD_tristate sk_is_nonip) 3271 { 3272 struct MHD_Connection *connection; 3273 3274 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 3275 /* Direct add to master daemon could never happen. */ 3276 mhd_assert (NULL == daemon->worker_pool); 3277 #endif 3278 3279 if (MHD_D_IS_USING_SELECT_ (daemon) && 3280 (! MHD_D_DOES_SCKT_FIT_FDSET_ (client_socket, daemon)) ) 3281 { 3282 #ifdef HAVE_MESSAGES 3283 MHD_DLOG (daemon, 3284 _ ("New connection socket descriptor (%d) is not less " \ 3285 "than FD_SETSIZE (%d).\n"), 3286 (int) client_socket, 3287 (int) MHD_D_GET_FD_SETSIZE_ (daemon)); 3288 #endif 3289 MHD_socket_close_chk_ (client_socket); 3290 #if defined(ENFILE) && (ENFILE + 0 != 0) 3291 errno = ENFILE; 3292 #endif 3293 return MHD_NO; 3294 } 3295 3296 if (MHD_D_IS_USING_EPOLL_ (daemon) && 3297 (! non_blck) ) 3298 { 3299 #ifdef HAVE_MESSAGES 3300 MHD_DLOG (daemon, 3301 _ ("Epoll mode supports only non-blocking sockets\n")); 3302 #endif 3303 MHD_socket_close_chk_ (client_socket); 3304 #if defined(EINVAL) && (EINVAL + 0 != 0) 3305 errno = EINVAL; 3306 #endif 3307 return MHD_NO; 3308 } 3309 3310 connection = new_connection_prepare_ (daemon, 3311 client_socket, 3312 addr, addrlen, 3313 external_add, 3314 non_blck, 3315 sk_spipe_supprs, 3316 sk_is_nonip); 3317 if (NULL == connection) 3318 return MHD_NO; 3319 3320 if ((external_add) && 3321 MHD_D_IS_THREAD_SAFE_ (daemon)) 3322 { 3323 /* Connection is added externally and MHD is thread safe mode. */ 3324 MHD_mutex_lock_chk_ (&daemon->new_connections_mutex); 3325 DLL_insert (daemon->new_connections_head, 3326 daemon->new_connections_tail, 3327 connection); 3328 daemon->have_new = true; 3329 MHD_mutex_unlock_chk_ (&daemon->new_connections_mutex); 3330 3331 /* The rest of connection processing must be handled in 3332 * the daemon thread. */ 3333 if ((MHD_ITC_IS_VALID_ (daemon->itc)) && 3334 (! MHD_itc_activate_ (daemon->itc, "n"))) 3335 { 3336 #ifdef HAVE_MESSAGES 3337 MHD_DLOG (daemon, 3338 _ ("Failed to signal new connection via inter-thread " \ 3339 "communication channel.\n")); 3340 #endif 3341 } 3342 return MHD_YES; 3343 } 3344 3345 return new_connection_process_ (daemon, connection); 3346 } 3347 3348 3349 static void 3350 new_connections_list_process_ (struct MHD_Daemon *daemon) 3351 { 3352 struct MHD_Connection *local_head; 3353 struct MHD_Connection *local_tail; 3354 mhd_assert (daemon->have_new); 3355 mhd_assert (MHD_D_IS_THREAD_SAFE_ (daemon)); 3356 3357 /* Detach DL-list of new connections from the daemon for 3358 * following local processing. */ 3359 MHD_mutex_lock_chk_ (&daemon->new_connections_mutex); 3360 mhd_assert (NULL != daemon->new_connections_head); 3361 local_head = daemon->new_connections_head; 3362 local_tail = daemon->new_connections_tail; 3363 daemon->new_connections_head = NULL; 3364 daemon->new_connections_tail = NULL; 3365 daemon->have_new = false; 3366 MHD_mutex_unlock_chk_ (&daemon->new_connections_mutex); 3367 (void) local_head; /* Mute compiler warning */ 3368 3369 /* Process new connections in FIFO order. */ 3370 do 3371 { 3372 struct MHD_Connection *c; /**< Currently processed connection */ 3373 3374 c = local_tail; 3375 DLL_remove (local_head, 3376 local_tail, 3377 c); 3378 mhd_assert (daemon == c->daemon); 3379 if (MHD_NO == new_connection_process_ (daemon, c)) 3380 { 3381 #ifdef HAVE_MESSAGES 3382 MHD_DLOG (daemon, 3383 _ ("Failed to start serving new connection.\n")); 3384 #endif 3385 (void) 0; 3386 } 3387 } while (NULL != local_tail); 3388 3389 } 3390 3391 3392 /** 3393 * Internal version of ::MHD_suspend_connection(). 3394 * 3395 * @remark In thread-per-connection mode: can be called from any thread, 3396 * in any other mode: to be called only from thread that process 3397 * daemon's select()/poll()/etc. 3398 * 3399 * @param connection the connection to suspend 3400 */ 3401 void 3402 internal_suspend_connection_ (struct MHD_Connection *connection) 3403 { 3404 struct MHD_Daemon *daemon = connection->daemon; 3405 mhd_assert (NULL == daemon->worker_pool); 3406 3407 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 3408 mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ 3409 MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) || \ 3410 MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); 3411 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); 3412 #endif 3413 if (connection->resuming) 3414 { 3415 /* suspending again while we didn't even complete resuming yet */ 3416 connection->resuming = false; 3417 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 3418 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); 3419 #endif 3420 return; 3421 } 3422 if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) 3423 { 3424 if (connection->connection_timeout_ms == daemon->connection_timeout_ms) 3425 XDLL_remove (daemon->normal_timeout_head, 3426 daemon->normal_timeout_tail, 3427 connection); 3428 else 3429 XDLL_remove (daemon->manual_timeout_head, 3430 daemon->manual_timeout_tail, 3431 connection); 3432 } 3433 DLL_remove (daemon->connections_head, 3434 daemon->connections_tail, 3435 connection); 3436 mhd_assert (! connection->suspended); 3437 DLL_insert (daemon->suspended_connections_head, 3438 daemon->suspended_connections_tail, 3439 connection); 3440 connection->suspended = true; 3441 #ifdef EPOLL_SUPPORT 3442 if (MHD_D_IS_USING_EPOLL_ (daemon)) 3443 { 3444 if (0 != (connection->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL)) 3445 { 3446 EDLL_remove (daemon->eready_head, 3447 daemon->eready_tail, 3448 connection); 3449 connection->epoll_state &= 3450 ~((enum MHD_EpollState) MHD_EPOLL_STATE_IN_EREADY_EDLL); 3451 } 3452 if (0 != (connection->epoll_state & MHD_EPOLL_STATE_IN_EPOLL_SET)) 3453 { 3454 if (0 != epoll_ctl (daemon->epoll_fd, 3455 EPOLL_CTL_DEL, 3456 connection->socket_fd, 3457 NULL)) 3458 MHD_PANIC (_ ("Failed to remove FD from epoll set.\n")); 3459 connection->epoll_state &= 3460 ~((enum MHD_EpollState) MHD_EPOLL_STATE_IN_EPOLL_SET); 3461 } 3462 connection->epoll_state |= MHD_EPOLL_STATE_SUSPENDED; 3463 } 3464 #endif 3465 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 3466 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); 3467 #endif 3468 } 3469 3470 3471 /** 3472 * Suspend handling of network data for a given connection. 3473 * This can be used to dequeue a connection from MHD's event loop 3474 * (not applicable to thread-per-connection!) for a while. 3475 * 3476 * If you use this API in conjunction with an "internal" socket polling, 3477 * you must set the option #MHD_USE_ITC to ensure that a resumed 3478 * connection is immediately processed by MHD. 3479 * 3480 * Suspended connections continue to count against the total number of 3481 * connections allowed (per daemon, as well as per IP, if such limits 3482 * are set). Suspended connections will NOT time out; timeouts will 3483 * restart when the connection handling is resumed. While a 3484 * connection is suspended, MHD will not detect disconnects by the 3485 * client. 3486 * 3487 * The only safe way to call this function is to call it from the 3488 * #MHD_AccessHandlerCallback or #MHD_ContentReaderCallback. 3489 * 3490 * Finally, it is an API violation to call #MHD_stop_daemon while 3491 * having suspended connections (this will at least create memory and 3492 * socket leaks or lead to undefined behavior). You must explicitly 3493 * resume all connections before stopping the daemon. 3494 * 3495 * @param connection the connection to suspend 3496 * 3497 * @sa #MHD_AccessHandlerCallback 3498 */ 3499 _MHD_EXTERN void 3500 MHD_suspend_connection (struct MHD_Connection *connection) 3501 { 3502 struct MHD_Daemon *const daemon = connection->daemon; 3503 3504 #ifdef MHD_USE_THREADS 3505 mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ 3506 MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) || \ 3507 MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); 3508 #endif /* MHD_USE_THREADS */ 3509 3510 if (0 == (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) 3511 MHD_PANIC (_ ("Cannot suspend connections without " \ 3512 "enabling MHD_ALLOW_SUSPEND_RESUME!\n")); 3513 #ifdef UPGRADE_SUPPORT 3514 if (NULL != connection->urh) 3515 { 3516 #ifdef HAVE_MESSAGES 3517 MHD_DLOG (daemon, 3518 _ ("Error: connection scheduled for \"upgrade\" cannot " \ 3519 "be suspended.\n")); 3520 #endif /* HAVE_MESSAGES */ 3521 return; 3522 } 3523 #endif /* UPGRADE_SUPPORT */ 3524 internal_suspend_connection_ (connection); 3525 } 3526 3527 3528 /** 3529 * Resume handling of network data for suspended connection. It is 3530 * safe to resume a suspended connection at any time. Calling this 3531 * function on a connection that was not previously suspended will 3532 * result in undefined behavior. 3533 * 3534 * If you are using this function in "external" sockets polling mode, you must 3535 * make sure to run #MHD_run() and #MHD_get_timeout() afterwards (before 3536 * again calling #MHD_get_fdset()), as otherwise the change may not be 3537 * reflected in the set returned by #MHD_get_fdset() and you may end up 3538 * with a connection that is stuck until the next network activity. 3539 * 3540 * @param connection the connection to resume 3541 */ 3542 _MHD_EXTERN void 3543 MHD_resume_connection (struct MHD_Connection *connection) 3544 { 3545 struct MHD_Daemon *daemon = connection->daemon; 3546 bool own_thread; /**< The connection's own thread completes the resume */ 3547 #if defined(MHD_USE_THREADS) 3548 mhd_assert (NULL == daemon->worker_pool); 3549 #endif /* MHD_USE_THREADS */ 3550 3551 if (0 == (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) 3552 MHD_PANIC (_ ("Cannot resume connections without enabling " \ 3553 "MHD_ALLOW_SUSPEND_RESUME!\n")); 3554 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 3555 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); 3556 #endif 3557 connection->resuming = true; 3558 /* An "upgraded" connection is resumed only to be moved to the cleanup 3559 list, which is the daemon thread's job even with a thread per 3560 connection. */ 3561 own_thread = MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) 3562 #ifdef UPGRADE_SUPPORT 3563 && (NULL == connection->urh) 3564 #endif /* UPGRADE_SUPPORT */ 3565 ; 3566 if (! own_thread) 3567 daemon->resuming = true; 3568 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 3569 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); 3570 #endif 3571 if (own_thread) 3572 { 3573 /* Wake the connection's own thread. See the description of 3574 @e resume_itc for why the daemon-wide ITC will not do. */ 3575 mhd_assert (MHD_ITC_IS_VALID_ (connection->resume_itc)); 3576 if (! MHD_itc_activate_ (connection->resume_itc, "r")) 3577 { 3578 #ifdef HAVE_MESSAGES 3579 MHD_DLOG (daemon, 3580 _ ("Failed to signal resume via the connection's " \ 3581 "inter-thread communication channel.\n")); 3582 #endif 3583 } 3584 } 3585 else if ( (MHD_ITC_IS_VALID_ (daemon->itc)) && 3586 (! MHD_itc_activate_ (daemon->itc, "r")) ) 3587 { 3588 #ifdef HAVE_MESSAGES 3589 MHD_DLOG (daemon, 3590 _ ("Failed to signal resume via inter-thread " \ 3591 "communication channel.\n")); 3592 #endif 3593 } 3594 } 3595 3596 3597 #ifdef UPGRADE_SUPPORT 3598 /** 3599 * Mark upgraded connection as closed by application. 3600 * 3601 * The @a connection pointer must not be used after call of this function 3602 * as it may be freed in other thread immediately. 3603 * @param connection the upgraded connection to mark as closed by application 3604 */ 3605 void 3606 MHD_upgraded_connection_mark_app_closed_ (struct MHD_Connection *connection) 3607 { 3608 /* Cache 'daemon' here to avoid data races */ 3609 struct MHD_Daemon *const daemon = connection->daemon; 3610 #if defined(MHD_USE_THREADS) 3611 mhd_assert (NULL == daemon->worker_pool); 3612 #endif /* MHD_USE_THREADS */ 3613 mhd_assert (NULL != connection->urh); 3614 mhd_assert (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)); 3615 3616 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); 3617 connection->urh->was_closed = true; 3618 connection->resuming = true; 3619 daemon->resuming = true; 3620 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); 3621 if ( (MHD_ITC_IS_VALID_ (daemon->itc)) && 3622 (! MHD_itc_activate_ (daemon->itc, "r")) ) 3623 { 3624 #ifdef HAVE_MESSAGES 3625 MHD_DLOG (daemon, 3626 _ ("Failed to signal resume via " \ 3627 "inter-thread communication channel.\n")); 3628 #endif 3629 } 3630 } 3631 3632 3633 #endif /* UPGRADE_SUPPORT */ 3634 3635 /** 3636 * Run through the suspended connections and move any that are no 3637 * longer suspended back to the active state. 3638 * @remark To be called only from thread that process 3639 * daemon's select()/poll()/etc. 3640 * 3641 * @param daemon daemon context 3642 * @return #MHD_YES if a connection was actually resumed 3643 */ 3644 static enum MHD_Result 3645 resume_suspended_connections (struct MHD_Daemon *daemon) 3646 { 3647 struct MHD_Connection *pos; 3648 struct MHD_Connection *prev = NULL; 3649 enum MHD_Result ret; 3650 const bool used_thr_p_c = (0 != (daemon->options 3651 & MHD_USE_THREAD_PER_CONNECTION)); 3652 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 3653 mhd_assert (NULL == daemon->worker_pool); 3654 mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ 3655 MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); 3656 #endif 3657 3658 ret = MHD_NO; 3659 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 3660 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); 3661 #endif 3662 3663 if (daemon->resuming) 3664 { 3665 prev = daemon->suspended_connections_tail; 3666 /* During shutdown check for resuming is forced. */ 3667 mhd_assert ((NULL != prev) || (daemon->shutdown) || \ 3668 (0 != (daemon->options & MHD_ALLOW_UPGRADE))); 3669 } 3670 3671 daemon->resuming = false; 3672 3673 while (NULL != (pos = prev)) 3674 { 3675 #ifdef UPGRADE_SUPPORT 3676 struct MHD_UpgradeResponseHandle *const urh = pos->urh; 3677 #else /* ! UPGRADE_SUPPORT */ 3678 static const void *const urh = NULL; 3679 #endif /* ! UPGRADE_SUPPORT */ 3680 prev = pos->prev; 3681 if ( (! pos->resuming) 3682 #ifdef UPGRADE_SUPPORT 3683 || ( (NULL != urh) && 3684 ( (! urh->was_closed) || 3685 (! urh->clean_ready) ) ) 3686 #endif /* UPGRADE_SUPPORT */ 3687 ) 3688 continue; 3689 ret = MHD_YES; 3690 mhd_assert (pos->suspended); 3691 DLL_remove (daemon->suspended_connections_head, 3692 daemon->suspended_connections_tail, 3693 pos); 3694 pos->suspended = false; 3695 if (NULL == urh) 3696 { 3697 DLL_insert (daemon->connections_head, 3698 daemon->connections_tail, 3699 pos); 3700 if (! used_thr_p_c) 3701 { 3702 /* The states of a suspended connection are not updated, so they 3703 are stale now that it is running again. Updating them here 3704 would mean running the state machine under the cleanup mutex, 3705 which is what 0ecf4f26e4c1a4c03d66e1d04bf4cae62bd236a0 backed 3706 out of; flag the connection instead and let call_handlers() 3707 update it before it acts on @e event_loop_info. Thread-per- 3708 connection does the same for itself, in 3709 thread_main_handle_connection(). */ 3710 pos->resumed = true; 3711 3712 /* Reset timeout timer on resume. */ 3713 if (0 != pos->connection_timeout_ms) 3714 pos->last_activity = MHD_monotonic_msec_counter (); 3715 3716 if (pos->connection_timeout_ms == daemon->connection_timeout_ms) 3717 XDLL_insert (daemon->normal_timeout_head, 3718 daemon->normal_timeout_tail, 3719 pos); 3720 else 3721 XDLL_insert (daemon->manual_timeout_head, 3722 daemon->manual_timeout_tail, 3723 pos); 3724 } 3725 #ifdef EPOLL_SUPPORT 3726 if (MHD_D_IS_USING_EPOLL_ (daemon)) 3727 { 3728 if (0 != (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL)) 3729 MHD_PANIC ("Resumed connection was already in EREADY set.\n"); 3730 /* we always mark resumed connections as ready, as we 3731 might have missed the edge poll event during suspension */ 3732 EDLL_insert (daemon->eready_head, 3733 daemon->eready_tail, 3734 pos); 3735 pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL \ 3736 | MHD_EPOLL_STATE_READ_READY 3737 | MHD_EPOLL_STATE_WRITE_READY; 3738 pos->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_SUSPENDED); 3739 } 3740 #endif 3741 } 3742 #ifdef UPGRADE_SUPPORT 3743 else 3744 { 3745 /* Data forwarding was finished (for TLS connections) AND 3746 * application was closed upgraded connection. 3747 * Insert connection into cleanup list. */ 3748 if ( (NULL != daemon->notify_completed) && 3749 (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) && 3750 (pos->rq.client_aware) ) 3751 { 3752 daemon->notify_completed (daemon->notify_completed_cls, 3753 pos, 3754 &pos->rq.client_context, 3755 MHD_REQUEST_TERMINATED_COMPLETED_OK); 3756 pos->rq.client_aware = false; 3757 } 3758 DLL_insert (daemon->cleanup_head, 3759 daemon->cleanup_tail, 3760 pos); 3761 daemon->data_already_pending = true; 3762 } 3763 #endif /* UPGRADE_SUPPORT */ 3764 pos->resuming = false; 3765 } 3766 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 3767 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); 3768 #endif 3769 if ( (used_thr_p_c) && 3770 (MHD_NO != ret) ) 3771 { /* Wake up suspended connections. */ 3772 if (! MHD_itc_activate_ (daemon->itc, 3773 "w")) 3774 { 3775 #ifdef HAVE_MESSAGES 3776 MHD_DLOG (daemon, 3777 _ ("Failed to signal resume of connection via " \ 3778 "inter-thread communication channel.\n")); 3779 #endif 3780 } 3781 } 3782 return ret; 3783 } 3784 3785 3786 /** 3787 * Add another client connection to the set of connections managed by 3788 * MHD. This API is usually not needed (since MHD will accept inbound 3789 * connections on the server socket). Use this API in special cases, 3790 * for example if your HTTP server is behind NAT and needs to connect 3791 * out to the HTTP client, or if you are building a proxy. 3792 * 3793 * If you use this API in conjunction with a internal select or a 3794 * thread pool, you must set the option 3795 * #MHD_USE_ITC to ensure that the freshly added 3796 * connection is immediately processed by MHD. 3797 * 3798 * The given client socket will be managed (and closed!) by MHD after 3799 * this call and must no longer be used directly by the application 3800 * afterwards. 3801 * 3802 * @param daemon daemon that manages the connection 3803 * @param client_socket socket to manage (MHD will expect 3804 * to receive an HTTP request from this socket next). 3805 * @param addr IP address of the client 3806 * @param addrlen number of bytes in @a addr 3807 * @return #MHD_YES on success, #MHD_NO if this daemon could 3808 * not handle the connection (i.e. malloc() failed, etc). 3809 * The socket will be closed in any case; `errno` is 3810 * set to indicate further details about the error. 3811 * @ingroup specialized 3812 */ 3813 _MHD_EXTERN enum MHD_Result 3814 MHD_add_connection (struct MHD_Daemon *daemon, 3815 MHD_socket client_socket, 3816 const struct sockaddr *addr, 3817 socklen_t addrlen) 3818 { 3819 bool sk_nonbl; 3820 bool sk_spipe_supprs; 3821 struct sockaddr_storage addrstorage; 3822 3823 /* TODO: fix atomic value reading */ 3824 if ((! MHD_D_IS_THREAD_SAFE_ (daemon)) && 3825 (daemon->connection_limit <= daemon->connections)) 3826 MHD_cleanup_connections (daemon); 3827 3828 #ifdef HAVE_MESSAGES 3829 if (MHD_D_IS_USING_THREADS_ (daemon) && 3830 (0 == (daemon->options & MHD_USE_ITC))) 3831 { 3832 MHD_DLOG (daemon, 3833 _ ("MHD_add_connection() has been called for daemon started" 3834 " without MHD_USE_ITC flag.\nDaemon will not process newly" 3835 " added connection until any activity occurs in already" 3836 " added sockets.\n")); 3837 } 3838 #endif /* HAVE_MESSAGES */ 3839 if (0 != addrlen) 3840 { 3841 if (AF_INET == addr->sa_family) 3842 { 3843 if (sizeof(struct sockaddr_in) > (size_t) addrlen) 3844 { 3845 #ifdef HAVE_MESSAGES 3846 MHD_DLOG (daemon, 3847 _ ("MHD_add_connection() has been called with " 3848 "incorrect 'addrlen' value.\n")); 3849 #endif /* HAVE_MESSAGES */ 3850 return MHD_NO; 3851 } 3852 #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN 3853 if ((0 != addr->sa_len) && 3854 (sizeof(struct sockaddr_in) > (size_t) addr->sa_len) ) 3855 { 3856 #ifdef HAVE_MESSAGES 3857 MHD_DLOG (daemon, 3858 _ ("MHD_add_connection() has been called with " \ 3859 "non-zero value of 'sa_len' member of " \ 3860 "'struct sockaddr' which does not match 'sa_family'.\n")); 3861 #endif /* HAVE_MESSAGES */ 3862 return MHD_NO; 3863 } 3864 #endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */ 3865 } 3866 #ifdef HAVE_INET6 3867 if (AF_INET6 == addr->sa_family) 3868 { 3869 if (sizeof(struct sockaddr_in6) > (size_t) addrlen) 3870 { 3871 #ifdef HAVE_MESSAGES 3872 MHD_DLOG (daemon, 3873 _ ("MHD_add_connection() has been called with " 3874 "incorrect 'addrlen' value.\n")); 3875 #endif /* HAVE_MESSAGES */ 3876 return MHD_NO; 3877 } 3878 #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN 3879 if ((0 != addr->sa_len) && 3880 (sizeof(struct sockaddr_in6) > (size_t) addr->sa_len) ) 3881 { 3882 #ifdef HAVE_MESSAGES 3883 MHD_DLOG (daemon, 3884 _ ("MHD_add_connection() has been called with " \ 3885 "non-zero value of 'sa_len' member of " \ 3886 "'struct sockaddr' which does not match 'sa_family'.\n")); 3887 #endif /* HAVE_MESSAGES */ 3888 return MHD_NO; 3889 } 3890 #endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */ 3891 } 3892 #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN 3893 if ((0 != addr->sa_len) && 3894 (addrlen > addr->sa_len)) 3895 addrlen = (socklen_t) addr->sa_len; /* Use safest value */ 3896 #endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */ 3897 #endif /* HAVE_INET6 */ 3898 } 3899 3900 if (! MHD_socket_nonblocking_ (client_socket)) 3901 { 3902 #ifdef HAVE_MESSAGES 3903 MHD_DLOG (daemon, 3904 _ ("Failed to set nonblocking mode on new client socket: %s\n"), 3905 MHD_socket_last_strerr_ ()); 3906 #endif 3907 sk_nonbl = false; 3908 } 3909 else 3910 sk_nonbl = true; 3911 3912 #ifndef MHD_WINSOCK_SOCKETS 3913 sk_spipe_supprs = false; 3914 #else /* MHD_WINSOCK_SOCKETS */ 3915 sk_spipe_supprs = true; /* Nothing to suppress on W32 */ 3916 #endif /* MHD_WINSOCK_SOCKETS */ 3917 #if defined(MHD_socket_nosignal_) 3918 if (! sk_spipe_supprs) 3919 sk_spipe_supprs = MHD_socket_nosignal_ (client_socket); 3920 if (! sk_spipe_supprs) 3921 { 3922 #ifdef HAVE_MESSAGES 3923 MHD_DLOG (daemon, 3924 _ ("Failed to suppress SIGPIPE on new client socket: %s\n"), 3925 MHD_socket_last_strerr_ ()); 3926 #else /* ! HAVE_MESSAGES */ 3927 (void) 0; /* Mute compiler warning */ 3928 #endif /* ! HAVE_MESSAGES */ 3929 #ifndef MSG_NOSIGNAL 3930 /* Application expects that SIGPIPE will be suppressed, 3931 * but suppression failed and SIGPIPE cannot be suppressed with send(). */ 3932 if (! daemon->sigpipe_blocked) 3933 { 3934 int err = MHD_socket_get_error_ (); 3935 MHD_socket_close_ (client_socket); 3936 MHD_socket_fset_error_ (err); 3937 return MHD_NO; 3938 } 3939 #endif /* MSG_NOSIGNAL */ 3940 } 3941 #endif /* MHD_socket_nosignal_ */ 3942 3943 if ( (0 != (daemon->options & MHD_USE_TURBO)) && 3944 (! MHD_socket_noninheritable_ (client_socket)) ) 3945 { 3946 #ifdef HAVE_MESSAGES 3947 MHD_DLOG (daemon, 3948 _ ("Failed to set noninheritable mode on new client socket.\n")); 3949 #endif 3950 } 3951 3952 /* Copy to sockaddr_storage structure to avoid alignment problems */ 3953 if (0 < addrlen) 3954 memcpy (&addrstorage, addr, (size_t) addrlen); 3955 #ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN 3956 addrstorage.ss_len = addrlen; /* Force set the right length */ 3957 #endif /* HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN */ 3958 3959 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 3960 if (NULL != daemon->worker_pool) 3961 { 3962 unsigned int i; 3963 /* have a pool, try to find a pool with capacity; we use the 3964 socket as the initial offset into the pool for load 3965 balancing */ 3966 for (i = 0; i < daemon->worker_pool_size; ++i) 3967 { 3968 struct MHD_Daemon *const worker = 3969 &daemon->worker_pool[(i + (unsigned int) client_socket) 3970 % daemon->worker_pool_size]; 3971 if (worker->connections < worker->connection_limit) 3972 return internal_add_connection (worker, 3973 client_socket, 3974 &addrstorage, 3975 addrlen, 3976 true, 3977 sk_nonbl, 3978 sk_spipe_supprs, 3979 _MHD_UNKNOWN); 3980 } 3981 /* all pools are at their connection limit, must refuse */ 3982 MHD_socket_close_chk_ (client_socket); 3983 #if defined(ENFILE) && (ENFILE + 0 != 0) 3984 errno = ENFILE; 3985 #endif 3986 return MHD_NO; 3987 } 3988 #endif /* MHD_USE_POSIX_THREADS || MHD_USE_W32_THREADS */ 3989 3990 return internal_add_connection (daemon, 3991 client_socket, 3992 &addrstorage, 3993 addrlen, 3994 true, 3995 sk_nonbl, 3996 sk_spipe_supprs, 3997 _MHD_UNKNOWN); 3998 } 3999 4000 4001 /** 4002 * Accept an incoming connection and create the MHD_Connection object for 4003 * it. This function also enforces policy by way of checking with the 4004 * accept policy callback. 4005 * @remark To be called only from thread that process 4006 * daemon's select()/poll()/etc. 4007 * 4008 * @param daemon handle with the listen socket 4009 * @return #MHD_YES on success (connections denied by policy or due 4010 * to 'out of memory' and similar errors) are still considered 4011 * successful as far as #MHD_accept_connection() is concerned); 4012 * a return code of #MHD_NO only refers to the actual 4013 * accept() system call. 4014 */ 4015 static enum MHD_Result 4016 MHD_accept_connection (struct MHD_Daemon *daemon) 4017 { 4018 struct sockaddr_storage addrstorage; 4019 socklen_t addrlen; 4020 MHD_socket s; 4021 MHD_socket fd; 4022 bool sk_nonbl; 4023 bool sk_spipe_supprs; 4024 bool sk_cloexec; 4025 enum MHD_tristate sk_non_ip; 4026 #if defined(_DEBUG) && defined (USE_ACCEPT4) 4027 const bool use_accept4 = ! daemon->avoid_accept4; 4028 #elif defined (USE_ACCEPT4) 4029 static const bool use_accept4 = true; 4030 #else /* ! USE_ACCEPT4 && ! _DEBUG */ 4031 static const bool use_accept4 = false; 4032 #endif /* ! USE_ACCEPT4 && ! _DEBUG */ 4033 4034 #ifdef MHD_USE_THREADS 4035 mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ 4036 MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); 4037 mhd_assert (NULL == daemon->worker_pool); 4038 #endif /* MHD_USE_THREADS */ 4039 4040 if ( (MHD_INVALID_SOCKET == (fd = daemon->listen_fd)) || 4041 (daemon->was_quiesced) ) 4042 return MHD_NO; 4043 4044 addrlen = (socklen_t) sizeof (addrstorage); 4045 memset (&addrstorage, 4046 0, 4047 (size_t) addrlen); 4048 #ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN 4049 addrstorage.ss_len = addrlen; 4050 #endif /* HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN */ 4051 4052 /* Initialise with default values to avoid compiler warnings */ 4053 sk_nonbl = false; 4054 sk_spipe_supprs = false; 4055 sk_cloexec = false; 4056 s = MHD_INVALID_SOCKET; 4057 4058 #ifdef USE_ACCEPT4 4059 if (use_accept4 && 4060 (MHD_INVALID_SOCKET != 4061 (s = accept4 (fd, 4062 (struct sockaddr *) &addrstorage, 4063 &addrlen, 4064 SOCK_CLOEXEC_OR_ZERO | SOCK_NONBLOCK_OR_ZERO 4065 | SOCK_NOSIGPIPE_OR_ZERO)))) 4066 { 4067 sk_nonbl = (SOCK_NONBLOCK_OR_ZERO != 0); 4068 #ifndef MHD_WINSOCK_SOCKETS 4069 sk_spipe_supprs = (SOCK_NOSIGPIPE_OR_ZERO != 0); 4070 #else /* MHD_WINSOCK_SOCKETS */ 4071 sk_spipe_supprs = true; /* Nothing to suppress on W32 */ 4072 #endif /* MHD_WINSOCK_SOCKETS */ 4073 sk_cloexec = (SOCK_CLOEXEC_OR_ZERO != 0); 4074 } 4075 #endif /* USE_ACCEPT4 */ 4076 #if defined(_DEBUG) || ! defined(USE_ACCEPT4) 4077 if (! use_accept4 && 4078 (MHD_INVALID_SOCKET != 4079 (s = accept (fd, 4080 (struct sockaddr *) &addrstorage, 4081 &addrlen)))) 4082 { 4083 #ifdef MHD_ACCEPT_INHERIT_NONBLOCK 4084 sk_nonbl = daemon->listen_nonblk; 4085 #else /* ! MHD_ACCEPT_INHERIT_NONBLOCK */ 4086 sk_nonbl = false; 4087 #endif /* ! MHD_ACCEPT_INHERIT_NONBLOCK */ 4088 #ifndef MHD_WINSOCK_SOCKETS 4089 sk_spipe_supprs = false; 4090 #else /* MHD_WINSOCK_SOCKETS */ 4091 sk_spipe_supprs = true; /* Nothing to suppress on W32 */ 4092 #endif /* MHD_WINSOCK_SOCKETS */ 4093 sk_cloexec = false; 4094 } 4095 #endif /* _DEBUG || !USE_ACCEPT4 */ 4096 4097 if (MHD_INVALID_SOCKET == s) 4098 { 4099 const int err = MHD_socket_get_error_ (); 4100 4101 /* This could be a common occurrence with multiple worker threads */ 4102 if (MHD_SCKT_ERR_IS_ (err, 4103 MHD_SCKT_EINVAL_)) 4104 return MHD_NO; /* can happen during shutdown */ 4105 if (MHD_SCKT_ERR_IS_DISCNN_BEFORE_ACCEPT_ (err)) 4106 return MHD_NO; /* do not print error if client just disconnected early */ 4107 #ifdef HAVE_MESSAGES 4108 if (! MHD_SCKT_ERR_IS_EAGAIN_ (err) ) 4109 MHD_DLOG (daemon, 4110 _ ("Error accepting connection: %s\n"), 4111 MHD_socket_strerr_ (err)); 4112 #endif 4113 if (MHD_SCKT_ERR_IS_LOW_RESOURCES_ (err) ) 4114 { 4115 /* system/process out of resources */ 4116 if (0 == daemon->connections) 4117 { 4118 #ifdef HAVE_MESSAGES 4119 /* Not setting 'at_limit' flag, as there is no way it 4120 would ever be cleared. Instead trying to produce 4121 bit fat ugly warning. */ 4122 MHD_DLOG (daemon, 4123 _ ("Hit process or system resource limit at FIRST " \ 4124 "connection. This is really bad as there is no sane " \ 4125 "way to proceed. Will try busy waiting for system " \ 4126 "resources to become magically available.\n")); 4127 #endif 4128 } 4129 else 4130 { 4131 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 4132 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); 4133 #endif 4134 daemon->at_limit = true; 4135 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 4136 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); 4137 #endif 4138 #ifdef HAVE_MESSAGES 4139 MHD_DLOG (daemon, 4140 _ ("Hit process or system resource limit at %u " \ 4141 "connections, temporarily suspending accept(). " \ 4142 "Consider setting a lower MHD_OPTION_CONNECTION_LIMIT.\n"), 4143 (unsigned int) daemon->connections); 4144 #endif 4145 } 4146 } 4147 return MHD_NO; 4148 } 4149 4150 sk_non_ip = daemon->listen_is_unix; 4151 if (0 >= addrlen) 4152 { 4153 #ifdef HAVE_MESSAGES 4154 if (_MHD_NO != daemon->listen_is_unix) 4155 MHD_DLOG (daemon, 4156 _ ("Accepted socket has zero-length address. " 4157 "Processing the new socket as a socket with " \ 4158 "unknown type.\n")); 4159 #endif 4160 addrlen = 0; 4161 sk_non_ip = _MHD_YES; /* IP-type addresses have non-zero length */ 4162 } 4163 if (((socklen_t) sizeof (addrstorage)) < addrlen) 4164 { 4165 /* Should not happen as 'sockaddr_storage' must be large enough to 4166 * store any address supported by the system. */ 4167 #ifdef HAVE_MESSAGES 4168 MHD_DLOG (daemon, 4169 _ ("Accepted socket address is larger than expected by " \ 4170 "system headers. Processing the new socket as a socket with " \ 4171 "unknown type.\n")); 4172 #endif 4173 addrlen = 0; 4174 sk_non_ip = _MHD_YES; /* IP-type addresses must fit */ 4175 } 4176 4177 if (! sk_nonbl && ! MHD_socket_nonblocking_ (s)) 4178 { 4179 #ifdef HAVE_MESSAGES 4180 MHD_DLOG (daemon, 4181 _ ("Failed to set nonblocking mode on incoming connection " \ 4182 "socket: %s\n"), 4183 MHD_socket_last_strerr_ ()); 4184 #else /* ! HAVE_MESSAGES */ 4185 (void) 0; /* Mute compiler warning */ 4186 #endif /* ! HAVE_MESSAGES */ 4187 } 4188 else 4189 sk_nonbl = true; 4190 4191 if (! sk_cloexec && ! MHD_socket_noninheritable_ (s)) 4192 { 4193 #ifdef HAVE_MESSAGES 4194 MHD_DLOG (daemon, 4195 _ ("Failed to set noninheritable mode on incoming connection " \ 4196 "socket.\n")); 4197 #else /* ! HAVE_MESSAGES */ 4198 (void) 0; /* Mute compiler warning */ 4199 #endif /* ! HAVE_MESSAGES */ 4200 } 4201 4202 #if defined(MHD_socket_nosignal_) 4203 if (! sk_spipe_supprs && ! MHD_socket_nosignal_ (s)) 4204 { 4205 #ifdef HAVE_MESSAGES 4206 MHD_DLOG (daemon, 4207 _ ("Failed to suppress SIGPIPE on incoming connection " \ 4208 "socket: %s\n"), 4209 MHD_socket_last_strerr_ ()); 4210 #else /* ! HAVE_MESSAGES */ 4211 (void) 0; /* Mute compiler warning */ 4212 #endif /* ! HAVE_MESSAGES */ 4213 #ifndef MSG_NOSIGNAL 4214 /* Application expects that SIGPIPE will be suppressed, 4215 * but suppression failed and SIGPIPE cannot be suppressed with send(). */ 4216 if (! daemon->sigpipe_blocked) 4217 { 4218 (void) MHD_socket_close_ (s); 4219 return MHD_NO; 4220 } 4221 #endif /* MSG_NOSIGNAL */ 4222 } 4223 else 4224 sk_spipe_supprs = true; 4225 #endif /* MHD_socket_nosignal_ */ 4226 #ifdef HAVE_MESSAGES 4227 #if _MHD_DEBUG_CONNECT 4228 MHD_DLOG (daemon, 4229 _ ("Accepted connection on socket %d\n"), 4230 s); 4231 #endif 4232 #endif 4233 (void) internal_add_connection (daemon, 4234 s, 4235 &addrstorage, 4236 addrlen, 4237 false, 4238 sk_nonbl, 4239 sk_spipe_supprs, 4240 sk_non_ip); 4241 return MHD_YES; 4242 } 4243 4244 4245 /** 4246 * Free resources associated with all closed connections. 4247 * (destroy responses, free buffers, etc.). All closed 4248 * connections are kept in the "cleanup" doubly-linked list. 4249 * @remark To be called only from thread that 4250 * process daemon's select()/poll()/etc. 4251 * 4252 * @param daemon daemon to clean up 4253 */ 4254 static void 4255 MHD_cleanup_connections (struct MHD_Daemon *daemon) 4256 { 4257 struct MHD_Connection *pos; 4258 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 4259 mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ 4260 MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); 4261 mhd_assert (NULL == daemon->worker_pool); 4262 4263 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); 4264 #endif 4265 while (NULL != (pos = daemon->cleanup_tail)) 4266 { 4267 DLL_remove (daemon->cleanup_head, 4268 daemon->cleanup_tail, 4269 pos); 4270 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 4271 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); 4272 if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) && 4273 (! pos->thread_joined) && 4274 (! MHD_thread_handle_ID_join_thread_ (pos->tid)) ) 4275 MHD_PANIC (_ ("Failed to join a thread.\n")); 4276 #endif 4277 #ifdef UPGRADE_SUPPORT 4278 cleanup_upgraded_connection (pos); 4279 #endif /* UPGRADE_SUPPORT */ 4280 MHD_pool_destroy (pos->pool); 4281 #ifdef HTTPS_SUPPORT 4282 if (NULL != pos->tls_session) 4283 gnutls_deinit (pos->tls_session); 4284 #endif /* HTTPS_SUPPORT */ 4285 4286 /* clean up the connection */ 4287 if (NULL != daemon->notify_connection) 4288 daemon->notify_connection (daemon->notify_connection_cls, 4289 pos, 4290 &pos->socket_context, 4291 MHD_CONNECTION_NOTIFY_CLOSED); 4292 MHD_ip_limit_del (daemon, 4293 pos->addr, 4294 pos->addr_len); 4295 #ifdef EPOLL_SUPPORT 4296 if (MHD_D_IS_USING_EPOLL_ (daemon)) 4297 { 4298 if (0 != (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL)) 4299 { 4300 EDLL_remove (daemon->eready_head, 4301 daemon->eready_tail, 4302 pos); 4303 pos->epoll_state &= 4304 ~((enum MHD_EpollState) MHD_EPOLL_STATE_IN_EREADY_EDLL); 4305 } 4306 if ( (-1 != daemon->epoll_fd) && 4307 (0 != (pos->epoll_state & MHD_EPOLL_STATE_IN_EPOLL_SET)) ) 4308 { 4309 /* epoll documentation suggests that closing a FD 4310 automatically removes it from the epoll set; however, 4311 this is not true as if we fail to do manually remove it, 4312 we are still seeing an event for this fd in epoll, 4313 causing grief (use-after-free...) --- at least on my 4314 system. */ 4315 if (0 != epoll_ctl (daemon->epoll_fd, 4316 EPOLL_CTL_DEL, 4317 pos->socket_fd, 4318 NULL)) 4319 MHD_PANIC (_ ("Failed to remove FD from epoll set.\n")); 4320 pos->epoll_state &= 4321 ~((enum MHD_EpollState) 4322 MHD_EPOLL_STATE_IN_EPOLL_SET); 4323 } 4324 } 4325 #endif 4326 if (NULL != pos->rp.response) 4327 { 4328 MHD_destroy_response (pos->rp.response); 4329 pos->rp.response = NULL; 4330 } 4331 if (MHD_INVALID_SOCKET != pos->socket_fd) 4332 MHD_socket_close_chk_ (pos->socket_fd); 4333 if (MHD_ITC_IS_VALID_ (pos->resume_itc)) 4334 MHD_itc_destroy_chk_ (pos->resume_itc); 4335 if (NULL != pos->addr) 4336 free (pos->addr); 4337 free (pos); 4338 4339 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 4340 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); 4341 #endif 4342 daemon->connections--; 4343 daemon->at_limit = false; 4344 } 4345 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 4346 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); 4347 #endif 4348 } 4349 4350 4351 /** 4352 * Obtain timeout value for polling function for this daemon. 4353 * 4354 * This function set value to the amount of milliseconds for which polling 4355 * function (`select()`, `poll()` or epoll) should at most block, not the 4356 * timeout value set for connections. 4357 * 4358 * Any "external" sockets polling function must be called with the timeout 4359 * value provided by this function. Smaller timeout values can be used for 4360 * polling function if it is required for any reason, but using larger 4361 * timeout value or no timeout (indefinite timeout) when this function 4362 * return #MHD_YES will break MHD processing logic and result in "hung" 4363 * connections with data pending in network buffers and other problems. 4364 * 4365 * It is important to always use this function (or #MHD_get_timeout64(), 4366 * #MHD_get_timeout64s(), #MHD_get_timeout_i() functions) when "external" 4367 * polling is used. 4368 * If this function returns #MHD_YES then #MHD_run() (or #MHD_run_from_select()) 4369 * must be called right after return from polling function, regardless of 4370 * the states of MHD FDs. 4371 * 4372 * In practice, if #MHD_YES is returned then #MHD_run() (or 4373 * #MHD_run_from_select()) must be called not later than @a timeout 4374 * millisecond even if no activity is detected on sockets by sockets 4375 * polling function. 4376 * @remark To be called only from thread that process 4377 * daemon's select()/poll()/etc. 4378 * 4379 * @param daemon daemon to query for timeout 4380 * @param[out] timeout set to the timeout (in milliseconds) 4381 * @return #MHD_YES on success, #MHD_NO if timeouts are 4382 * not used and no data processing is pending. 4383 * @ingroup event 4384 */ 4385 _MHD_EXTERN enum MHD_Result 4386 MHD_get_timeout (struct MHD_Daemon *daemon, 4387 MHD_UNSIGNED_LONG_LONG *timeout) 4388 { 4389 uint64_t t64; 4390 if (MHD_NO == MHD_get_timeout64 (daemon, &t64)) 4391 return MHD_NO; 4392 4393 #if SIZEOF_UINT64_T > SIZEOF_UNSIGNED_LONG_LONG 4394 if (ULLONG_MAX <= t64) 4395 *timeout = ULLONG_MAX; 4396 else 4397 #endif /* SIZEOF_UINT64_T > SIZEOF_UNSIGNED_LONG_LONG */ 4398 *timeout = (MHD_UNSIGNED_LONG_LONG) t64; 4399 return MHD_YES; 4400 } 4401 4402 4403 /** 4404 * Obtain timeout value for external polling function for this daemon. 4405 * 4406 * This function set value to the amount of milliseconds for which polling 4407 * function (`select()`, `poll()` or epoll) should at most block, not the 4408 * timeout value set for connections. 4409 * 4410 * Any "external" sockets polling function must be called with the timeout 4411 * value provided by this function. Smaller timeout values can be used for 4412 * polling function if it is required for any reason, but using larger 4413 * timeout value or no timeout (indefinite timeout) when this function 4414 * return #MHD_YES will break MHD processing logic and result in "hung" 4415 * connections with data pending in network buffers and other problems. 4416 * 4417 * It is important to always use this function (or #MHD_get_timeout(), 4418 * #MHD_get_timeout64s(), #MHD_get_timeout_i() functions) when "external" 4419 * polling is used. 4420 * If this function returns #MHD_YES then #MHD_run() (or #MHD_run_from_select()) 4421 * must be called right after return from polling function, regardless of 4422 * the states of MHD FDs. 4423 * 4424 * In practice, if #MHD_YES is returned then #MHD_run() (or 4425 * #MHD_run_from_select()) must be called not later than @a timeout 4426 * millisecond even if no activity is detected on sockets by sockets 4427 * polling function. 4428 * @remark To be called only from thread that process 4429 * daemon's select()/poll()/etc. 4430 * 4431 * @param daemon daemon to query for timeout 4432 * @param[out] timeout64 the pointer to the variable to be set to the 4433 * timeout (in milliseconds) 4434 * @return #MHD_YES if timeout value has been set, 4435 * #MHD_NO if timeouts are not used and no data processing is pending. 4436 * @note Available since #MHD_VERSION 0x00097701 4437 * @ingroup event 4438 */ 4439 _MHD_EXTERN enum MHD_Result 4440 MHD_get_timeout64 (struct MHD_Daemon *daemon, 4441 uint64_t *timeout64) 4442 { 4443 uint64_t earliest_deadline; 4444 struct MHD_Connection *pos; 4445 struct MHD_Connection *earliest_tmot_conn; /**< the connection with earliest timeout */ 4446 bool resuming; /**< the copy of @a daemon->resuming, read under the lock */ 4447 4448 #ifdef MHD_USE_THREADS 4449 mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ 4450 MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); 4451 #endif /* MHD_USE_THREADS */ 4452 4453 if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) 4454 { 4455 #ifdef HAVE_MESSAGES 4456 MHD_DLOG (daemon, 4457 _ ("Illegal call to MHD_get_timeout.\n")); 4458 #endif 4459 return MHD_NO; 4460 } 4461 /* Unlike the other flags checked below, which are touched only by the 4462 thread that processes this daemon's polling, 'resuming' is set by 4463 #MHD_resume_connection(), which the application may legally call from 4464 any thread. It is guarded by 'cleanup_connection_mutex' everywhere. */ 4465 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 4466 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); 4467 #endif 4468 resuming = daemon->resuming; 4469 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 4470 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); 4471 #endif 4472 if (daemon->data_already_pending 4473 || (NULL != daemon->cleanup_head) 4474 || resuming 4475 || daemon->have_new 4476 || daemon->shutdown) 4477 { 4478 /* Some data or connection statuses already waiting to be processed. */ 4479 *timeout64 = 0; 4480 return MHD_YES; 4481 } 4482 #ifdef EPOLL_SUPPORT 4483 if (MHD_D_IS_USING_EPOLL_ (daemon) && 4484 ((NULL != daemon->eready_head) 4485 #if defined(UPGRADE_SUPPORT) && defined(HTTPS_SUPPORT) 4486 || (NULL != daemon->eready_urh_head) 4487 #endif /* UPGRADE_SUPPORT && HTTPS_SUPPORT */ 4488 ) ) 4489 { 4490 /* Some connection(s) already have some data pending. */ 4491 *timeout64 = 0; 4492 return MHD_YES; 4493 } 4494 #endif /* EPOLL_SUPPORT */ 4495 4496 earliest_tmot_conn = NULL; 4497 earliest_deadline = 0; /* mute compiler warning */ 4498 /* normal timeouts are sorted, so we only need to look at the 'tail' (oldest) */ 4499 pos = daemon->normal_timeout_tail; 4500 if ( (NULL != pos) && 4501 (0 != pos->connection_timeout_ms) ) 4502 { 4503 earliest_tmot_conn = pos; 4504 earliest_deadline = pos->last_activity + pos->connection_timeout_ms; 4505 } 4506 4507 for (pos = daemon->manual_timeout_tail; 4508 NULL != pos; 4509 pos = pos->prevX) 4510 { 4511 if (0 != pos->connection_timeout_ms) 4512 { 4513 if ( (NULL == earliest_tmot_conn) || 4514 (earliest_deadline > 4515 pos->last_activity + pos->connection_timeout_ms) ) 4516 { 4517 earliest_tmot_conn = pos; 4518 earliest_deadline = pos->last_activity + pos->connection_timeout_ms; 4519 } 4520 } 4521 } 4522 4523 if (NULL != earliest_tmot_conn) 4524 { 4525 *timeout64 = connection_get_wait (earliest_tmot_conn); 4526 return MHD_YES; 4527 } 4528 return MHD_NO; 4529 } 4530 4531 4532 #if defined(HAVE_POLL) || defined(EPOLL_SUPPORT) 4533 /** 4534 * Obtain timeout value for external polling function for this daemon. 4535 * 4536 * This function set value to the amount of milliseconds for which polling 4537 * function (`select()`, `poll()` or epoll) should at most block, not the 4538 * timeout value set for connections. 4539 * 4540 * Any "external" sockets polling function must be called with the timeout 4541 * value provided by this function (if returned value is non-negative). 4542 * Smaller timeout values can be used for polling function if it is required 4543 * for any reason, but using larger timeout value or no timeout (indefinite 4544 * timeout) when this function returns non-negative value will break MHD 4545 * processing logic and result in "hung" connections with data pending in 4546 * network buffers and other problems. 4547 * 4548 * It is important to always use this function (or #MHD_get_timeout(), 4549 * #MHD_get_timeout64(), #MHD_get_timeout_i() functions) when "external" 4550 * polling is used. 4551 * If this function returns non-negative value then #MHD_run() (or 4552 * #MHD_run_from_select()) must be called right after return from polling 4553 * function, regardless of the states of MHD FDs. 4554 * 4555 * In practice, if zero or positive value is returned then #MHD_run() (or 4556 * #MHD_run_from_select()) must be called not later than returned amount of 4557 * millisecond even if no activity is detected on sockets by sockets 4558 * polling function. 4559 * @remark To be called only from thread that process 4560 * daemon's select()/poll()/etc. 4561 * 4562 * @param daemon the daemon to query for timeout 4563 * @return -1 if connections' timeouts are not set and no data processing 4564 * is pending, so external polling function may wait for sockets 4565 * activity for indefinite amount of time, 4566 * otherwise returned value is the the maximum amount of millisecond 4567 * that external polling function must wait for the activity of FDs. 4568 * @note Available since #MHD_VERSION 0x00097701 4569 * @ingroup event 4570 */ 4571 _MHD_EXTERN int64_t 4572 MHD_get_timeout64s (struct MHD_Daemon *daemon) 4573 { 4574 uint64_t utimeout; 4575 if (MHD_NO == MHD_get_timeout64 (daemon, &utimeout)) 4576 return -1; 4577 if (INT64_MAX < utimeout) 4578 return INT64_MAX; 4579 4580 return (int64_t) utimeout; 4581 } 4582 4583 4584 /** 4585 * Obtain timeout value for external polling function for this daemon. 4586 * 4587 * This function set value to the amount of milliseconds for which polling 4588 * function (`select()`, `poll()` or epoll) should at most block, not the 4589 * timeout value set for connections. 4590 * 4591 * Any "external" sockets polling function must be called with the timeout 4592 * value provided by this function (if returned value is non-negative). 4593 * Smaller timeout values can be used for polling function if it is required 4594 * for any reason, but using larger timeout value or no timeout (indefinite 4595 * timeout) when this function returns non-negative value will break MHD 4596 * processing logic and result in "hung" connections with data pending in 4597 * network buffers and other problems. 4598 * 4599 * It is important to always use this function (or #MHD_get_timeout(), 4600 * #MHD_get_timeout64(), #MHD_get_timeout64s() functions) when "external" 4601 * polling is used. 4602 * If this function returns non-negative value then #MHD_run() (or 4603 * #MHD_run_from_select()) must be called right after return from polling 4604 * function, regardless of the states of MHD FDs. 4605 * 4606 * In practice, if zero or positive value is returned then #MHD_run() (or 4607 * #MHD_run_from_select()) must be called not later than returned amount of 4608 * millisecond even if no activity is detected on sockets by sockets 4609 * polling function. 4610 * @remark To be called only from thread that process 4611 * daemon's select()/poll()/etc. 4612 * 4613 * @param daemon the daemon to query for timeout 4614 * @return -1 if connections' timeouts are not set and no data processing 4615 * is pending, so external polling function may wait for sockets 4616 * activity for indefinite amount of time, 4617 * otherwise returned value is the the maximum amount of millisecond 4618 * (capped at INT_MAX) that external polling function must wait 4619 * for the activity of FDs. 4620 * @note Available since #MHD_VERSION 0x00097701 4621 * @ingroup event 4622 */ 4623 _MHD_EXTERN int 4624 MHD_get_timeout_i (struct MHD_Daemon *daemon) 4625 { 4626 #if SIZEOF_INT >= SIZEOF_INT64_T 4627 return MHD_get_timeout64s (daemon); 4628 #else /* SIZEOF_INT < SIZEOF_INT64_T */ 4629 const int64_t to64 = MHD_get_timeout64s (daemon); 4630 if (INT_MAX >= to64) 4631 return (int) to64; 4632 return INT_MAX; 4633 #endif /* SIZEOF_INT < SIZEOF_INT64_T */ 4634 } 4635 4636 4637 /** 4638 * Obtain timeout value for polling function for this daemon. 4639 * @remark To be called only from the thread that processes 4640 * daemon's select()/poll()/etc. 4641 * 4642 * @param daemon the daemon to query for timeout 4643 * @param max_timeout the maximum return value (in milliseconds), 4644 * ignored if set to '-1' 4645 * @return timeout value in milliseconds or -1 if no timeout is expected. 4646 */ 4647 static int64_t 4648 get_timeout_millisec_ (struct MHD_Daemon *daemon, 4649 int32_t max_timeout) 4650 { 4651 uint64_t d_timeout; 4652 mhd_assert (0 <= max_timeout || -1 == max_timeout); 4653 if (0 == max_timeout) 4654 return 0; 4655 4656 if (MHD_NO == MHD_get_timeout64 (daemon, &d_timeout)) 4657 return max_timeout; 4658 4659 if ((0 < max_timeout) && ((uint64_t) max_timeout < d_timeout)) 4660 return max_timeout; 4661 4662 if (INT64_MAX <= d_timeout) 4663 return INT64_MAX; 4664 4665 return (int64_t) d_timeout; 4666 } 4667 4668 4669 /** 4670 * Obtain timeout value for polling function for this daemon. 4671 * @remark To be called only from the thread that processes 4672 * daemon's select()/poll()/etc. 4673 * 4674 * @param daemon the daemon to query for timeout 4675 * @param max_timeout the maximum return value (in milliseconds), 4676 * ignored if set to '-1' 4677 * @return timeout value in milliseconds, capped to INT_MAX, or 4678 * -1 if no timeout is expected. 4679 */ 4680 static int 4681 get_timeout_millisec_int (struct MHD_Daemon *daemon, 4682 int32_t max_timeout) 4683 { 4684 int64_t res; 4685 4686 res = get_timeout_millisec_ (daemon, max_timeout); 4687 #if SIZEOF_INT < SIZEOF_INT64_T 4688 if (INT_MAX <= res) 4689 return INT_MAX; 4690 #endif /* SIZEOF_INT < SIZEOF_INT64_T */ 4691 return (int) res; 4692 } 4693 4694 4695 #endif /* HAVE_POLL || EPOLL_SUPPORT */ 4696 4697 /** 4698 * Internal version of #MHD_run_from_select(). 4699 * 4700 * @param daemon daemon to run select loop for 4701 * @param read_fd_set read set 4702 * @param write_fd_set write set 4703 * @param except_fd_set except set 4704 * @param fd_setsize value of FD_SETSIZE used when fd_sets were created 4705 * @return #MHD_NO on serious errors, #MHD_YES on success 4706 * @ingroup event 4707 */ 4708 static enum MHD_Result 4709 internal_run_from_select (struct MHD_Daemon *daemon, 4710 const fd_set *read_fd_set, 4711 const fd_set *write_fd_set, 4712 const fd_set *except_fd_set, 4713 int fd_setsize) 4714 { 4715 MHD_socket ds; 4716 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) 4717 struct MHD_UpgradeResponseHandle *urh; 4718 struct MHD_UpgradeResponseHandle *urhn; 4719 #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ 4720 4721 mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ 4722 (MHD_thread_handle_ID_is_valid_ID_ (daemon->tid))); 4723 mhd_assert ((0 != (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ 4724 (! MHD_thread_handle_ID_is_valid_ID_ (daemon->tid))); 4725 mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ 4726 (MHD_thread_handle_ID_is_current_thread_ (daemon->tid))); 4727 4728 mhd_assert (0 < fd_setsize); 4729 (void) fd_setsize; /* Mute compiler warning */ 4730 #ifndef HAS_FD_SETSIZE_OVERRIDABLE 4731 (void) fd_setsize; /* Mute compiler warning */ 4732 mhd_assert (((int) FD_SETSIZE) <= fd_setsize); 4733 fd_setsize = FD_SETSIZE; /* Help compiler to optimise */ 4734 #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ 4735 4736 /* Clear ITC to avoid spinning select */ 4737 /* Do it before any other processing so new signals 4738 will trigger select again and will be processed */ 4739 if (MHD_ITC_IS_VALID_ (daemon->itc)) 4740 { /* Have ITC */ 4741 bool need_to_clear_itc = true; /* ITC is always non-blocking, it is safe to clear even if ITC not activated */ 4742 if (MHD_SCKT_FD_FITS_FDSET_SETSIZE_ (MHD_itc_r_fd_ (daemon->itc), 4743 NULL, fd_setsize)) 4744 need_to_clear_itc = FD_ISSET (MHD_itc_r_fd_ (daemon->itc), \ 4745 (fd_set *) _MHD_DROP_CONST (read_fd_set)); /* Skip clearing, if not needed */ 4746 if (need_to_clear_itc) 4747 MHD_itc_clear_ (daemon->itc); 4748 } 4749 4750 /* Reset. New value will be set when connections are processed. */ 4751 /* Note: no-op for thread-per-connection as it is always false in that mode. */ 4752 daemon->data_already_pending = false; 4753 4754 /* Process externally added connection if any */ 4755 if (daemon->have_new) 4756 new_connections_list_process_ (daemon); 4757 4758 /* select connection thread handling type */ 4759 ds = daemon->listen_fd; 4760 if ( (MHD_INVALID_SOCKET != ds) && 4761 (! daemon->was_quiesced) ) 4762 { 4763 bool need_to_accept; 4764 if (MHD_SCKT_FD_FITS_FDSET_SETSIZE_ (ds, NULL, fd_setsize)) 4765 need_to_accept = FD_ISSET (ds, 4766 (fd_set *) _MHD_DROP_CONST (read_fd_set)); 4767 else /* Cannot check whether new connection are pending */ 4768 need_to_accept = daemon->listen_nonblk; /* Try to accept if non-blocking */ 4769 4770 if (need_to_accept) 4771 (void) MHD_accept_connection (daemon); 4772 } 4773 4774 if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) 4775 { 4776 /* do not have a thread per connection, process all connections now */ 4777 struct MHD_Connection *pos; 4778 struct MHD_Connection *prev; 4779 4780 for (pos = daemon->connections_tail; NULL != pos; pos = prev) 4781 { 4782 MHD_socket cs; 4783 bool r_ready; 4784 bool w_ready; 4785 bool has_err; 4786 4787 prev = pos->prev; 4788 cs = pos->socket_fd; 4789 if (MHD_INVALID_SOCKET == cs) 4790 continue; 4791 4792 if (MHD_SCKT_FD_FITS_FDSET_SETSIZE_ (cs, NULL, fd_setsize)) 4793 { 4794 r_ready = FD_ISSET (cs, 4795 (fd_set *) _MHD_DROP_CONST (read_fd_set)); 4796 w_ready = FD_ISSET (cs, 4797 (fd_set *) _MHD_DROP_CONST (write_fd_set)); 4798 has_err = (NULL != except_fd_set) && 4799 FD_ISSET (cs, 4800 (fd_set *) _MHD_DROP_CONST (except_fd_set)); 4801 } 4802 else 4803 { /* Cannot check the real readiness */ 4804 r_ready = pos->sk_nonblck; 4805 w_ready = r_ready; 4806 has_err = false; 4807 } 4808 call_handlers (pos, 4809 r_ready, 4810 w_ready, 4811 has_err); 4812 } 4813 } 4814 4815 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) 4816 /* handle upgraded HTTPS connections */ 4817 for (urh = daemon->urh_tail; NULL != urh; urh = urhn) 4818 { 4819 urhn = urh->prev; 4820 /* update urh state based on select() output */ 4821 urh_from_fdset (urh, 4822 read_fd_set, 4823 write_fd_set, 4824 except_fd_set, 4825 fd_setsize); 4826 /* call generic forwarding function for passing data */ 4827 process_urh (urh); 4828 /* Finished forwarding? */ 4829 if ( (0 == urh->in_buffer_size) && 4830 (0 == urh->out_buffer_size) && 4831 (0 == urh->in_buffer_used) && 4832 (0 == urh->out_buffer_used) ) 4833 { 4834 MHD_connection_finish_forward_ (urh->connection); 4835 urh->clean_ready = true; 4836 /* Resuming will move connection to cleanup list. */ 4837 MHD_resume_connection (urh->connection); 4838 } 4839 } 4840 #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ 4841 MHD_cleanup_connections (daemon); 4842 return MHD_YES; 4843 } 4844 4845 4846 #undef MHD_run_from_select 4847 4848 /** 4849 * Run webserver operations. This method should be called by clients 4850 * in combination with #MHD_get_fdset and #MHD_get_timeout() if the 4851 * client-controlled select method is used. 4852 * This function specifies FD_SETSIZE used when provided fd_sets were 4853 * created. It is important on platforms where FD_SETSIZE can be 4854 * overridden. 4855 * 4856 * You can use this function instead of #MHD_run if you called 4857 * 'select()' on the result from #MHD_get_fdset2(). File descriptors in 4858 * the sets that are not controlled by MHD will be ignored. Calling 4859 * this function instead of #MHD_run() is more efficient as MHD will 4860 * not have to call 'select()' again to determine which operations are 4861 * ready. 4862 * 4863 * If #MHD_get_timeout() returned #MHD_YES, than this function must be 4864 * called right after 'select()' returns regardless of detected activity 4865 * on the daemon's FDs. 4866 * 4867 * This function cannot be used with daemon started with 4868 * #MHD_USE_INTERNAL_POLLING_THREAD flag. 4869 * 4870 * @param daemon the daemon to run select loop for 4871 * @param read_fd_set the read set 4872 * @param write_fd_set the write set 4873 * @param except_fd_set the except set 4874 * @param fd_setsize the value of FD_SETSIZE 4875 * @return #MHD_NO on serious errors, #MHD_YES on success 4876 * @sa #MHD_get_fdset2(), #MHD_OPTION_APP_FD_SETSIZE 4877 * @ingroup event 4878 */ 4879 _MHD_EXTERN enum MHD_Result 4880 MHD_run_from_select2 (struct MHD_Daemon *daemon, 4881 const fd_set *read_fd_set, 4882 const fd_set *write_fd_set, 4883 const fd_set *except_fd_set, 4884 unsigned int fd_setsize) 4885 { 4886 if (MHD_D_IS_USING_POLL_ (daemon) || 4887 MHD_D_IS_USING_THREADS_ (daemon)) 4888 return MHD_NO; 4889 if ((NULL == read_fd_set) || (NULL == write_fd_set)) 4890 return MHD_NO; 4891 #ifdef HAVE_MESSAGES 4892 if (NULL == except_fd_set) 4893 { 4894 MHD_DLOG (daemon, 4895 _ ("MHD_run_from_select() called with except_fd_set " 4896 "set to NULL. Such behavior is deprecated.\n")); 4897 } 4898 #endif /* HAVE_MESSAGES */ 4899 4900 #ifdef HAS_FD_SETSIZE_OVERRIDABLE 4901 if (0 == fd_setsize) 4902 return MHD_NO; 4903 else if (((unsigned int) INT_MAX) < fd_setsize) 4904 fd_setsize = (unsigned int) INT_MAX; 4905 #ifdef HAVE_MESSAGES 4906 else if (daemon->fdset_size > ((int) fd_setsize)) 4907 { 4908 if (daemon->fdset_size_set_by_app) 4909 { 4910 MHD_DLOG (daemon, 4911 _ ("%s() called with fd_setsize (%u) " \ 4912 "less than value set by MHD_OPTION_APP_FD_SETSIZE (%d). " \ 4913 "Some socket FDs may be not processed. " \ 4914 "Use MHD_OPTION_APP_FD_SETSIZE with the correct value.\n"), 4915 "MHD_run_from_select2", fd_setsize, daemon->fdset_size); 4916 } 4917 else 4918 { 4919 MHD_DLOG (daemon, 4920 _ ("%s() called with fd_setsize (%u) " \ 4921 "less than FD_SETSIZE used by MHD (%d). " \ 4922 "Some socket FDs may be not processed. " \ 4923 "Consider using MHD_OPTION_APP_FD_SETSIZE option.\n"), 4924 "MHD_run_from_select2", fd_setsize, daemon->fdset_size); 4925 } 4926 } 4927 #endif /* HAVE_MESSAGES */ 4928 #else /* ! HAS_FD_SETSIZE_OVERRIDABLE */ 4929 if (((unsigned int) FD_SETSIZE) > fd_setsize) 4930 { 4931 #ifdef HAVE_MESSAGES 4932 MHD_DLOG (daemon, 4933 _ ("%s() called with fd_setsize (%u) " \ 4934 "less than fixed FD_SETSIZE value (%d) used on the " \ 4935 "platform.\n"), 4936 "MHD_run_from_select2", fd_setsize, (int) FD_SETSIZE); 4937 #endif /* HAVE_MESSAGES */ 4938 return MHD_NO; 4939 } 4940 #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ 4941 4942 if (MHD_D_IS_USING_EPOLL_ (daemon)) 4943 { 4944 #ifdef EPOLL_SUPPORT 4945 enum MHD_Result ret = MHD_epoll (daemon, 4946 0); 4947 4948 MHD_cleanup_connections (daemon); 4949 return ret; 4950 #else /* ! EPOLL_SUPPORT */ 4951 return MHD_NO; 4952 #endif /* ! EPOLL_SUPPORT */ 4953 } 4954 4955 /* Resuming external connections when using an extern mainloop */ 4956 if (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) 4957 resume_suspended_connections (daemon); 4958 4959 return internal_run_from_select (daemon, 4960 read_fd_set, 4961 write_fd_set, 4962 except_fd_set, 4963 (int) fd_setsize); 4964 } 4965 4966 4967 /** 4968 * Run webserver operations. This method should be called by clients 4969 * in combination with #MHD_get_fdset and #MHD_get_timeout() if the 4970 * client-controlled select method is used. 4971 * 4972 * You can use this function instead of #MHD_run if you called 4973 * `select()` on the result from #MHD_get_fdset. File descriptors in 4974 * the sets that are not controlled by MHD will be ignored. Calling 4975 * this function instead of #MHD_run is more efficient as MHD will 4976 * not have to call `select()` again to determine which operations are 4977 * ready. 4978 * 4979 * If #MHD_get_timeout() returned #MHD_YES, than this function must be 4980 * called right after `select()` returns regardless of detected activity 4981 * on the daemon's FDs. 4982 * 4983 * This function cannot be used with daemon started with 4984 * #MHD_USE_INTERNAL_POLLING_THREAD flag. 4985 * 4986 * @param daemon daemon to run select loop for 4987 * @param read_fd_set read set 4988 * @param write_fd_set write set 4989 * @param except_fd_set except set 4990 * @return #MHD_NO on serious errors, #MHD_YES on success 4991 * @ingroup event 4992 */ 4993 _MHD_EXTERN enum MHD_Result 4994 MHD_run_from_select (struct MHD_Daemon *daemon, 4995 const fd_set *read_fd_set, 4996 const fd_set *write_fd_set, 4997 const fd_set *except_fd_set) 4998 { 4999 return MHD_run_from_select2 (daemon, 5000 read_fd_set, 5001 write_fd_set, 5002 except_fd_set, 5003 #ifdef HAS_FD_SETSIZE_OVERRIDABLE 5004 daemon->fdset_size_set_by_app ? 5005 ((unsigned int) daemon->fdset_size) : 5006 ((unsigned int) _MHD_SYS_DEFAULT_FD_SETSIZE) 5007 #else /* ! HAS_FD_SETSIZE_OVERRIDABLE */ 5008 ((unsigned int) _MHD_SYS_DEFAULT_FD_SETSIZE) 5009 #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ 5010 ); 5011 } 5012 5013 5014 /** 5015 * Main internal select() call. Will compute select sets, call select() 5016 * and then #internal_run_from_select with the result. 5017 * 5018 * @param daemon daemon to run select() loop for 5019 * @param millisec the maximum time in milliseconds to wait for events, 5020 * set to '0' for non-blocking processing, 5021 * set to '-1' to wait indefinitely. 5022 * @return #MHD_NO on serious errors, #MHD_YES on success 5023 */ 5024 static enum MHD_Result 5025 MHD_select (struct MHD_Daemon *daemon, 5026 int32_t millisec) 5027 { 5028 int num_ready; 5029 fd_set rs; 5030 fd_set ws; 5031 fd_set es; 5032 MHD_socket maxsock; 5033 struct timeval timeout; 5034 struct timeval *tv; 5035 int err_state; 5036 MHD_socket ls; 5037 5038 timeout.tv_sec = 0; 5039 timeout.tv_usec = 0; 5040 if (daemon->shutdown) 5041 return MHD_NO; 5042 FD_ZERO (&rs); 5043 FD_ZERO (&ws); 5044 FD_ZERO (&es); 5045 maxsock = MHD_INVALID_SOCKET; 5046 err_state = MHD_NO; 5047 if ( (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) && 5048 (MHD_NO != resume_suspended_connections (daemon)) && 5049 (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) ) 5050 millisec = 0; 5051 5052 if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) 5053 { 5054 /* single-threaded, go over everything */ 5055 if (MHD_NO == 5056 internal_get_fdset2 (daemon, 5057 &rs, 5058 &ws, 5059 &es, 5060 &maxsock, 5061 (int) FD_SETSIZE)) 5062 { 5063 #ifdef HAVE_MESSAGES 5064 MHD_DLOG (daemon, 5065 _ ("Could not obtain daemon fdsets.\n")); 5066 #endif 5067 err_state = MHD_YES; 5068 } 5069 } 5070 else 5071 { 5072 bool itc_added; 5073 /* accept only, have one thread per connection */ 5074 itc_added = false; 5075 if (MHD_ITC_IS_VALID_ (daemon->itc)) 5076 { 5077 itc_added = MHD_add_to_fd_set_ (MHD_itc_r_fd_ (daemon->itc), 5078 &rs, 5079 &maxsock, 5080 (int) FD_SETSIZE); 5081 if (! itc_added) 5082 { 5083 #ifdef HAVE_MESSAGES 5084 MHD_DLOG (daemon, _ ("Could not add control inter-thread " \ 5085 "communication channel FD to fdset.\n")); 5086 #endif 5087 err_state = MHD_YES; 5088 } 5089 } 5090 if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) && 5091 (! daemon->was_quiesced) ) 5092 { 5093 /* Stop listening if we are at the configured connection limit */ 5094 /* If we're at the connection limit, no point in really 5095 accepting new connections; however, make sure we do not miss 5096 the shutdown OR the termination of an existing connection; so 5097 only do this optimisation if we have a signaling ITC in 5098 place. */ 5099 if (! itc_added || 5100 ((daemon->connections < daemon->connection_limit) && 5101 ! daemon->at_limit)) 5102 { 5103 if (! MHD_add_to_fd_set_ (ls, 5104 &rs, 5105 &maxsock, 5106 (int) FD_SETSIZE)) 5107 { 5108 #ifdef HAVE_MESSAGES 5109 MHD_DLOG (daemon, 5110 _ ("Could not add listen socket to fdset.\n")); 5111 #endif 5112 err_state = MHD_YES; 5113 } 5114 } 5115 } 5116 } 5117 5118 if (MHD_NO != err_state) 5119 millisec = 0; 5120 if (0 == millisec) 5121 { 5122 timeout.tv_usec = 0; 5123 timeout.tv_sec = 0; 5124 tv = &timeout; 5125 } 5126 else 5127 { 5128 uint64_t mhd_tmo; 5129 uint64_t select_tmo; 5130 5131 if ( (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) && 5132 (MHD_NO != MHD_get_timeout64 (daemon, &mhd_tmo)) ) 5133 { 5134 if ( (0 < millisec) && 5135 (mhd_tmo > (uint64_t) millisec) ) 5136 select_tmo = (uint64_t) millisec; 5137 else 5138 select_tmo = mhd_tmo; 5139 tv = &timeout; /* have timeout value */ 5140 } 5141 else if (0 < millisec) 5142 { 5143 select_tmo = (uint64_t) millisec; 5144 tv = &timeout; /* have timeout value */ 5145 } 5146 else 5147 { 5148 select_tmo = 0; /* Not actually used, silent compiler warning */ 5149 tv = NULL; 5150 } 5151 5152 if (NULL != tv) 5153 { /* have timeout value */ 5154 #if (SIZEOF_UINT64_T - 2) >= SIZEOF_STRUCT_TIMEVAL_TV_SEC 5155 if (select_tmo / 1000 > TIMEVAL_TV_SEC_MAX) 5156 timeout.tv_sec = TIMEVAL_TV_SEC_MAX; 5157 else 5158 #endif /* (SIZEOF_UINT64_T - 2) >= SIZEOF_STRUCT_TIMEVAL_TV_SEC */ 5159 timeout.tv_sec = (_MHD_TIMEVAL_TV_SEC_TYPE) (select_tmo / 1000); 5160 5161 timeout.tv_usec = ((uint16_t) (select_tmo % 1000)) * ((int32_t) 1000); 5162 } 5163 } 5164 num_ready = MHD_SYS_select_ (maxsock + 1, 5165 &rs, 5166 &ws, 5167 &es, 5168 tv); 5169 if (daemon->shutdown) 5170 return MHD_NO; 5171 if (num_ready < 0) 5172 { 5173 const int err = MHD_socket_get_error_ (); 5174 if (MHD_SCKT_ERR_IS_EINTR_ (err)) 5175 return (MHD_NO == err_state) ? MHD_YES : MHD_NO; 5176 #ifdef HAVE_MESSAGES 5177 MHD_DLOG (daemon, 5178 _ ("select failed: %s\n"), 5179 MHD_socket_strerr_ (err)); 5180 #endif 5181 return MHD_NO; 5182 } 5183 if (MHD_NO != internal_run_from_select (daemon, 5184 &rs, 5185 &ws, 5186 &es, 5187 (int) FD_SETSIZE)) 5188 return (MHD_NO == err_state) ? MHD_YES : MHD_NO; 5189 return MHD_NO; 5190 } 5191 5192 5193 #ifdef HAVE_POLL 5194 /** 5195 * Process all of our connections and possibly the server 5196 * socket using poll(). 5197 * 5198 * @param daemon daemon to run poll loop for 5199 * @param millisec the maximum time in milliseconds to wait for events, 5200 * set to '0' for non-blocking processing, 5201 * set to '-1' to wait indefinitely. 5202 * @return #MHD_NO on serious errors, #MHD_YES on success 5203 */ 5204 static enum MHD_Result 5205 MHD_poll_all (struct MHD_Daemon *daemon, 5206 int32_t millisec) 5207 { 5208 unsigned int num_connections; 5209 struct MHD_Connection *pos; 5210 struct MHD_Connection *prev; 5211 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) 5212 struct MHD_UpgradeResponseHandle *urh; 5213 struct MHD_UpgradeResponseHandle *urhn; 5214 #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ 5215 5216 mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ 5217 (MHD_thread_handle_ID_is_valid_ID_ (daemon->tid))); 5218 mhd_assert ((0 != (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ 5219 (! MHD_thread_handle_ID_is_valid_ID_ (daemon->tid))); 5220 mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ 5221 (MHD_thread_handle_ID_is_current_thread_ (daemon->tid))); 5222 5223 if ( (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) && 5224 (MHD_NO != resume_suspended_connections (daemon)) ) 5225 millisec = 0; 5226 5227 /* count number of connections and thus determine poll set size */ 5228 num_connections = 0; 5229 for (pos = daemon->connections_head; NULL != pos; pos = pos->next) 5230 num_connections++; 5231 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) 5232 for (urh = daemon->urh_head; NULL != urh; urh = urh->next) 5233 num_connections += 2; 5234 #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ 5235 { 5236 unsigned int i; 5237 int timeout; 5238 unsigned int poll_server; 5239 int poll_listen; 5240 int poll_itc_idx; 5241 struct pollfd *p; 5242 MHD_socket ls; 5243 5244 p = MHD_calloc_ ((2 + (size_t) num_connections), 5245 sizeof (struct pollfd)); 5246 if (NULL == p) 5247 { 5248 #ifdef HAVE_MESSAGES 5249 MHD_DLOG (daemon, 5250 _ ("Error allocating memory: %s\n"), 5251 MHD_strerror_ (errno)); 5252 #endif 5253 return MHD_NO; 5254 } 5255 poll_server = 0; 5256 poll_listen = -1; 5257 if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) && 5258 (! daemon->was_quiesced) && 5259 (daemon->connections < daemon->connection_limit) && 5260 (! daemon->at_limit) ) 5261 { 5262 /* only listen if we are not at the connection limit */ 5263 p[poll_server].fd = ls; 5264 p[poll_server].events = POLLIN; 5265 p[poll_server].revents = 0; 5266 poll_listen = (int) poll_server; 5267 poll_server++; 5268 } 5269 poll_itc_idx = -1; 5270 if (MHD_ITC_IS_VALID_ (daemon->itc)) 5271 { 5272 p[poll_server].fd = MHD_itc_r_fd_ (daemon->itc); 5273 p[poll_server].events = POLLIN; 5274 p[poll_server].revents = 0; 5275 poll_itc_idx = (int) poll_server; 5276 poll_server++; 5277 } 5278 5279 timeout = get_timeout_millisec_int (daemon, millisec); 5280 5281 i = 0; 5282 for (pos = daemon->connections_tail; NULL != pos; pos = pos->prev) 5283 { 5284 p[poll_server + i].fd = pos->socket_fd; 5285 switch (pos->event_loop_info) 5286 { 5287 case MHD_EVENT_LOOP_INFO_READ: 5288 case MHD_EVENT_LOOP_INFO_PROCESS_READ: 5289 p[poll_server + i].events |= POLLIN | MHD_POLL_EVENTS_ERR_DISC; 5290 break; 5291 case MHD_EVENT_LOOP_INFO_WRITE: 5292 p[poll_server + i].events |= POLLOUT | MHD_POLL_EVENTS_ERR_DISC; 5293 break; 5294 case MHD_EVENT_LOOP_INFO_PROCESS: 5295 p[poll_server + i].events |= MHD_POLL_EVENTS_ERR_DISC; 5296 break; 5297 case MHD_EVENT_LOOP_INFO_CLEANUP: 5298 timeout = 0; /* clean up "pos" immediately */ 5299 break; 5300 } 5301 i++; 5302 } 5303 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) 5304 for (urh = daemon->urh_tail; NULL != urh; urh = urh->prev) 5305 { 5306 urh_to_pollfd (urh, &(p[poll_server + i])); 5307 i += 2; 5308 } 5309 #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ 5310 if (0 == poll_server + num_connections) 5311 { 5312 free (p); 5313 return MHD_YES; 5314 } 5315 if (MHD_sys_poll_ (p, 5316 poll_server + num_connections, 5317 timeout) < 0) 5318 { 5319 const int err = MHD_socket_get_error_ (); 5320 if (MHD_SCKT_ERR_IS_EINTR_ (err)) 5321 { 5322 free (p); 5323 return MHD_YES; 5324 } 5325 #ifdef HAVE_MESSAGES 5326 MHD_DLOG (daemon, 5327 _ ("poll failed: %s\n"), 5328 MHD_socket_strerr_ (err)); 5329 #endif 5330 free (p); 5331 return MHD_NO; 5332 } 5333 5334 /* handle ITC FD */ 5335 /* do it before any other processing so 5336 new signals will be processed in next loop */ 5337 if ( (-1 != poll_itc_idx) && 5338 (0 != (p[poll_itc_idx].revents & POLLIN)) ) 5339 MHD_itc_clear_ (daemon->itc); 5340 5341 /* handle shutdown */ 5342 if (daemon->shutdown) 5343 { 5344 free (p); 5345 return MHD_NO; 5346 } 5347 5348 /* Process externally added connection if any */ 5349 if (daemon->have_new) 5350 new_connections_list_process_ (daemon); 5351 5352 /* handle 'listen' FD */ 5353 if ( (-1 != poll_listen) && 5354 (0 != (p[poll_listen].revents & POLLIN)) ) 5355 (void) MHD_accept_connection (daemon); 5356 5357 /* Reset. New value will be set when connections are processed. */ 5358 daemon->data_already_pending = false; 5359 5360 i = 0; 5361 prev = daemon->connections_tail; 5362 while (NULL != (pos = prev)) 5363 { 5364 prev = pos->prev; 5365 /* first, sanity checks */ 5366 if (i >= num_connections) 5367 break; /* connection list changed somehow, retry later ... */ 5368 if (p[poll_server + i].fd != pos->socket_fd) 5369 continue; /* fd mismatch, something else happened, retry later ... */ 5370 call_handlers (pos, 5371 0 != (p[poll_server + i].revents & POLLIN), 5372 0 != (p[poll_server + i].revents & POLLOUT), 5373 0 != (p[poll_server + i].revents 5374 & MHD_POLL_REVENTS_ERR_DISC)); 5375 i++; 5376 } 5377 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) 5378 for (urh = daemon->urh_tail; NULL != urh; urh = urhn) 5379 { 5380 if (i >= num_connections) 5381 break; /* connection list changed somehow, retry later ... */ 5382 5383 /* Get next connection here as connection can be removed 5384 * from 'daemon->urh_head' list. */ 5385 urhn = urh->prev; 5386 /* Check for fd mismatch. FIXME: required for safety? */ 5387 if ((p[poll_server + i].fd != urh->connection->socket_fd) || 5388 (p[poll_server + i + 1].fd != urh->mhd.socket)) 5389 break; 5390 urh_from_pollfd (urh, 5391 &p[poll_server + i]); 5392 i += 2; 5393 process_urh (urh); 5394 /* Finished forwarding? */ 5395 if ( (0 == urh->in_buffer_size) && 5396 (0 == urh->out_buffer_size) && 5397 (0 == urh->in_buffer_used) && 5398 (0 == urh->out_buffer_used) ) 5399 { 5400 /* MHD_connection_finish_forward_() will remove connection from 5401 * 'daemon->urh_head' list. */ 5402 MHD_connection_finish_forward_ (urh->connection); 5403 urh->clean_ready = true; 5404 /* If 'urh->was_closed' already was set to true, connection will be 5405 * moved immediately to cleanup list. Otherwise connection 5406 * will stay in suspended list until 'urh' will be marked 5407 * with 'was_closed' by application. */ 5408 MHD_resume_connection (urh->connection); 5409 } 5410 } 5411 #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ 5412 5413 free (p); 5414 } 5415 return MHD_YES; 5416 } 5417 5418 5419 /** 5420 * Process only the listen socket using poll(). 5421 * 5422 * @param daemon daemon to run poll loop for 5423 * @param may_block #MHD_YES if blocking, #MHD_NO if non-blocking 5424 * @return #MHD_NO on serious errors, #MHD_YES on success 5425 */ 5426 static enum MHD_Result 5427 MHD_poll_listen_socket (struct MHD_Daemon *daemon, 5428 int may_block) 5429 { 5430 struct pollfd p[2]; 5431 int timeout; 5432 unsigned int poll_count; 5433 int poll_listen; 5434 int poll_itc_idx; 5435 MHD_socket ls; 5436 5437 mhd_assert (MHD_thread_handle_ID_is_valid_ID_ (daemon->tid)); 5438 mhd_assert (MHD_thread_handle_ID_is_current_thread_ (daemon->tid)); 5439 5440 memset (&p, 5441 0, 5442 sizeof (p)); 5443 poll_count = 0; 5444 poll_listen = -1; 5445 poll_itc_idx = -1; 5446 if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) && 5447 (! daemon->was_quiesced) ) 5448 5449 { 5450 p[poll_count].fd = ls; 5451 p[poll_count].events = POLLIN; 5452 p[poll_count].revents = 0; 5453 poll_listen = (int) poll_count; 5454 poll_count++; 5455 } 5456 if (MHD_ITC_IS_VALID_ (daemon->itc)) 5457 { 5458 p[poll_count].fd = MHD_itc_r_fd_ (daemon->itc); 5459 p[poll_count].events = POLLIN; 5460 p[poll_count].revents = 0; 5461 poll_itc_idx = (int) poll_count; 5462 poll_count++; 5463 } 5464 5465 if (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) 5466 (void) resume_suspended_connections (daemon); 5467 5468 if (MHD_NO == may_block) 5469 timeout = 0; 5470 else 5471 timeout = -1; 5472 if (0 == poll_count) 5473 return MHD_YES; 5474 if (MHD_sys_poll_ (p, 5475 poll_count, 5476 timeout) < 0) 5477 { 5478 const int err = MHD_socket_get_error_ (); 5479 5480 if (MHD_SCKT_ERR_IS_EINTR_ (err)) 5481 return MHD_YES; 5482 #ifdef HAVE_MESSAGES 5483 MHD_DLOG (daemon, 5484 _ ("poll failed: %s\n"), 5485 MHD_socket_strerr_ (err)); 5486 #endif 5487 return MHD_NO; 5488 } 5489 if ( (0 <= poll_itc_idx) && 5490 (0 != (p[poll_itc_idx].revents & POLLIN)) ) 5491 MHD_itc_clear_ (daemon->itc); 5492 5493 /* handle shutdown */ 5494 if (daemon->shutdown) 5495 return MHD_NO; 5496 5497 /* Process externally added connection if any */ 5498 if (daemon->have_new) 5499 new_connections_list_process_ (daemon); 5500 5501 if ( (0 <= poll_listen) && 5502 (0 != (p[poll_listen].revents & POLLIN)) ) 5503 (void) MHD_accept_connection (daemon); 5504 return MHD_YES; 5505 } 5506 5507 5508 #endif 5509 5510 #ifdef HAVE_POLL 5511 5512 /** 5513 * Do poll()-based processing. 5514 * 5515 * @param daemon daemon to run poll()-loop for 5516 * @param may_block #MHD_YES if blocking, #MHD_NO if non-blocking 5517 * @return #MHD_NO on serious errors, #MHD_YES on success 5518 */ 5519 static enum MHD_Result 5520 MHD_poll (struct MHD_Daemon *daemon, 5521 int may_block) 5522 { 5523 if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) 5524 return MHD_poll_all (daemon, 5525 may_block ? -1 : 0); 5526 return MHD_poll_listen_socket (daemon, 5527 may_block); 5528 } 5529 5530 5531 #endif /* HAVE_POLL */ 5532 5533 5534 #ifdef EPOLL_SUPPORT 5535 5536 /** 5537 * How many events to we process at most per epoll() call? Trade-off 5538 * between required stack-size and number of system calls we have to 5539 * make; 128 should be way enough to avoid more than one system call 5540 * for most scenarios, and still be moderate in stack size 5541 * consumption. Embedded systems might want to choose a smaller value 5542 * --- but why use epoll() on such a system in the first place? 5543 */ 5544 #define MAX_EVENTS 128 5545 5546 5547 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) 5548 5549 /** 5550 * Checks whether @a urh has some data to process. 5551 * 5552 * @param urh upgrade handler to analyse 5553 * @return 'true' if @a urh has some data to process, 5554 * 'false' otherwise 5555 */ 5556 static bool 5557 is_urh_ready (struct MHD_UpgradeResponseHandle *const urh) 5558 { 5559 const struct MHD_Connection *const connection = urh->connection; 5560 5561 if ( (0 == urh->in_buffer_size) && 5562 (0 == urh->out_buffer_size) && 5563 (0 == urh->in_buffer_used) && 5564 (0 == urh->out_buffer_used) ) 5565 return false; 5566 if (connection->daemon->shutdown) 5567 return true; 5568 if ( ( (0 != ((MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_ERROR) 5569 & urh->app.celi)) || 5570 (connection->tls_read_ready) ) && 5571 (urh->in_buffer_used < urh->in_buffer_size) ) 5572 return true; 5573 if ( ( (0 != ((MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_ERROR) 5574 & urh->mhd.celi)) || 5575 urh->was_closed) && 5576 (urh->out_buffer_used < urh->out_buffer_size) ) 5577 return true; 5578 if ( (0 != (MHD_EPOLL_STATE_WRITE_READY & urh->app.celi)) && 5579 (urh->out_buffer_used > 0) ) 5580 return true; 5581 if ( (0 != (MHD_EPOLL_STATE_WRITE_READY & urh->mhd.celi)) && 5582 (urh->in_buffer_used > 0) ) 5583 return true; 5584 return false; 5585 } 5586 5587 5588 /** 5589 * Do epoll()-based processing for TLS connections that have been 5590 * upgraded. This requires a separate epoll() invocation as we 5591 * cannot use the `struct MHD_Connection` data structures for 5592 * the `union epoll_data` in this case. 5593 * @remark To be called only from thread that process 5594 * daemon's select()/poll()/etc. 5595 */ 5596 static enum MHD_Result 5597 run_epoll_for_upgrade (struct MHD_Daemon *daemon) 5598 { 5599 struct epoll_event events[MAX_EVENTS]; 5600 int num_events; 5601 struct MHD_UpgradeResponseHandle *pos; 5602 struct MHD_UpgradeResponseHandle *prev; 5603 5604 #ifdef MHD_USE_THREADS 5605 mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ 5606 MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); 5607 #endif /* MHD_USE_THREADS */ 5608 5609 num_events = MAX_EVENTS; 5610 while (0 != num_events) 5611 { 5612 unsigned int i; 5613 /* update event masks */ 5614 num_events = epoll_wait (daemon->epoll_upgrade_fd, 5615 events, 5616 MAX_EVENTS, 5617 0); 5618 if (-1 == num_events) 5619 { 5620 const int err = MHD_socket_get_error_ (); 5621 5622 if (MHD_SCKT_ERR_IS_EINTR_ (err)) 5623 return MHD_YES; 5624 #ifdef HAVE_MESSAGES 5625 MHD_DLOG (daemon, 5626 _ ("Call to epoll_wait failed: %s\n"), 5627 MHD_socket_strerr_ (err)); 5628 #endif 5629 return MHD_NO; 5630 } 5631 for (i = 0; i < (unsigned int) num_events; i++) 5632 { 5633 struct UpgradeEpollHandle *const ueh = events[i].data.ptr; 5634 struct MHD_UpgradeResponseHandle *const urh = ueh->urh; 5635 bool new_err_state = false; 5636 5637 if (urh->clean_ready) 5638 continue; 5639 5640 /* Update ueh state based on what is ready according to epoll() */ 5641 if (0 != (events[i].events & EPOLLIN)) 5642 { 5643 ueh->celi |= MHD_EPOLL_STATE_READ_READY; 5644 } 5645 if (0 != (events[i].events & EPOLLOUT)) 5646 { 5647 ueh->celi |= MHD_EPOLL_STATE_WRITE_READY; 5648 } 5649 if (0 != (events[i].events & EPOLLHUP)) 5650 { 5651 ueh->celi |= MHD_EPOLL_STATE_READ_READY | MHD_EPOLL_STATE_WRITE_READY; 5652 } 5653 5654 if ( (0 == (ueh->celi & MHD_EPOLL_STATE_ERROR)) && 5655 (0 != (events[i].events & (EPOLLERR | EPOLLPRI))) ) 5656 { 5657 /* Process new error state only one time and avoid continuously 5658 * marking this connection as 'ready'. */ 5659 ueh->celi |= MHD_EPOLL_STATE_ERROR; 5660 new_err_state = true; 5661 } 5662 if (! urh->in_eready_list) 5663 { 5664 if (new_err_state || 5665 is_urh_ready (urh)) 5666 { 5667 EDLL_insert (daemon->eready_urh_head, 5668 daemon->eready_urh_tail, 5669 urh); 5670 urh->in_eready_list = true; 5671 } 5672 } 5673 } 5674 } 5675 prev = daemon->eready_urh_tail; 5676 while (NULL != (pos = prev)) 5677 { 5678 prev = pos->prevE; 5679 process_urh (pos); 5680 if (! is_urh_ready (pos)) 5681 { 5682 EDLL_remove (daemon->eready_urh_head, 5683 daemon->eready_urh_tail, 5684 pos); 5685 pos->in_eready_list = false; 5686 } 5687 /* Finished forwarding? */ 5688 if ( (0 == pos->in_buffer_size) && 5689 (0 == pos->out_buffer_size) && 5690 (0 == pos->in_buffer_used) && 5691 (0 == pos->out_buffer_used) ) 5692 { 5693 MHD_connection_finish_forward_ (pos->connection); 5694 pos->clean_ready = true; 5695 /* If 'pos->was_closed' already was set to true, connection 5696 * will be moved immediately to cleanup list. Otherwise 5697 * connection will stay in suspended list until 'pos' will 5698 * be marked with 'was_closed' by application. */ 5699 MHD_resume_connection (pos->connection); 5700 } 5701 } 5702 5703 return MHD_YES; 5704 } 5705 5706 5707 #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ 5708 5709 5710 /** 5711 * Pointer-marker to distinguish ITC slot in epoll sets. 5712 */ 5713 static const char *const epoll_itc_marker = "itc_marker"; 5714 5715 5716 /** 5717 * Do epoll()-based processing. 5718 * 5719 * @param daemon daemon to run poll loop for 5720 * @param millisec the maximum time in milliseconds to wait for events, 5721 * set to '0' for non-blocking processing, 5722 * set to '-1' to wait indefinitely. 5723 * @return #MHD_NO on serious errors, #MHD_YES on success 5724 */ 5725 static enum MHD_Result 5726 MHD_epoll (struct MHD_Daemon *daemon, 5727 int32_t millisec) 5728 { 5729 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) 5730 static const char *const upgrade_marker = "upgrade_ptr"; 5731 #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ 5732 struct MHD_Connection *pos; 5733 struct MHD_Connection *prev; 5734 struct epoll_event events[MAX_EVENTS]; 5735 struct epoll_event event; 5736 int timeout_ms; 5737 int num_events; 5738 unsigned int i; 5739 MHD_socket ls; 5740 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) 5741 bool run_upgraded = false; 5742 #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ 5743 bool need_to_accept; 5744 5745 mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ 5746 (MHD_thread_handle_ID_is_valid_ID_ (daemon->tid))); 5747 mhd_assert ((0 != (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ 5748 (! MHD_thread_handle_ID_is_valid_ID_ (daemon->tid))); 5749 mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ 5750 (MHD_thread_handle_ID_is_current_thread_ (daemon->tid))); 5751 5752 if (-1 == daemon->epoll_fd) 5753 return MHD_NO; /* we're down! */ 5754 if (daemon->shutdown) 5755 return MHD_NO; 5756 /* 'listen_socket_in_epoll', 'was_quiesced' and the epoll set itself 5757 are shared with MHD_quiesce_daemon(), which runs on the 5758 application's thread. Testing them and acting on the result has to 5759 be one atomic step. */ 5760 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 5761 MHD_mutex_lock_chk_ (&daemon->epoll_listen_mutex); 5762 #endif 5763 if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) && 5764 (! daemon->was_quiesced) && 5765 (daemon->connections < daemon->connection_limit) && 5766 (! daemon->listen_socket_in_epoll) && 5767 (! daemon->at_limit) ) 5768 { 5769 event.events = EPOLLIN | EPOLLRDHUP; 5770 event.data.ptr = daemon; 5771 if (0 != epoll_ctl (daemon->epoll_fd, 5772 EPOLL_CTL_ADD, 5773 ls, 5774 &event)) 5775 { 5776 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 5777 MHD_mutex_unlock_chk_ (&daemon->epoll_listen_mutex); 5778 #endif 5779 #ifdef HAVE_MESSAGES 5780 MHD_DLOG (daemon, 5781 _ ("Call to epoll_ctl failed: %s\n"), 5782 MHD_socket_last_strerr_ ()); 5783 #endif 5784 return MHD_NO; 5785 } 5786 daemon->listen_socket_in_epoll = true; 5787 } 5788 if ( (daemon->was_quiesced) && 5789 (daemon->listen_socket_in_epoll) ) 5790 { 5791 if (0 != epoll_ctl (daemon->epoll_fd, 5792 EPOLL_CTL_DEL, 5793 ls, 5794 NULL)) 5795 MHD_PANIC ("Failed to remove listen FD from epoll set.\n"); 5796 daemon->listen_socket_in_epoll = false; 5797 } 5798 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 5799 MHD_mutex_unlock_chk_ (&daemon->epoll_listen_mutex); 5800 #endif 5801 5802 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) 5803 if ( ( (! daemon->upgrade_fd_in_epoll) && 5804 (-1 != daemon->epoll_upgrade_fd) ) ) 5805 { 5806 event.events = EPOLLIN | EPOLLOUT | EPOLLRDHUP; 5807 event.data.ptr = _MHD_DROP_CONST (upgrade_marker); 5808 if (0 != epoll_ctl (daemon->epoll_fd, 5809 EPOLL_CTL_ADD, 5810 daemon->epoll_upgrade_fd, 5811 &event)) 5812 { 5813 #ifdef HAVE_MESSAGES 5814 MHD_DLOG (daemon, 5815 _ ("Call to epoll_ctl failed: %s\n"), 5816 MHD_socket_last_strerr_ ()); 5817 #endif 5818 return MHD_NO; 5819 } 5820 daemon->upgrade_fd_in_epoll = true; 5821 } 5822 #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ 5823 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 5824 MHD_mutex_lock_chk_ (&daemon->epoll_listen_mutex); 5825 #endif 5826 if ( (daemon->listen_socket_in_epoll) && 5827 ( (daemon->connections == daemon->connection_limit) || 5828 (daemon->at_limit) || 5829 (daemon->was_quiesced) ) ) 5830 { 5831 /* we're at the connection limit, disable listen socket 5832 for event loop for now */ 5833 if (0 != epoll_ctl (daemon->epoll_fd, 5834 EPOLL_CTL_DEL, 5835 ls, 5836 NULL)) 5837 MHD_PANIC (_ ("Failed to remove listen FD from epoll set.\n")); 5838 daemon->listen_socket_in_epoll = false; 5839 } 5840 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 5841 MHD_mutex_unlock_chk_ (&daemon->epoll_listen_mutex); 5842 #endif 5843 5844 if ( (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) && 5845 (MHD_NO != resume_suspended_connections (daemon)) ) 5846 millisec = 0; 5847 5848 timeout_ms = get_timeout_millisec_int (daemon, 5849 millisec); 5850 5851 /* Reset. New value will be set when connections are processed. */ 5852 /* Note: Used mostly for uniformity here as same situation is 5853 * signaled in epoll mode by non-empty eready DLL. */ 5854 daemon->data_already_pending = false; 5855 5856 need_to_accept = false; 5857 /* drain 'epoll' event queue; need to iterate as we get at most 5858 MAX_EVENTS in one system call here; in practice this should 5859 pretty much mean only one round, but better an extra loop here 5860 than unfair behavior... */ 5861 num_events = MAX_EVENTS; 5862 while (MAX_EVENTS == num_events) 5863 { 5864 /* update event masks */ 5865 num_events = epoll_wait (daemon->epoll_fd, 5866 events, 5867 MAX_EVENTS, 5868 timeout_ms); 5869 /* A full batch may have been the last of the pending events: the next 5870 call only drains what is left, it must not wait. With edge-triggered 5871 connections nothing new arrives until they are processed, so waiting 5872 here would stall every connection until the timeout. */ 5873 timeout_ms = 0; 5874 if (-1 == num_events) 5875 { 5876 const int err = MHD_socket_get_error_ (); 5877 if (MHD_SCKT_ERR_IS_EINTR_ (err)) 5878 return MHD_YES; 5879 #ifdef HAVE_MESSAGES 5880 MHD_DLOG (daemon, 5881 _ ("Call to epoll_wait failed: %s\n"), 5882 MHD_socket_strerr_ (err)); 5883 #endif 5884 return MHD_NO; 5885 } 5886 for (i = 0; i < (unsigned int) num_events; i++) 5887 { 5888 /* First, check for the values of `ptr` that would indicate 5889 that this event is not about a normal connection. */ 5890 if (NULL == events[i].data.ptr) 5891 continue; /* shutdown signal! */ 5892 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) 5893 if (upgrade_marker == events[i].data.ptr) 5894 { 5895 /* activity on an upgraded connection, we process 5896 those in a separate epoll() */ 5897 run_upgraded = true; 5898 continue; 5899 } 5900 #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ 5901 if (epoll_itc_marker == events[i].data.ptr) 5902 { 5903 /* It's OK to clear ITC here as all external 5904 conditions will be processed later. */ 5905 MHD_itc_clear_ (daemon->itc); 5906 continue; 5907 } 5908 if (daemon == events[i].data.ptr) 5909 { 5910 /* Check for error conditions on listen socket. */ 5911 /* FIXME: Initiate MHD_quiesce_daemon() to prevent busy waiting? */ 5912 if (0 == (events[i].events & (EPOLLERR | EPOLLHUP))) 5913 need_to_accept = true; 5914 continue; 5915 } 5916 /* this is an event relating to a 'normal' connection, 5917 remember the event and if appropriate mark the 5918 connection as 'eready'. */ 5919 pos = events[i].data.ptr; 5920 /* normal processing: update read/write data */ 5921 if (0 != (events[i].events & (EPOLLPRI | EPOLLERR | EPOLLHUP))) 5922 { 5923 pos->epoll_state |= MHD_EPOLL_STATE_ERROR; 5924 if (0 == (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL)) 5925 { 5926 EDLL_insert (daemon->eready_head, 5927 daemon->eready_tail, 5928 pos); 5929 pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL; 5930 } 5931 } 5932 else 5933 { 5934 if (0 != (events[i].events & EPOLLIN)) 5935 { 5936 pos->epoll_state |= MHD_EPOLL_STATE_READ_READY; 5937 if ( ( (0 != (MHD_EVENT_LOOP_INFO_READ & pos->event_loop_info)) || 5938 (pos->read_buffer_size > pos->read_buffer_offset) ) && 5939 (0 == (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL) ) ) 5940 { 5941 EDLL_insert (daemon->eready_head, 5942 daemon->eready_tail, 5943 pos); 5944 pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL; 5945 } 5946 } 5947 if (0 != (events[i].events & EPOLLOUT)) 5948 { 5949 pos->epoll_state |= MHD_EPOLL_STATE_WRITE_READY; 5950 if ( (MHD_EVENT_LOOP_INFO_WRITE == pos->event_loop_info) && 5951 (0 == (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL) ) ) 5952 { 5953 EDLL_insert (daemon->eready_head, 5954 daemon->eready_tail, 5955 pos); 5956 pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL; 5957 } 5958 } 5959 } 5960 } 5961 } 5962 5963 /* Process externally added connection if any */ 5964 if (daemon->have_new) 5965 new_connections_list_process_ (daemon); 5966 5967 if (need_to_accept) 5968 { 5969 unsigned int series_length = 0; 5970 5971 /* Run 'accept' until it fails or daemon at limit of connections. 5972 * Do not accept more then 10 connections at once. The rest will 5973 * be accepted on next turn (level trigger is used for listen 5974 * socket). */ 5975 while ( (MHD_NO != MHD_accept_connection (daemon)) && 5976 (series_length < 10) && 5977 (daemon->connections < daemon->connection_limit) && 5978 (! daemon->at_limit) ) 5979 series_length++; 5980 } 5981 5982 /* Handle timed-out connections; we need to do this here 5983 as the epoll mechanism won't call the 'MHD_connection_handle_idle()' on everything, 5984 as the other event loops do. As timeouts do not get an explicit 5985 event, we need to find those connections that might have timed out 5986 here. 5987 5988 Connections with custom timeouts must all be looked at, as we 5989 do not bother to sort that (presumably very short) list. */ 5990 prev = daemon->manual_timeout_tail; 5991 while (NULL != (pos = prev)) 5992 { 5993 prev = pos->prevX; 5994 MHD_connection_handle_idle (pos); 5995 } 5996 /* Connections with the default timeout are sorted by prepending 5997 them to the head of the list whenever we touch the connection; 5998 thus it suffices to iterate from the tail until the first 5999 connection is NOT timed out */ 6000 prev = daemon->normal_timeout_tail; 6001 while (NULL != (pos = prev)) 6002 { 6003 prev = pos->prevX; 6004 MHD_connection_handle_idle (pos); 6005 if (MHD_CONNECTION_CLOSED != pos->state) 6006 break; /* sorted by timeout, no need to visit the rest! */ 6007 } 6008 6009 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) 6010 if (run_upgraded || (NULL != daemon->eready_urh_head)) 6011 run_epoll_for_upgrade (daemon); 6012 #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ 6013 6014 /* process events for connections */ 6015 prev = daemon->eready_tail; 6016 while (NULL != (pos = prev)) 6017 { 6018 prev = pos->prevE; 6019 call_handlers (pos, 6020 0 != (pos->epoll_state & MHD_EPOLL_STATE_READ_READY), 6021 0 != (pos->epoll_state & MHD_EPOLL_STATE_WRITE_READY), 6022 0 != (pos->epoll_state & MHD_EPOLL_STATE_ERROR)); 6023 if (MHD_EPOLL_STATE_IN_EREADY_EDLL == 6024 (pos->epoll_state & (MHD_EPOLL_STATE_SUSPENDED 6025 | MHD_EPOLL_STATE_IN_EREADY_EDLL))) 6026 { 6027 if ( ((MHD_EVENT_LOOP_INFO_READ == pos->event_loop_info) && 6028 (0 == (pos->epoll_state & MHD_EPOLL_STATE_READ_READY)) ) || 6029 ((MHD_EVENT_LOOP_INFO_WRITE == pos->event_loop_info) && 6030 (0 == (pos->epoll_state & MHD_EPOLL_STATE_WRITE_READY)) ) || 6031 (MHD_EVENT_LOOP_INFO_CLEANUP == pos->event_loop_info) ) 6032 { 6033 EDLL_remove (daemon->eready_head, 6034 daemon->eready_tail, 6035 pos); 6036 pos->epoll_state &= 6037 ~((enum MHD_EpollState) MHD_EPOLL_STATE_IN_EREADY_EDLL); 6038 } 6039 } 6040 } 6041 6042 return MHD_YES; 6043 } 6044 6045 6046 #endif 6047 6048 6049 /** 6050 * Run webserver operations (without blocking unless in client callbacks). 6051 * 6052 * This method should be called by clients in combination with 6053 * #MHD_get_fdset() (or #MHD_get_daemon_info() with MHD_DAEMON_INFO_EPOLL_FD 6054 * if epoll is used) and #MHD_get_timeout() if the client-controlled 6055 * connection polling method is used (i.e. daemon was started without 6056 * #MHD_USE_INTERNAL_POLLING_THREAD flag). 6057 * 6058 * This function is a convenience method, which is useful if the 6059 * fd_sets from #MHD_get_fdset were not directly passed to `select()`; 6060 * with this function, MHD will internally do the appropriate `select()` 6061 * call itself again. While it is acceptable to call #MHD_run (if 6062 * #MHD_USE_INTERNAL_POLLING_THREAD is not set) at any moment, you should 6063 * call #MHD_run_from_select() if performance is important (as it saves an 6064 * expensive call to `select()`). 6065 * 6066 * If #MHD_get_timeout() returned #MHD_YES, than this function must be called 6067 * right after polling function returns regardless of detected activity on 6068 * the daemon's FDs. 6069 * 6070 * @param daemon daemon to run 6071 * @return #MHD_YES on success, #MHD_NO if this 6072 * daemon was not started with the right 6073 * options for this call. 6074 * @ingroup event 6075 */ 6076 _MHD_EXTERN enum MHD_Result 6077 MHD_run (struct MHD_Daemon *daemon) 6078 { 6079 if ( (daemon->shutdown) || 6080 MHD_D_IS_USING_THREADS_ (daemon) ) 6081 return MHD_NO; 6082 6083 (void) MHD_run_wait (daemon, 0); 6084 return MHD_YES; 6085 } 6086 6087 6088 /** 6089 * Run webserver operation with possible blocking. 6090 * 6091 * This function does the following: waits for any network event not more than 6092 * specified number of milliseconds, processes all incoming and outgoing data, 6093 * processes new connections, processes any timed-out connection, and does 6094 * other things required to run webserver. 6095 * Once all connections are processed, function returns. 6096 * 6097 * This function is useful for quick and simple (lazy) webserver implementation 6098 * if application needs to run a single thread only and does not have any other 6099 * network activity. 6100 * 6101 * This function calls MHD_get_timeout() internally and use returned value as 6102 * maximum wait time if it less than value of @a millisec parameter. 6103 * 6104 * It is expected that the "external" socket polling function is not used in 6105 * conjunction with this function unless the @a millisec is set to zero. 6106 * 6107 * @param daemon the daemon to run 6108 * @param millisec the maximum time in milliseconds to wait for network and 6109 * other events. Note: there is no guarantee that function 6110 * blocks for the specified amount of time. The real processing 6111 * time can be shorter (if some data or connection timeout 6112 * comes earlier) or longer (if data processing requires more 6113 * time, especially in user callbacks). 6114 * If set to '0' then function does not block and processes 6115 * only already available data (if any). 6116 * If set to '-1' then function waits for events 6117 * indefinitely (blocks until next network activity or 6118 * connection timeout). 6119 * @return #MHD_YES on success, #MHD_NO if this 6120 * daemon was not started with the right 6121 * options for this call or some serious 6122 * unrecoverable error occurs. 6123 * @note Available since #MHD_VERSION 0x00097206 6124 * @ingroup event 6125 */ 6126 _MHD_EXTERN enum MHD_Result 6127 MHD_run_wait (struct MHD_Daemon *daemon, 6128 int32_t millisec) 6129 { 6130 enum MHD_Result res; 6131 if ( (daemon->shutdown) || 6132 MHD_D_IS_USING_THREADS_ (daemon) ) 6133 return MHD_NO; 6134 6135 mhd_assert (! MHD_thread_handle_ID_is_valid_handle_ (daemon->tid)); 6136 6137 if (0 > millisec) 6138 millisec = -1; 6139 #ifdef HAVE_POLL 6140 if (MHD_D_IS_USING_POLL_ (daemon)) 6141 { 6142 res = MHD_poll_all (daemon, millisec); 6143 MHD_cleanup_connections (daemon); 6144 } 6145 else 6146 #endif /* HAVE_POLL */ 6147 #ifdef EPOLL_SUPPORT 6148 if (MHD_D_IS_USING_EPOLL_ (daemon)) 6149 { 6150 res = MHD_epoll (daemon, millisec); 6151 MHD_cleanup_connections (daemon); 6152 } 6153 else 6154 #endif 6155 if (1) 6156 { 6157 mhd_assert (MHD_D_IS_USING_SELECT_ (daemon)); 6158 #ifdef HAS_FD_SETSIZE_OVERRIDABLE 6159 #ifdef HAVE_MESSAGES 6160 if (daemon->fdset_size_set_by_app 6161 && (((int) FD_SETSIZE) < daemon->fdset_size)) 6162 { 6163 MHD_DLOG (daemon, 6164 _ ("MHD_run()/MHD_run_wait() called for daemon started with " \ 6165 "MHD_OPTION_APP_FD_SETSIZE option (%d). " \ 6166 "The library was compiled with smaller FD_SETSIZE (%d). " \ 6167 "Some socket FDs may be not processed. " \ 6168 "Use MHD_run_from_select2() instead of MHD_run() or " \ 6169 "do not use MHD_OPTION_APP_FD_SETSIZE option.\n"), 6170 daemon->fdset_size, (int) FD_SETSIZE); 6171 } 6172 #endif /* HAVE_MESSAGES */ 6173 #endif /* HAS_FD_SETSIZE_OVERRIDABLE */ 6174 6175 res = MHD_select (daemon, millisec); 6176 /* MHD_select does MHD_cleanup_connections already */ 6177 } 6178 return res; 6179 } 6180 6181 6182 /** 6183 * Close the given connection, remove it from all of its 6184 * DLLs and move it into the cleanup queue. 6185 * @remark To be called only from thread that 6186 * process daemon's select()/poll()/etc. 6187 * 6188 * @param pos connection to move to cleanup 6189 */ 6190 static void 6191 close_connection (struct MHD_Connection *pos) 6192 { 6193 struct MHD_Daemon *daemon = pos->daemon; 6194 6195 #ifdef MHD_USE_THREADS 6196 mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ 6197 MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); 6198 mhd_assert (NULL == daemon->worker_pool); 6199 #endif /* MHD_USE_THREADS */ 6200 6201 if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) 6202 { 6203 MHD_connection_mark_closed_ (pos); 6204 return; /* must let thread to do the rest */ 6205 } 6206 MHD_connection_close_ (pos, 6207 MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN); 6208 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 6209 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); 6210 #endif 6211 mhd_assert (! pos->suspended); 6212 mhd_assert (! pos->resuming); 6213 if (pos->connection_timeout_ms == daemon->connection_timeout_ms) 6214 XDLL_remove (daemon->normal_timeout_head, 6215 daemon->normal_timeout_tail, 6216 pos); 6217 else 6218 XDLL_remove (daemon->manual_timeout_head, 6219 daemon->manual_timeout_tail, 6220 pos); 6221 DLL_remove (daemon->connections_head, 6222 daemon->connections_tail, 6223 pos); 6224 DLL_insert (daemon->cleanup_head, 6225 daemon->cleanup_tail, 6226 pos); 6227 daemon->data_already_pending = true; 6228 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 6229 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); 6230 #endif 6231 } 6232 6233 6234 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 6235 /** 6236 * Thread that runs the polling loop until the daemon 6237 * is explicitly shut down. 6238 * 6239 * @param cls `struct MHD_Deamon` to run select loop in a thread for 6240 * @return always 0 (on shutdown) 6241 */ 6242 static MHD_THRD_RTRN_TYPE_ MHD_THRD_CALL_SPEC_ 6243 MHD_polling_thread (void *cls) 6244 { 6245 struct MHD_Daemon *daemon = cls; 6246 #ifdef HAVE_PTHREAD_SIGMASK 6247 sigset_t s_mask; 6248 int err; 6249 #endif /* HAVE_PTHREAD_SIGMASK */ 6250 6251 MHD_thread_handle_ID_set_current_thread_ID_ (&(daemon->tid)); 6252 #ifdef HAVE_PTHREAD_SIGMASK 6253 if ((0 == sigemptyset (&s_mask)) && 6254 (0 == sigaddset (&s_mask, SIGPIPE))) 6255 { 6256 err = pthread_sigmask (SIG_BLOCK, &s_mask, NULL); 6257 } 6258 else 6259 err = errno; 6260 if (0 == err) 6261 daemon->sigpipe_blocked = true; 6262 #ifdef HAVE_MESSAGES 6263 else 6264 MHD_DLOG (daemon, 6265 _ ("Failed to block SIGPIPE on daemon thread: %s\n"), 6266 MHD_strerror_ (errno)); 6267 #endif /* HAVE_MESSAGES */ 6268 #endif /* HAVE_PTHREAD_SIGMASK */ 6269 while (! daemon->shutdown) 6270 { 6271 #ifdef HAVE_POLL 6272 if (MHD_D_IS_USING_POLL_ (daemon)) 6273 MHD_poll (daemon, MHD_YES); 6274 else 6275 #endif /* HAVE_POLL */ 6276 #ifdef EPOLL_SUPPORT 6277 if (MHD_D_IS_USING_EPOLL_ (daemon)) 6278 MHD_epoll (daemon, -1); 6279 else 6280 #endif 6281 MHD_select (daemon, -1); 6282 MHD_cleanup_connections (daemon); 6283 } 6284 6285 /* Resume any pending for resume connections, join 6286 * all connection's threads (if any) and finally cleanup 6287 * everything. */ 6288 if (0 != (MHD_TEST_ALLOW_SUSPEND_RESUME & daemon->options)) 6289 resume_suspended_connections (daemon); 6290 close_all_connections (daemon); 6291 6292 return (MHD_THRD_RTRN_TYPE_) 0; 6293 } 6294 6295 6296 #endif 6297 6298 6299 /** 6300 * Process escape sequences ('%HH') Updates val in place; the 6301 * result cannot be larger than the input. 6302 * The result must also still be 0-terminated. 6303 * 6304 * @param cls closure (use NULL) 6305 * @param connection handle to connection, not used 6306 * @param val value to unescape (modified in the process) 6307 * @return length of the resulting val (strlen(val) maybe 6308 * shorter afterwards due to elimination of escape sequences) 6309 */ 6310 static size_t 6311 unescape_wrapper (void *cls, 6312 struct MHD_Connection *connection, 6313 char *val) 6314 { 6315 bool broken; 6316 size_t res; 6317 (void) cls; /* Mute compiler warning. */ 6318 6319 /* TODO: add individual parameter */ 6320 if (0 <= connection->daemon->client_discipline) 6321 return MHD_str_pct_decode_in_place_strict_ (val); 6322 6323 res = MHD_str_pct_decode_in_place_lenient_ (val, &broken); 6324 #ifdef HAVE_MESSAGES 6325 if (broken) 6326 { 6327 MHD_DLOG (connection->daemon, 6328 _ ("The URL encoding is broken.\n")); 6329 } 6330 #endif /* HAVE_MESSAGES */ 6331 return res; 6332 } 6333 6334 6335 /** 6336 * Start a webserver on the given port. Variadic version of 6337 * #MHD_start_daemon_va. 6338 * 6339 * @param flags combination of `enum MHD_FLAG` values 6340 * @param port port to bind to (in host byte order), 6341 * use '0' to bind to random free port, 6342 * ignored if #MHD_OPTION_SOCK_ADDR or 6343 * #MHD_OPTION_LISTEN_SOCKET is provided 6344 * or #MHD_USE_NO_LISTEN_SOCKET is specified 6345 * @param apc callback to call to check which clients 6346 * will be allowed to connect; you can pass NULL 6347 * in which case connections from any IP will be 6348 * accepted 6349 * @param apc_cls extra argument to @a apc 6350 * @param dh handler called for all requests (repeatedly) 6351 * @param dh_cls extra argument to @a dh 6352 * @return NULL on error, handle to daemon on success 6353 * @ingroup event 6354 */ 6355 _MHD_EXTERN struct MHD_Daemon * 6356 MHD_start_daemon (unsigned int flags, 6357 uint16_t port, 6358 MHD_AcceptPolicyCallback apc, 6359 void *apc_cls, 6360 MHD_AccessHandlerCallback dh, 6361 void *dh_cls, 6362 ...) 6363 { 6364 struct MHD_Daemon *daemon; 6365 va_list ap; 6366 6367 va_start (ap, 6368 dh_cls); 6369 daemon = MHD_start_daemon_va (flags, 6370 port, 6371 apc, 6372 apc_cls, 6373 dh, 6374 dh_cls, 6375 ap); 6376 va_end (ap); 6377 return daemon; 6378 } 6379 6380 6381 /** 6382 * Stop accepting connections from the listening socket. Allows 6383 * clients to continue processing, but stops accepting new 6384 * connections. Note that the caller is responsible for closing the 6385 * returned socket; however, if MHD is run using threads (anything but 6386 * external select mode), socket will be removed from existing threads 6387 * with some delay and it must not be closed while it's in use. To make 6388 * sure that the socket is not used anymore, call #MHD_stop_daemon. 6389 * 6390 * Note that some thread modes require the caller to have passed 6391 * #MHD_USE_ITC when using this API. If this daemon is 6392 * in one of those modes and this option was not given to 6393 * #MHD_start_daemon, this function will return #MHD_INVALID_SOCKET. 6394 * 6395 * @param daemon daemon to stop accepting new connections for 6396 * @return old listen socket on success, #MHD_INVALID_SOCKET if 6397 * the daemon was already not listening anymore 6398 * @ingroup specialized 6399 */ 6400 _MHD_EXTERN MHD_socket 6401 MHD_quiesce_daemon (struct MHD_Daemon *daemon) 6402 { 6403 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 6404 unsigned int i; 6405 #endif 6406 MHD_socket ret; 6407 6408 ret = daemon->listen_fd; 6409 if ((MHD_INVALID_SOCKET == ret) 6410 || daemon->was_quiesced) 6411 return MHD_INVALID_SOCKET; 6412 if ( (0 == (daemon->options & (MHD_USE_ITC))) && 6413 MHD_D_IS_USING_THREADS_ (daemon) ) 6414 { 6415 #ifdef HAVE_MESSAGES 6416 MHD_DLOG (daemon, 6417 _ ("Using MHD_quiesce_daemon in this mode " \ 6418 "requires MHD_USE_ITC.\n")); 6419 #endif 6420 return MHD_INVALID_SOCKET; 6421 } 6422 6423 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 6424 if (NULL != daemon->worker_pool) 6425 for (i = 0; i < daemon->worker_pool_size; i++) 6426 { 6427 /* Each worker is an independent daemon with its own epoll set and 6428 its own lock; they are taken one at a time and never nested, so 6429 there is no ordering to get wrong. Holding the worker's lock 6430 is what stops it removing the same descriptor concurrently from 6431 its own MHD_epoll(). */ 6432 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 6433 MHD_mutex_lock_chk_ (&daemon->worker_pool[i].epoll_listen_mutex); 6434 #endif 6435 daemon->worker_pool[i].was_quiesced = true; 6436 #ifdef EPOLL_SUPPORT 6437 if (MHD_D_IS_USING_EPOLL_ (daemon) && 6438 (-1 != daemon->worker_pool[i].epoll_fd) && 6439 (daemon->worker_pool[i].listen_socket_in_epoll) ) 6440 { 6441 if (0 != epoll_ctl (daemon->worker_pool[i].epoll_fd, 6442 EPOLL_CTL_DEL, 6443 ret, 6444 NULL)) 6445 MHD_PANIC (_ ("Failed to remove listen FD from epoll set.\n")); 6446 daemon->worker_pool[i].listen_socket_in_epoll = false; 6447 } 6448 else 6449 #endif 6450 if (MHD_ITC_IS_VALID_ (daemon->worker_pool[i].itc)) 6451 { 6452 if (! MHD_itc_activate_ (daemon->worker_pool[i].itc, "q")) 6453 MHD_PANIC (_ ("Failed to signal quiesce via inter-thread " \ 6454 "communication channel.\n")); 6455 } 6456 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 6457 MHD_mutex_unlock_chk_ (&daemon->worker_pool[i].epoll_listen_mutex); 6458 #endif 6459 } 6460 #endif 6461 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 6462 MHD_mutex_lock_chk_ (&daemon->epoll_listen_mutex); 6463 #endif 6464 daemon->was_quiesced = true; 6465 #ifdef EPOLL_SUPPORT 6466 if (MHD_D_IS_USING_EPOLL_ (daemon) && 6467 (-1 != daemon->epoll_fd) && 6468 (daemon->listen_socket_in_epoll) ) 6469 { 6470 if (0 != epoll_ctl (daemon->epoll_fd, 6471 EPOLL_CTL_DEL, 6472 ret, 6473 NULL)) 6474 MHD_PANIC ("Failed to remove listen FD from epoll set.\n"); 6475 daemon->listen_socket_in_epoll = false; 6476 } 6477 #endif 6478 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 6479 MHD_mutex_unlock_chk_ (&daemon->epoll_listen_mutex); 6480 #endif 6481 if ( (MHD_ITC_IS_VALID_ (daemon->itc)) && 6482 (! MHD_itc_activate_ (daemon->itc, "q")) ) 6483 MHD_PANIC (_ ("failed to signal quiesce via inter-thread " \ 6484 "communication channel.\n")); 6485 return ret; 6486 } 6487 6488 6489 /** 6490 * Temporal location of the application-provided parameters/options. 6491 * Used when options are decoded from #MHD_start_deamon() parameters, but 6492 * not yet processed/applied. 6493 */ 6494 struct MHD_InterimParams_ 6495 { 6496 /** 6497 * The total number of all user options used. 6498 * 6499 * Contains number only of meaningful options, i.e. #MHD_OPTION_END and 6500 * #MHD_OPTION_ARRAY themselves are not counted, while options inside 6501 * #MHD_OPTION_ARRAY are counted. 6502 */ 6503 size_t num_opts; 6504 /** 6505 * Set to 'true' if @a fdset_size is set by application. 6506 */ 6507 bool fdset_size_set; 6508 /** 6509 * The value for #MHD_OPTION_APP_FD_SETSIZE set by application. 6510 */ 6511 int fdset_size; 6512 /** 6513 * Set to 'true' if @a listen_fd is set by application. 6514 */ 6515 bool listen_fd_set; 6516 /** 6517 * Application-provided listen socket. 6518 */ 6519 MHD_socket listen_fd; 6520 /** 6521 * Set to 'true' if @a server_addr is set by application. 6522 */ 6523 bool pserver_addr_set; 6524 /** 6525 * Application-provided struct sockaddr to bind server to. 6526 */ 6527 const struct sockaddr *pserver_addr; 6528 /** 6529 * Set to 'true' if @a server_addr_len is set by application. 6530 */ 6531 bool server_addr_len_set; 6532 /** 6533 * Applicaiton-provided the size of the memory pointed by @a server_addr. 6534 */ 6535 socklen_t server_addr_len; 6536 }; 6537 6538 /** 6539 * Signature of the MHD custom logger function. 6540 * 6541 * @param cls closure 6542 * @param format format string 6543 * @param va arguments to the format string (fprintf-style) 6544 */ 6545 typedef void 6546 (*VfprintfFunctionPointerType)(void *cls, 6547 const char *format, 6548 va_list va); 6549 6550 6551 /** 6552 * Parse a list of options given as varargs. 6553 * 6554 * @param daemon the daemon to initialize 6555 * @param servaddr where to store the server's listen address 6556 * @param params the interim parameters to be assigned to 6557 * @param ap the options 6558 * @return #MHD_YES on success, #MHD_NO on error 6559 */ 6560 static enum MHD_Result 6561 parse_options_va (struct MHD_Daemon *daemon, 6562 struct MHD_InterimParams_ *params, 6563 va_list ap); 6564 6565 6566 /** 6567 * Parse a list of options given as varargs. 6568 * 6569 * @param daemon the daemon to initialize 6570 * @param servaddr where to store the server's listen address 6571 * @param params the interim parameters to be assigned to 6572 * @param ... the options 6573 * @return #MHD_YES on success, #MHD_NO on error 6574 */ 6575 static enum MHD_Result 6576 parse_options (struct MHD_Daemon *daemon, 6577 struct MHD_InterimParams_ *params, 6578 ...) 6579 { 6580 va_list ap; 6581 enum MHD_Result ret; 6582 6583 va_start (ap, params); 6584 ret = parse_options_va (daemon, 6585 params, 6586 ap); 6587 va_end (ap); 6588 return ret; 6589 } 6590 6591 6592 #ifdef HTTPS_SUPPORT 6593 /** 6594 * Type of GnuTLS priorities base string 6595 */ 6596 enum MHD_TlsPrioritiesBaseType 6597 { 6598 MHD_TLS_PRIO_BASE_LIBMHD = 0, /**< @c "@LIBMICROHTTPD" */ 6599 MHD_TLS_PRIO_BASE_SYSTEM = 1, /**< @c "@SYSTEM" */ 6600 #if GNUTLS_VERSION_NUMBER >= 0x030300 6601 MHD_TLS_PRIO_BASE_DEFAULT, /**< Default priorities string */ 6602 #endif /* GNUTLS_VERSION_NUMBER >= 0x030300 */ 6603 MHD_TLS_PRIO_BASE_NORMAL /**< @c "NORMAL */ 6604 }; 6605 6606 static const struct _MHD_cstr_w_len MHD_TlsBasePriotities[] = { 6607 _MHD_S_STR_W_LEN ("@LIBMICROHTTPD"), 6608 _MHD_S_STR_W_LEN ("@SYSTEM"), 6609 #if GNUTLS_VERSION_NUMBER >= 0x030300 6610 {NULL, 0}, 6611 #endif /* GNUTLS_VERSION_NUMBER >= 0x030300 */ 6612 _MHD_S_STR_W_LEN ("NORMAL") 6613 }; 6614 6615 /** 6616 * Initialise TLS priorities with default settings 6617 * @param daemon the daemon to initialise TLS priorities 6618 * @return true on success, false on error 6619 */ 6620 static bool 6621 daemon_tls_priorities_init_default (struct MHD_Daemon *daemon) 6622 { 6623 unsigned int p; 6624 int res; 6625 6626 mhd_assert (0 != (((unsigned int) daemon->options) & MHD_USE_TLS)); 6627 mhd_assert (NULL == daemon->priority_cache); 6628 mhd_assert (MHD_TLS_PRIO_BASE_NORMAL + 1 == \ 6629 sizeof(MHD_TlsBasePriotities) / sizeof(MHD_TlsBasePriotities[0])); 6630 6631 res = GNUTLS_E_SUCCESS; /* Mute compiler warning */ 6632 6633 for (p = 0; 6634 p < sizeof(MHD_TlsBasePriotities) / sizeof(MHD_TlsBasePriotities[0]); 6635 ++p) 6636 { 6637 res = gnutls_priority_init (&daemon->priority_cache, 6638 MHD_TlsBasePriotities[p].str, NULL); 6639 if (GNUTLS_E_SUCCESS == res) 6640 { 6641 #ifdef _DEBUG 6642 #ifdef HAVE_MESSAGES 6643 switch ((enum MHD_TlsPrioritiesBaseType) p) 6644 { 6645 case MHD_TLS_PRIO_BASE_LIBMHD: 6646 MHD_DLOG (daemon, 6647 _ ("GnuTLS priorities have been initialised with " \ 6648 "@LIBMICROHTTPD application-specific system-wide " \ 6649 "configuration.\n") ); 6650 break; 6651 case MHD_TLS_PRIO_BASE_SYSTEM: 6652 MHD_DLOG (daemon, 6653 _ ("GnuTLS priorities have been initialised with " \ 6654 "@SYSTEM system-wide configuration.\n") ); 6655 break; 6656 #if GNUTLS_VERSION_NUMBER >= 0x030300 6657 case MHD_TLS_PRIO_BASE_DEFAULT: 6658 MHD_DLOG (daemon, 6659 _ ("GnuTLS priorities have been initialised with " \ 6660 "GnuTLS default configuration.\n") ); 6661 break; 6662 #endif /* GNUTLS_VERSION_NUMBER >= 0x030300 */ 6663 case MHD_TLS_PRIO_BASE_NORMAL: 6664 MHD_DLOG (daemon, 6665 _ ("GnuTLS priorities have been initialised with " \ 6666 "NORMAL configuration.\n") ); 6667 break; 6668 default: 6669 mhd_assert (0); 6670 } 6671 #endif /* HAVE_MESSAGES */ 6672 #endif /* _DEBUG */ 6673 return true; 6674 } 6675 } 6676 #ifdef HAVE_MESSAGES 6677 MHD_DLOG (daemon, 6678 _ ("Failed to set GnuTLS priorities. Last error: %s\n"), 6679 gnutls_strerror (res)); 6680 #endif /* HAVE_MESSAGES */ 6681 return false; 6682 } 6683 6684 6685 /** 6686 * The inner helper function for #daemon_tls_priorities_init_app(). 6687 * @param daemon the daemon to use 6688 * @param prio the appication-specified appendix for default priorities 6689 * @param prio_len the length of @a prio 6690 * @param buf the temporal buffer for string manipulations 6691 * @param buf_size the size of the @a buf 6692 * @return true on success, false on error 6693 */ 6694 static bool 6695 daemon_tls_priorities_init_append_inner_ (struct MHD_Daemon *daemon, 6696 const char *prio, 6697 size_t prio_len, 6698 char *buf, 6699 const size_t buf_size) 6700 { 6701 unsigned int p; 6702 int res; 6703 const char *err_pos; 6704 6705 (void) buf_size; /* Mute compiler warning for non-Debug builds */ 6706 mhd_assert (0 != (((unsigned int) daemon->options) & MHD_USE_TLS)); 6707 mhd_assert (NULL == daemon->priority_cache); 6708 mhd_assert (MHD_TLS_PRIO_BASE_NORMAL + 1 == \ 6709 sizeof(MHD_TlsBasePriotities) / sizeof(MHD_TlsBasePriotities[0])); 6710 6711 res = GNUTLS_E_SUCCESS; /* Mute compiler warning */ 6712 err_pos = ""; /* Mute compiler warning */ 6713 6714 for (p = 0; 6715 p < sizeof(MHD_TlsBasePriotities) / sizeof(MHD_TlsBasePriotities[0]); 6716 ++p) 6717 { 6718 6719 #if GNUTLS_VERSION_NUMBER >= 0x030300 6720 #if GNUTLS_VERSION_NUMBER >= 0x030603 6721 if (NULL == MHD_TlsBasePriotities[p].str) 6722 res = gnutls_priority_init2 (&daemon->priority_cache, prio, &err_pos, 6723 GNUTLS_PRIORITY_INIT_DEF_APPEND); 6724 else 6725 #else /* 0x030300 <= GNUTLS_VERSION_NUMBER 6726 && GNUTLS_VERSION_NUMBER < 0x030603 */ 6727 if (NULL == MHD_TlsBasePriotities[p].str) 6728 continue; /* Skip the value, no way to append priorities to the default string */ 6729 else 6730 #endif /* GNUTLS_VERSION_NUMBER < 0x030603 */ 6731 #endif /* GNUTLS_VERSION_NUMBER >= 0x030300 */ 6732 if (1) 6733 { 6734 size_t buf_pos; 6735 6736 mhd_assert (NULL != MHD_TlsBasePriotities[p].str); 6737 buf_pos = 0; 6738 memcpy (buf + buf_pos, MHD_TlsBasePriotities[p].str, 6739 MHD_TlsBasePriotities[p].len); 6740 buf_pos += MHD_TlsBasePriotities[p].len; 6741 buf[buf_pos++] = ':'; 6742 memcpy (buf + buf_pos, prio, prio_len + 1); 6743 #ifdef _DEBUG 6744 buf_pos += prio_len + 1; 6745 mhd_assert (buf_size >= buf_pos); 6746 #endif /* _DEBUG */ 6747 res = gnutls_priority_init (&daemon->priority_cache, buf, &err_pos); 6748 } 6749 if (GNUTLS_E_SUCCESS == res) 6750 { 6751 #ifdef _DEBUG 6752 #ifdef HAVE_MESSAGES 6753 switch ((enum MHD_TlsPrioritiesBaseType) p) 6754 { 6755 case MHD_TLS_PRIO_BASE_LIBMHD: 6756 MHD_DLOG (daemon, 6757 _ ("GnuTLS priorities have been initialised with " \ 6758 "priorities specified by application appended to " \ 6759 "@LIBMICROHTTPD application-specific system-wide " \ 6760 "configuration.\n") ); 6761 break; 6762 case MHD_TLS_PRIO_BASE_SYSTEM: 6763 MHD_DLOG (daemon, 6764 _ ("GnuTLS priorities have been initialised with " \ 6765 "priorities specified by application appended to " \ 6766 "@SYSTEM system-wide configuration.\n") ); 6767 break; 6768 #if GNUTLS_VERSION_NUMBER >= 0x030300 6769 case MHD_TLS_PRIO_BASE_DEFAULT: 6770 MHD_DLOG (daemon, 6771 _ ("GnuTLS priorities have been initialised with " \ 6772 "priorities specified by application appended to " \ 6773 "GnuTLS default configuration.\n") ); 6774 break; 6775 #endif /* GNUTLS_VERSION_NUMBER >= 0x030300 */ 6776 case MHD_TLS_PRIO_BASE_NORMAL: 6777 MHD_DLOG (daemon, 6778 _ ("GnuTLS priorities have been initialised with " \ 6779 "priorities specified by application appended to " \ 6780 "NORMAL configuration.\n") ); 6781 break; 6782 default: 6783 mhd_assert (0); 6784 } 6785 #endif /* HAVE_MESSAGES */ 6786 #endif /* _DEBUG */ 6787 return true; 6788 } 6789 } 6790 #ifdef HAVE_MESSAGES 6791 MHD_DLOG (daemon, 6792 _ ("Failed to set GnuTLS priorities. Last error: %s. " \ 6793 "The problematic part starts at: %s\n"), 6794 gnutls_strerror (res), err_pos); 6795 #endif /* HAVE_MESSAGES */ 6796 return false; 6797 } 6798 6799 6800 #define LOCAL_BUFF_SIZE 128 6801 6802 /** 6803 * Initialise TLS priorities with default settings with application-specified 6804 * appended string. 6805 * @param daemon the daemon to initialise TLS priorities 6806 * @param prio the application specified priorities to be appended to 6807 * the GnuTLS standard priorities string 6808 * @return true on success, false on error 6809 */ 6810 static bool 6811 daemon_tls_priorities_init_append (struct MHD_Daemon *daemon, const char *prio) 6812 { 6813 static const size_t longest_base_prio = MHD_STATICSTR_LEN_ ("@LIBMICROHTTPD"); 6814 bool ret; 6815 size_t prio_len; 6816 size_t buf_size_needed; 6817 6818 if (NULL == prio) 6819 return daemon_tls_priorities_init_default (daemon); 6820 6821 if (':' == prio[0]) 6822 ++prio; 6823 6824 prio_len = strlen (prio); 6825 6826 buf_size_needed = longest_base_prio + 1 + prio_len + 1; 6827 6828 if (LOCAL_BUFF_SIZE >= buf_size_needed) 6829 { 6830 char local_buffer[LOCAL_BUFF_SIZE]; 6831 ret = daemon_tls_priorities_init_append_inner_ (daemon, prio, prio_len, 6832 local_buffer, 6833 LOCAL_BUFF_SIZE); 6834 } 6835 else 6836 { 6837 char *allocated_buffer; 6838 allocated_buffer = (char *) malloc (buf_size_needed); 6839 if (NULL == allocated_buffer) 6840 { 6841 #ifdef HAVE_MESSAGES 6842 MHD_DLOG (daemon, 6843 _ ("Error allocating memory: %s\n"), 6844 MHD_strerror_ (errno)); 6845 #endif 6846 return false; 6847 } 6848 ret = daemon_tls_priorities_init_append_inner_ (daemon, prio, prio_len, 6849 allocated_buffer, 6850 buf_size_needed); 6851 free (allocated_buffer); 6852 } 6853 return ret; 6854 } 6855 6856 6857 #endif /* HTTPS_SUPPORT */ 6858 6859 6860 /** 6861 * Parse a list of options given as varargs. 6862 * 6863 * @param[in,out] daemon the daemon to initialize 6864 * @param[out] params the interim parameters to be assigned to 6865 * @param ap the options 6866 * @return #MHD_YES on success, #MHD_NO on error 6867 */ 6868 static enum MHD_Result 6869 parse_options_va (struct MHD_Daemon *daemon, 6870 struct MHD_InterimParams_ *params, 6871 va_list ap) 6872 { 6873 enum MHD_OPTION opt; 6874 struct MHD_OptionItem *oa; 6875 unsigned int i; 6876 unsigned int uv; 6877 #ifdef HTTPS_SUPPORT 6878 const char *pstr; 6879 #if GNUTLS_VERSION_MAJOR >= 3 6880 gnutls_certificate_retrieve_function2 * pgcrf; 6881 #endif 6882 #if GNUTLS_VERSION_NUMBER >= 0x030603 6883 gnutls_certificate_retrieve_function3 * pgcrf2; 6884 #endif 6885 #endif /* HTTPS_SUPPORT */ 6886 6887 while (MHD_OPTION_END != (opt = (enum MHD_OPTION) va_arg (ap, int))) 6888 { 6889 /* Increase counter at start, so resulting value is number of 6890 * processed options, including any failed ones. */ 6891 params->num_opts++; 6892 switch (opt) 6893 { 6894 case MHD_OPTION_CONNECTION_MEMORY_LIMIT: 6895 if (1) 6896 { 6897 size_t val; 6898 6899 val = va_arg (ap, 6900 size_t); 6901 if (0 != val) 6902 { 6903 daemon->pool_size = val; 6904 if (64 > daemon->pool_size) 6905 { 6906 #ifdef HAVE_MESSAGES 6907 MHD_DLOG (daemon, 6908 _ ("Warning: specified " \ 6909 "MHD_OPTION_CONNECTION_MEMORY_LIMIT " \ 6910 "value is too small and rounded up to 64.\n")); 6911 #endif /* HAVE_MESSAGES */ 6912 daemon->pool_size = 64; 6913 } 6914 if (daemon->pool_size / 4 < daemon->pool_increment) 6915 daemon->pool_increment = daemon->pool_size / 4; 6916 } 6917 } 6918 break; 6919 case MHD_OPTION_CONNECTION_MEMORY_INCREMENT: 6920 if (1) 6921 { 6922 size_t val; 6923 6924 val = va_arg (ap, 6925 size_t); 6926 6927 if (0 != val) 6928 { 6929 daemon->pool_increment = val; 6930 if (daemon->pool_size / 4 < daemon->pool_increment) 6931 { 6932 #ifdef HAVE_MESSAGES 6933 MHD_DLOG (daemon, 6934 _ ("Warning: specified " \ 6935 "MHD_OPTION_CONNECTION_MEMORY_INCREMENT value is " \ 6936 "too large and rounded down to 1/4 of " \ 6937 "MHD_OPTION_CONNECTION_MEMORY_LIMIT.\n")); 6938 #endif /* HAVE_MESSAGES */ 6939 daemon->pool_increment = daemon->pool_size / 4; 6940 } 6941 } 6942 } 6943 break; 6944 case MHD_OPTION_CONNECTION_LIMIT: 6945 daemon->connection_limit = va_arg (ap, 6946 unsigned int); 6947 break; 6948 case MHD_OPTION_CONNECTION_TIMEOUT: 6949 uv = va_arg (ap, 6950 unsigned int); 6951 #if (SIZEOF_UINT64_T - 2) <= SIZEOF_UNSIGNED_INT 6952 if ((UINT64_MAX / 4000 - 1) < uv) 6953 { 6954 #ifdef HAVE_MESSAGES 6955 MHD_DLOG (daemon, 6956 _ ("The specified connection timeout (%u) is too large. " \ 6957 "Maximum allowed value (%" PRIu64 ") will be used " \ 6958 "instead.\n"), 6959 uv, 6960 (UINT64_MAX / 4000 - 1)); 6961 #endif 6962 uv = UINT64_MAX / 4000 - 1; 6963 } 6964 #endif /* (SIZEOF_UINT64_T - 2) <= SIZEOF_UNSIGNED_INT */ 6965 daemon->connection_timeout_ms = ((uint64_t) uv) * 1000; 6966 break; 6967 case MHD_OPTION_NOTIFY_COMPLETED: 6968 daemon->notify_completed = va_arg (ap, 6969 MHD_RequestCompletedCallback); 6970 daemon->notify_completed_cls = va_arg (ap, 6971 void *); 6972 break; 6973 case MHD_OPTION_NOTIFY_CONNECTION: 6974 daemon->notify_connection = va_arg (ap, 6975 MHD_NotifyConnectionCallback); 6976 daemon->notify_connection_cls = va_arg (ap, 6977 void *); 6978 break; 6979 case MHD_OPTION_PER_IP_CONNECTION_LIMIT: 6980 daemon->per_ip_connection_limit = va_arg (ap, 6981 unsigned int); 6982 break; 6983 case MHD_OPTION_SOCK_ADDR_LEN: 6984 params->server_addr_len = va_arg (ap, 6985 socklen_t); 6986 params->server_addr_len_set = true; 6987 params->pserver_addr = va_arg (ap, 6988 const struct sockaddr *); 6989 params->pserver_addr_set = true; 6990 break; 6991 case MHD_OPTION_SOCK_ADDR: 6992 params->server_addr_len_set = false; 6993 params->pserver_addr = va_arg (ap, 6994 const struct sockaddr *); 6995 params->pserver_addr_set = true; 6996 break; 6997 case MHD_OPTION_URI_LOG_CALLBACK: 6998 daemon->uri_log_callback = va_arg (ap, 6999 LogCallback); 7000 daemon->uri_log_callback_cls = va_arg (ap, 7001 void *); 7002 break; 7003 case MHD_OPTION_SERVER_INSANITY: 7004 daemon->insanity_level = (enum MHD_DisableSanityCheck) 7005 va_arg (ap, 7006 unsigned int); 7007 break; 7008 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 7009 case MHD_OPTION_THREAD_POOL_SIZE: 7010 daemon->worker_pool_size = va_arg (ap, 7011 unsigned int); 7012 if (0 == daemon->worker_pool_size) 7013 { 7014 (void) 0; /* MHD_OPTION_THREAD_POOL_SIZE ignored, do nothing */ 7015 } 7016 else if (1 == daemon->worker_pool_size) 7017 { 7018 #ifdef HAVE_MESSAGES 7019 MHD_DLOG (daemon, 7020 _ ("Warning: value \"1\", specified as the thread pool " \ 7021 "size, is ignored. Thread pool is not used.\n")); 7022 #endif 7023 daemon->worker_pool_size = 0; 7024 } 7025 #if SIZEOF_UNSIGNED_INT >= (SIZEOF_SIZE_T - 2) 7026 /* Next comparison could be always false on some platforms and whole branch will 7027 * be optimized out on these platforms. On others it will be compiled into real 7028 * check. */ 7029 else if (daemon->worker_pool_size >= 7030 (SIZE_MAX / sizeof (struct MHD_Daemon))) /* Compiler may warn on some platforms, ignore warning. */ 7031 { 7032 #ifdef HAVE_MESSAGES 7033 MHD_DLOG (daemon, 7034 _ ("Specified thread pool size (%u) too big.\n"), 7035 daemon->worker_pool_size); 7036 #endif 7037 return MHD_NO; 7038 } 7039 #endif /* SIZEOF_UNSIGNED_INT >= (SIZEOF_SIZE_T - 2) */ 7040 else 7041 { 7042 if (! MHD_D_IS_USING_THREADS_ (daemon)) 7043 { 7044 #ifdef HAVE_MESSAGES 7045 MHD_DLOG (daemon, 7046 _ ("MHD_OPTION_THREAD_POOL_SIZE option is specified but " 7047 "MHD_USE_INTERNAL_POLLING_THREAD flag is not specified.\n")); 7048 #endif 7049 return MHD_NO; 7050 } 7051 if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) 7052 { 7053 #ifdef HAVE_MESSAGES 7054 MHD_DLOG (daemon, 7055 _ ("Both MHD_OPTION_THREAD_POOL_SIZE option and " 7056 "MHD_USE_THREAD_PER_CONNECTION flag are specified.\n")); 7057 #endif 7058 return MHD_NO; 7059 } 7060 } 7061 break; 7062 #endif 7063 #ifdef HTTPS_SUPPORT 7064 case MHD_OPTION_HTTPS_MEM_KEY: 7065 pstr = va_arg (ap, 7066 const char *); 7067 if (0 != (daemon->options & MHD_USE_TLS)) 7068 daemon->https_mem_key = pstr; 7069 #ifdef HAVE_MESSAGES 7070 else 7071 MHD_DLOG (daemon, 7072 _ ("MHD HTTPS option %d passed to MHD but " \ 7073 "MHD_USE_TLS not set.\n"), 7074 opt); 7075 #endif 7076 break; 7077 case MHD_OPTION_HTTPS_KEY_PASSWORD: 7078 pstr = va_arg (ap, 7079 const char *); 7080 if (0 != (daemon->options & MHD_USE_TLS)) 7081 daemon->https_key_password = pstr; 7082 #ifdef HAVE_MESSAGES 7083 else 7084 MHD_DLOG (daemon, 7085 _ ("MHD HTTPS option %d passed to MHD but " \ 7086 "MHD_USE_TLS not set.\n"), 7087 opt); 7088 #endif 7089 break; 7090 case MHD_OPTION_HTTPS_MEM_CERT: 7091 pstr = va_arg (ap, 7092 const char *); 7093 if (0 != (daemon->options & MHD_USE_TLS)) 7094 daemon->https_mem_cert = pstr; 7095 #ifdef HAVE_MESSAGES 7096 else 7097 MHD_DLOG (daemon, 7098 _ ("MHD HTTPS option %d passed to MHD but " \ 7099 "MHD_USE_TLS not set.\n"), 7100 opt); 7101 #endif 7102 break; 7103 case MHD_OPTION_HTTPS_MEM_TRUST: 7104 pstr = va_arg (ap, 7105 const char *); 7106 if (0 != (daemon->options & MHD_USE_TLS)) 7107 daemon->https_mem_trust = pstr; 7108 #ifdef HAVE_MESSAGES 7109 else 7110 MHD_DLOG (daemon, 7111 _ ("MHD HTTPS option %d passed to MHD but " \ 7112 "MHD_USE_TLS not set.\n"), 7113 opt); 7114 #endif 7115 break; 7116 case MHD_OPTION_HTTPS_CRED_TYPE: 7117 daemon->cred_type = (gnutls_credentials_type_t) va_arg (ap, 7118 int); 7119 break; 7120 case MHD_OPTION_HTTPS_MEM_DHPARAMS: 7121 pstr = va_arg (ap, 7122 const char *); 7123 if (0 != (daemon->options & MHD_USE_TLS)) 7124 { 7125 gnutls_datum_t dhpar; 7126 size_t pstr_len; 7127 7128 if (gnutls_dh_params_init (&daemon->https_mem_dhparams) < 0) 7129 { 7130 #ifdef HAVE_MESSAGES 7131 MHD_DLOG (daemon, 7132 _ ("Error initializing DH parameters.\n")); 7133 #endif 7134 return MHD_NO; 7135 } 7136 dhpar.data = (unsigned char *) _MHD_DROP_CONST (pstr); 7137 pstr_len = strlen (pstr); 7138 if (UINT_MAX < pstr_len) 7139 { 7140 #ifdef HAVE_MESSAGES 7141 MHD_DLOG (daemon, 7142 _ ("Diffie-Hellman parameters string too long.\n")); 7143 #endif 7144 return MHD_NO; 7145 } 7146 dhpar.size = (unsigned int) pstr_len; 7147 if (gnutls_dh_params_import_pkcs3 (daemon->https_mem_dhparams, 7148 &dhpar, 7149 GNUTLS_X509_FMT_PEM) < 0) 7150 { 7151 #ifdef HAVE_MESSAGES 7152 MHD_DLOG (daemon, 7153 _ ("Bad Diffie-Hellman parameters format.\n")); 7154 #endif 7155 gnutls_dh_params_deinit (daemon->https_mem_dhparams); 7156 return MHD_NO; 7157 } 7158 daemon->have_dhparams = true; 7159 } 7160 #ifdef HAVE_MESSAGES 7161 else 7162 MHD_DLOG (daemon, 7163 _ ("MHD HTTPS option %d passed to MHD but " \ 7164 "MHD_USE_TLS not set.\n"), 7165 opt); 7166 #endif 7167 break; 7168 case MHD_OPTION_HTTPS_PRIORITIES: 7169 case MHD_OPTION_HTTPS_PRIORITIES_APPEND: 7170 pstr = va_arg (ap, 7171 const char *); 7172 if (0 != (daemon->options & MHD_USE_TLS)) 7173 { 7174 if (NULL != daemon->priority_cache) 7175 gnutls_priority_deinit (daemon->priority_cache); 7176 7177 if (MHD_OPTION_HTTPS_PRIORITIES == opt) 7178 { 7179 int init_res; 7180 const char *err_pos; 7181 init_res = gnutls_priority_init (&daemon->priority_cache, 7182 pstr, 7183 &err_pos); 7184 if (GNUTLS_E_SUCCESS != init_res) 7185 { 7186 #ifdef HAVE_MESSAGES 7187 MHD_DLOG (daemon, 7188 _ ("Setting priorities to '%s' failed: %s " \ 7189 "The problematic part starts at: %s\n"), 7190 pstr, 7191 gnutls_strerror (init_res), 7192 err_pos); 7193 #endif 7194 daemon->priority_cache = NULL; 7195 return MHD_NO; 7196 } 7197 } 7198 else 7199 { 7200 /* The cache has been deinited */ 7201 daemon->priority_cache = NULL; 7202 if (! daemon_tls_priorities_init_append (daemon, pstr)) 7203 return MHD_NO; 7204 } 7205 } 7206 #ifdef HAVE_MESSAGES 7207 else 7208 MHD_DLOG (daemon, 7209 _ ("MHD HTTPS option %d passed to MHD but " \ 7210 "MHD_USE_TLS not set.\n"), 7211 opt); 7212 #endif 7213 break; 7214 case MHD_OPTION_HTTPS_CERT_CALLBACK: 7215 #if GNUTLS_VERSION_MAJOR < 3 7216 #ifdef HAVE_MESSAGES 7217 MHD_DLOG (daemon, 7218 _ ("MHD_OPTION_HTTPS_CERT_CALLBACK requires building " \ 7219 "MHD with GnuTLS >= 3.0.\n")); 7220 #endif 7221 return MHD_NO; 7222 #else 7223 pgcrf = va_arg (ap, 7224 gnutls_certificate_retrieve_function2 *); 7225 if (0 != (daemon->options & MHD_USE_TLS)) 7226 daemon->cert_callback = pgcrf; 7227 #ifdef HAVE_MESSAGES 7228 else 7229 MHD_DLOG (daemon, 7230 _ ("MHD HTTPS option %d passed to MHD but " \ 7231 "MHD_USE_TLS not set.\n"), 7232 opt); 7233 #endif /* HAVE_MESSAGES */ 7234 break; 7235 #endif 7236 case MHD_OPTION_HTTPS_CERT_CALLBACK2: 7237 #if GNUTLS_VERSION_NUMBER < 0x030603 7238 #ifdef HAVE_MESSAGES 7239 MHD_DLOG (daemon, 7240 _ ("MHD_OPTION_HTTPS_CERT_CALLBACK2 requires building " \ 7241 "MHD with GnuTLS >= 3.6.3.\n")); 7242 #endif 7243 return MHD_NO; 7244 #else 7245 pgcrf2 = va_arg (ap, 7246 gnutls_certificate_retrieve_function3 *); 7247 if (0 != (daemon->options & MHD_USE_TLS)) 7248 daemon->cert_callback2 = pgcrf2; 7249 #ifdef HAVE_MESSAGES 7250 else 7251 MHD_DLOG (daemon, 7252 _ ("MHD HTTPS option %d passed to MHD but " \ 7253 "MHD_USE_TLS not set.\n"), 7254 opt); 7255 #endif /* HAVE_MESSAGES */ 7256 break; 7257 #endif 7258 #endif /* HTTPS_SUPPORT */ 7259 #ifdef DAUTH_SUPPORT 7260 case MHD_OPTION_DIGEST_AUTH_RANDOM: 7261 case MHD_OPTION_DIGEST_AUTH_RANDOM_COPY: 7262 daemon->digest_auth_rand_size = va_arg (ap, 7263 size_t); 7264 daemon->digest_auth_random = va_arg (ap, 7265 const char *); 7266 if (MHD_OPTION_DIGEST_AUTH_RANDOM_COPY == opt) 7267 /* Set to some non-NULL value just to indicate that copy is required. */ 7268 daemon->digest_auth_random_copy = daemon; 7269 else 7270 daemon->digest_auth_random_copy = NULL; 7271 break; 7272 case MHD_OPTION_NONCE_NC_SIZE: 7273 daemon->nonce_nc_size = va_arg (ap, 7274 unsigned int); 7275 break; 7276 case MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE: 7277 daemon->dauth_bind_type = va_arg (ap, 7278 unsigned int); 7279 if (0 != (daemon->dauth_bind_type & MHD_DAUTH_BIND_NONCE_URI_PARAMS)) 7280 daemon->dauth_bind_type |= MHD_DAUTH_BIND_NONCE_URI; 7281 break; 7282 case MHD_OPTION_DIGEST_AUTH_DEFAULT_NONCE_TIMEOUT: 7283 if (1) 7284 { 7285 unsigned int val; 7286 val = va_arg (ap, 7287 unsigned int); 7288 if (0 != val) 7289 daemon->dauth_def_nonce_timeout = val; 7290 } 7291 break; 7292 case MHD_OPTION_DIGEST_AUTH_DEFAULT_MAX_NC: 7293 if (1) 7294 { 7295 uint32_t val; 7296 val = va_arg (ap, 7297 uint32_t); 7298 if (0 != val) 7299 daemon->dauth_def_max_nc = val; 7300 } 7301 break; 7302 #else /* ! DAUTH_SUPPORT */ 7303 case MHD_OPTION_DIGEST_AUTH_RANDOM: 7304 case MHD_OPTION_DIGEST_AUTH_RANDOM_COPY: 7305 case MHD_OPTION_NONCE_NC_SIZE: 7306 case MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE: 7307 case MHD_OPTION_DIGEST_AUTH_DEFAULT_NONCE_TIMEOUT: 7308 case MHD_OPTION_DIGEST_AUTH_DEFAULT_MAX_NC: 7309 #ifdef HAVE_MESSAGES 7310 MHD_DLOG (daemon, 7311 _ ("Digest Auth is disabled for this build " \ 7312 "of GNU libmicrohttpd.\n")); 7313 #endif /* HAVE_MESSAGES */ 7314 return MHD_NO; 7315 #endif /* ! DAUTH_SUPPORT */ 7316 case MHD_OPTION_LISTEN_SOCKET: 7317 params->listen_fd = va_arg (ap, 7318 MHD_socket); 7319 params->listen_fd_set = true; 7320 break; 7321 case MHD_OPTION_EXTERNAL_LOGGER: 7322 #ifdef HAVE_MESSAGES 7323 daemon->custom_error_log = va_arg (ap, 7324 VfprintfFunctionPointerType); 7325 daemon->custom_error_log_cls = va_arg (ap, 7326 void *); 7327 if (1 != params->num_opts) 7328 MHD_DLOG (daemon, 7329 _ ("MHD_OPTION_EXTERNAL_LOGGER is not the first option " 7330 "specified for the daemon. Some messages may be " 7331 "printed by the standard MHD logger.\n")); 7332 7333 #else 7334 (void) va_arg (ap, 7335 VfprintfFunctionPointerType); 7336 (void) va_arg (ap, 7337 void *); 7338 #endif 7339 break; 7340 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 7341 case MHD_OPTION_THREAD_STACK_SIZE: 7342 daemon->thread_stack_size = va_arg (ap, 7343 size_t); 7344 break; 7345 #endif 7346 case MHD_OPTION_TCP_FASTOPEN_QUEUE_SIZE: 7347 #ifdef TCP_FASTOPEN 7348 daemon->fastopen_queue_size = va_arg (ap, 7349 unsigned int); 7350 break; 7351 #else /* ! TCP_FASTOPEN */ 7352 #ifdef HAVE_MESSAGES 7353 MHD_DLOG (daemon, 7354 _ ("TCP fastopen is not supported on this platform.\n")); 7355 #endif /* HAVE_MESSAGES */ 7356 return MHD_NO; 7357 #endif /* ! TCP_FASTOPEN */ 7358 case MHD_OPTION_LISTENING_ADDRESS_REUSE: 7359 daemon->listening_address_reuse = va_arg (ap, 7360 unsigned int) ? 1 : -1; 7361 break; 7362 case MHD_OPTION_LISTEN_BACKLOG_SIZE: 7363 daemon->listen_backlog_size = va_arg (ap, 7364 unsigned int); 7365 break; 7366 case MHD_OPTION_STRICT_FOR_CLIENT: 7367 daemon->client_discipline = va_arg (ap, int); /* Temporal assignment */ 7368 /* Map to correct value */ 7369 if (-1 >= daemon->client_discipline) 7370 daemon->client_discipline = -3; 7371 else if (1 <= daemon->client_discipline) 7372 daemon->client_discipline = 1; 7373 #ifdef HAVE_MESSAGES 7374 if ( (0 != (daemon->options & MHD_USE_PEDANTIC_CHECKS)) && 7375 (1 != daemon->client_discipline) ) 7376 { 7377 MHD_DLOG (daemon, 7378 _ ("Flag MHD_USE_PEDANTIC_CHECKS is ignored because " 7379 "another behaviour is specified by " 7380 "MHD_OPTION_STRICT_CLIENT.\n")); 7381 } 7382 #endif /* HAVE_MESSAGES */ 7383 break; 7384 case MHD_OPTION_CLIENT_DISCIPLINE_LVL: 7385 daemon->client_discipline = va_arg (ap, int); 7386 #ifdef HAVE_MESSAGES 7387 if ( (0 != (daemon->options & MHD_USE_PEDANTIC_CHECKS)) && 7388 (1 != daemon->client_discipline) ) 7389 { 7390 MHD_DLOG (daemon, 7391 _ ("Flag MHD_USE_PEDANTIC_CHECKS is ignored because " 7392 "another behaviour is specified by " 7393 "MHD_OPTION_CLIENT_DISCIPLINE_LVL.\n")); 7394 } 7395 #endif /* HAVE_MESSAGES */ 7396 break; 7397 case MHD_OPTION_ALLOW_BIN_ZERO_IN_URI_PATH: 7398 daemon->allow_bzero_in_url = va_arg (ap, int); 7399 if ((0 > daemon->allow_bzero_in_url) || 7400 (2 < daemon->allow_bzero_in_url)) 7401 daemon->allow_bzero_in_url = 1; 7402 break; 7403 case MHD_OPTION_ARRAY: 7404 params->num_opts--; /* Do not count MHD_OPTION_ARRAY */ 7405 oa = va_arg (ap, struct MHD_OptionItem *); 7406 i = 0; 7407 while (MHD_OPTION_END != (opt = oa[i].option)) 7408 { 7409 switch (opt) 7410 { 7411 /* all options taking 'size_t' */ 7412 case MHD_OPTION_CONNECTION_MEMORY_LIMIT: 7413 case MHD_OPTION_CONNECTION_MEMORY_INCREMENT: 7414 case MHD_OPTION_THREAD_STACK_SIZE: 7415 if (MHD_NO == parse_options (daemon, 7416 params, 7417 opt, 7418 (size_t) oa[i].value, 7419 MHD_OPTION_END)) 7420 return MHD_NO; 7421 break; 7422 /* all options taking 'unsigned int' */ 7423 case MHD_OPTION_NONCE_NC_SIZE: 7424 case MHD_OPTION_CONNECTION_LIMIT: 7425 case MHD_OPTION_CONNECTION_TIMEOUT: 7426 case MHD_OPTION_PER_IP_CONNECTION_LIMIT: 7427 case MHD_OPTION_THREAD_POOL_SIZE: 7428 case MHD_OPTION_TCP_FASTOPEN_QUEUE_SIZE: 7429 case MHD_OPTION_LISTENING_ADDRESS_REUSE: 7430 case MHD_OPTION_LISTEN_BACKLOG_SIZE: 7431 case MHD_OPTION_SERVER_INSANITY: 7432 case MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE: 7433 case MHD_OPTION_DIGEST_AUTH_DEFAULT_NONCE_TIMEOUT: 7434 if (MHD_NO == parse_options (daemon, 7435 params, 7436 opt, 7437 (unsigned int) oa[i].value, 7438 MHD_OPTION_END)) 7439 return MHD_NO; 7440 break; 7441 /* all options taking 'enum' */ 7442 case MHD_OPTION_HTTPS_CRED_TYPE: 7443 #ifdef HTTPS_SUPPORT 7444 if (MHD_NO == parse_options (daemon, 7445 params, 7446 opt, 7447 (gnutls_credentials_type_t) oa[i].value, 7448 MHD_OPTION_END)) 7449 #endif /* HTTPS_SUPPORT */ 7450 return MHD_NO; 7451 break; 7452 /* all options taking 'MHD_socket' */ 7453 case MHD_OPTION_LISTEN_SOCKET: 7454 if (MHD_NO == parse_options (daemon, 7455 params, 7456 opt, 7457 (MHD_socket) oa[i].value, 7458 MHD_OPTION_END)) 7459 return MHD_NO; 7460 break; 7461 /* all options taking 'int' */ 7462 case MHD_OPTION_STRICT_FOR_CLIENT: 7463 case MHD_OPTION_CLIENT_DISCIPLINE_LVL: 7464 case MHD_OPTION_SIGPIPE_HANDLED_BY_APP: 7465 case MHD_OPTION_TLS_NO_ALPN: 7466 case MHD_OPTION_APP_FD_SETSIZE: 7467 case MHD_OPTION_ALLOW_BIN_ZERO_IN_URI_PATH: 7468 if (MHD_NO == parse_options (daemon, 7469 params, 7470 opt, 7471 (int) oa[i].value, 7472 MHD_OPTION_END)) 7473 return MHD_NO; 7474 break; 7475 /* all options taking 'uint32_t' */ 7476 case MHD_OPTION_DIGEST_AUTH_DEFAULT_MAX_NC: 7477 if (MHD_NO == parse_options (daemon, 7478 params, 7479 opt, 7480 (uint32_t) oa[i].value, 7481 MHD_OPTION_END)) 7482 return MHD_NO; 7483 break; 7484 /* all options taking one pointer */ 7485 case MHD_OPTION_SOCK_ADDR: 7486 case MHD_OPTION_HTTPS_MEM_KEY: 7487 case MHD_OPTION_HTTPS_KEY_PASSWORD: 7488 case MHD_OPTION_HTTPS_MEM_CERT: 7489 case MHD_OPTION_HTTPS_MEM_TRUST: 7490 case MHD_OPTION_HTTPS_MEM_DHPARAMS: 7491 case MHD_OPTION_HTTPS_PRIORITIES: 7492 case MHD_OPTION_HTTPS_PRIORITIES_APPEND: 7493 case MHD_OPTION_ARRAY: 7494 case MHD_OPTION_HTTPS_CERT_CALLBACK: 7495 case MHD_OPTION_HTTPS_CERT_CALLBACK2: 7496 if (MHD_NO == parse_options (daemon, 7497 params, 7498 opt, 7499 oa[i].ptr_value, 7500 MHD_OPTION_END)) 7501 return MHD_NO; 7502 break; 7503 /* all options taking two pointers */ 7504 case MHD_OPTION_NOTIFY_COMPLETED: 7505 case MHD_OPTION_NOTIFY_CONNECTION: 7506 case MHD_OPTION_URI_LOG_CALLBACK: 7507 case MHD_OPTION_EXTERNAL_LOGGER: 7508 case MHD_OPTION_UNESCAPE_CALLBACK: 7509 case MHD_OPTION_GNUTLS_PSK_CRED_HANDLER: 7510 if (MHD_NO == parse_options (daemon, 7511 params, 7512 opt, 7513 (void *) oa[i].value, 7514 oa[i].ptr_value, 7515 MHD_OPTION_END)) 7516 return MHD_NO; 7517 break; 7518 /* options taking size_t-number followed by pointer */ 7519 case MHD_OPTION_DIGEST_AUTH_RANDOM: 7520 case MHD_OPTION_DIGEST_AUTH_RANDOM_COPY: 7521 if (MHD_NO == parse_options (daemon, 7522 params, 7523 opt, 7524 (size_t) oa[i].value, 7525 oa[i].ptr_value, 7526 MHD_OPTION_END)) 7527 return MHD_NO; 7528 break; 7529 /* options taking socklen_t-number followed by pointer */ 7530 case MHD_OPTION_SOCK_ADDR_LEN: 7531 if (MHD_NO == parse_options (daemon, 7532 params, 7533 opt, 7534 (socklen_t) oa[i].value, 7535 oa[i].ptr_value, 7536 MHD_OPTION_END)) 7537 return MHD_NO; 7538 break; 7539 case MHD_OPTION_END: /* Not possible */ 7540 default: 7541 return MHD_NO; 7542 } 7543 i++; 7544 } 7545 break; 7546 case MHD_OPTION_UNESCAPE_CALLBACK: 7547 daemon->unescape_callback = va_arg (ap, 7548 UnescapeCallback); 7549 daemon->unescape_callback_cls = va_arg (ap, 7550 void *); 7551 break; 7552 #ifdef HTTPS_SUPPORT 7553 case MHD_OPTION_GNUTLS_PSK_CRED_HANDLER: 7554 #if GNUTLS_VERSION_MAJOR >= 3 7555 daemon->cred_callback = va_arg (ap, 7556 MHD_PskServerCredentialsCallback); 7557 daemon->cred_callback_cls = va_arg (ap, 7558 void *); 7559 break; 7560 #else 7561 MHD_DLOG (daemon, 7562 _ ("MHD HTTPS option %d passed to MHD compiled " \ 7563 "without GNUtls >= 3.\n"), 7564 opt); 7565 return MHD_NO; 7566 #endif 7567 #endif /* HTTPS_SUPPORT */ 7568 case MHD_OPTION_SIGPIPE_HANDLED_BY_APP: 7569 if (! MHD_D_IS_USING_THREADS_ (daemon)) 7570 daemon->sigpipe_blocked = ( (va_arg (ap, 7571 int)) != 0); 7572 else 7573 { 7574 (void) va_arg (ap, 7575 int); 7576 } 7577 break; 7578 case MHD_OPTION_TLS_NO_ALPN: 7579 #ifdef HTTPS_SUPPORT 7580 daemon->disable_alpn = (va_arg (ap, 7581 int) != 0); 7582 #else /* ! HTTPS_SUPPORT */ 7583 (void) va_arg (ap, int); 7584 #endif /* ! HTTPS_SUPPORT */ 7585 #ifdef HAVE_MESSAGES 7586 if (0 == (daemon->options & MHD_USE_TLS)) 7587 MHD_DLOG (daemon, 7588 _ ("MHD HTTPS option %d passed to MHD " \ 7589 "but MHD_USE_TLS not set.\n"), 7590 (int) opt); 7591 #endif /* HAVE_MESSAGES */ 7592 break; 7593 case MHD_OPTION_APP_FD_SETSIZE: 7594 params->fdset_size_set = true; 7595 params->fdset_size = va_arg (ap, 7596 int); 7597 break; 7598 #ifndef HTTPS_SUPPORT 7599 case MHD_OPTION_HTTPS_MEM_KEY: 7600 case MHD_OPTION_HTTPS_MEM_CERT: 7601 case MHD_OPTION_HTTPS_CRED_TYPE: 7602 case MHD_OPTION_HTTPS_PRIORITIES: 7603 case MHD_OPTION_HTTPS_PRIORITIES_APPEND: 7604 case MHD_OPTION_HTTPS_MEM_TRUST: 7605 case MHD_OPTION_HTTPS_CERT_CALLBACK: 7606 case MHD_OPTION_HTTPS_MEM_DHPARAMS: 7607 case MHD_OPTION_HTTPS_KEY_PASSWORD: 7608 case MHD_OPTION_GNUTLS_PSK_CRED_HANDLER: 7609 case MHD_OPTION_HTTPS_CERT_CALLBACK2: 7610 #ifdef HAVE_MESSAGES 7611 MHD_DLOG (daemon, 7612 _ ("MHD HTTPS option %d passed to MHD " 7613 "compiled without HTTPS support.\n"), 7614 opt); 7615 #endif 7616 return MHD_NO; 7617 #endif /* HTTPS_SUPPORT */ 7618 case MHD_OPTION_END: /* Not possible */ 7619 default: 7620 #ifdef HAVE_MESSAGES 7621 MHD_DLOG (daemon, 7622 _ ("Invalid option %d! (Did you terminate " 7623 "the list with MHD_OPTION_END?).\n"), 7624 opt); 7625 #endif 7626 return MHD_NO; 7627 } 7628 } 7629 return MHD_YES; 7630 } 7631 7632 7633 #ifdef EPOLL_SUPPORT 7634 static int 7635 setup_epoll_fd (struct MHD_Daemon *daemon) 7636 { 7637 int fd; 7638 7639 #ifndef HAVE_MESSAGES 7640 (void) daemon; /* Mute compiler warning. */ 7641 #endif /* ! HAVE_MESSAGES */ 7642 7643 #ifdef USE_EPOLL_CREATE1 7644 fd = epoll_create1 (EPOLL_CLOEXEC); 7645 #else /* ! USE_EPOLL_CREATE1 */ 7646 fd = epoll_create (MAX_EVENTS); 7647 #endif /* ! USE_EPOLL_CREATE1 */ 7648 if (MHD_INVALID_SOCKET == fd) 7649 { 7650 #ifdef HAVE_MESSAGES 7651 MHD_DLOG (daemon, 7652 _ ("Call to epoll_create1 failed: %s\n"), 7653 MHD_socket_last_strerr_ ()); 7654 #endif 7655 return MHD_INVALID_SOCKET; 7656 } 7657 #if ! defined(USE_EPOLL_CREATE1) 7658 if (! MHD_socket_noninheritable_ (fd)) 7659 { 7660 #ifdef HAVE_MESSAGES 7661 MHD_DLOG (daemon, 7662 _ ("Failed to set noninheritable mode on epoll FD.\n")); 7663 #endif 7664 } 7665 #endif /* ! USE_EPOLL_CREATE1 */ 7666 return fd; 7667 } 7668 7669 7670 /** 7671 * Setup epoll() FD for the daemon and initialize it to listen 7672 * on the listen FD. 7673 * @remark To be called only from MHD_start_daemon_va() 7674 * 7675 * @param daemon daemon to initialize for epoll() 7676 * @return #MHD_YES on success, #MHD_NO on failure 7677 */ 7678 static enum MHD_Result 7679 setup_epoll_to_listen (struct MHD_Daemon *daemon) 7680 { 7681 struct epoll_event event; 7682 MHD_socket ls; 7683 7684 mhd_assert (MHD_D_IS_USING_EPOLL_ (daemon)); 7685 mhd_assert (0 == (daemon->options & MHD_USE_THREAD_PER_CONNECTION)); 7686 mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ 7687 (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) || \ 7688 MHD_ITC_IS_VALID_ (daemon->itc) ); 7689 daemon->epoll_fd = setup_epoll_fd (daemon); 7690 if (! MHD_D_IS_USING_THREADS_ (daemon) 7691 && (0 != (daemon->options & MHD_USE_AUTO))) 7692 { 7693 /* Application requested "MHD_USE_AUTO", probably MHD_get_fdset() will be 7694 used. 7695 Make sure that epoll FD is suitable for fd_set. 7696 Actually, MHD_get_fdset() is allowed for MHD_USE_EPOLL direct, 7697 but most probably direct requirement for MHD_USE_EPOLL means that 7698 epoll FD will be used directly. This logic is fuzzy, but better 7699 than nothing with current MHD API. */ 7700 if (! MHD_D_DOES_SCKT_FIT_FDSET_ (daemon->epoll_fd, daemon)) 7701 { 7702 #ifdef HAVE_MESSAGES 7703 MHD_DLOG (daemon, 7704 _ ("The epoll FD is too large to be used with fd_set.\n")); 7705 #endif /* HAVE_MESSAGES */ 7706 return MHD_NO; 7707 } 7708 } 7709 if (-1 == daemon->epoll_fd) 7710 return MHD_NO; 7711 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) 7712 if (0 != (MHD_ALLOW_UPGRADE & daemon->options)) 7713 { 7714 daemon->epoll_upgrade_fd = setup_epoll_fd (daemon); 7715 if (MHD_INVALID_SOCKET == daemon->epoll_upgrade_fd) 7716 return MHD_NO; 7717 } 7718 #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ 7719 if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) && 7720 (! daemon->was_quiesced) ) 7721 { 7722 event.events = EPOLLIN | EPOLLRDHUP; 7723 event.data.ptr = daemon; 7724 if (0 != epoll_ctl (daemon->epoll_fd, 7725 EPOLL_CTL_ADD, 7726 ls, 7727 &event)) 7728 { 7729 #ifdef HAVE_MESSAGES 7730 MHD_DLOG (daemon, 7731 _ ("Call to epoll_ctl failed: %s\n"), 7732 MHD_socket_last_strerr_ ()); 7733 #endif 7734 return MHD_NO; 7735 } 7736 daemon->listen_socket_in_epoll = true; 7737 } 7738 7739 if (MHD_ITC_IS_VALID_ (daemon->itc)) 7740 { 7741 event.events = EPOLLIN | EPOLLRDHUP; 7742 event.data.ptr = _MHD_DROP_CONST (epoll_itc_marker); 7743 if (0 != epoll_ctl (daemon->epoll_fd, 7744 EPOLL_CTL_ADD, 7745 MHD_itc_r_fd_ (daemon->itc), 7746 &event)) 7747 { 7748 #ifdef HAVE_MESSAGES 7749 MHD_DLOG (daemon, 7750 _ ("Call to epoll_ctl failed: %s\n"), 7751 MHD_socket_last_strerr_ ()); 7752 #endif 7753 return MHD_NO; 7754 } 7755 } 7756 return MHD_YES; 7757 } 7758 7759 7760 #endif 7761 7762 7763 /** 7764 * Apply interim parameters 7765 * @param[in,out] d the daemon to use 7766 * @param[out] ppsockaddr the pointer to store the pointer to 'struct sockaddr' 7767 * if provided by application 7768 * @param[out] psockaddr_len the size memory area pointed by 'struct sockaddr' 7769 * if provided by application 7770 * @param[in,out] params the interim parameters to process 7771 * @return true in case of success, 7772 * false in case of critical error (the daemon must be closed). 7773 */ 7774 static bool 7775 process_interim_params (struct MHD_Daemon *d, 7776 const struct sockaddr **ppsockaddr, 7777 socklen_t *psockaddr_len, 7778 struct MHD_InterimParams_ *params) 7779 { 7780 if (params->fdset_size_set) 7781 { 7782 if (0 >= params->fdset_size) 7783 { 7784 #ifdef HAVE_MESSAGES 7785 MHD_DLOG (d, 7786 _ ("MHD_OPTION_APP_FD_SETSIZE value (%d) is not positive.\n"), 7787 params->fdset_size); 7788 #endif /* HAVE_MESSAGES */ 7789 return false; 7790 } 7791 if (MHD_D_IS_USING_THREADS_ (d)) 7792 { 7793 #ifdef HAVE_MESSAGES 7794 MHD_DLOG (d, 7795 _ ("MHD_OPTION_APP_FD_SETSIZE is ignored for daemon started " \ 7796 "with MHD_USE_INTERNAL_POLLING_THREAD.\n")); 7797 #endif /* HAVE_MESSAGES */ 7798 (void) 0; 7799 } 7800 else if (MHD_D_IS_USING_POLL_ (d)) 7801 { 7802 #ifdef HAVE_MESSAGES 7803 MHD_DLOG (d, 7804 _ ("MHD_OPTION_APP_FD_SETSIZE is ignored for daemon started " \ 7805 "with MHD_USE_POLL.\n")); 7806 #endif /* HAVE_MESSAGES */ 7807 (void) 0; 7808 } 7809 else 7810 { /* The daemon without internal threads, external sockets polling */ 7811 #ifndef HAS_FD_SETSIZE_OVERRIDABLE 7812 if (((int) FD_SETSIZE) != params->fdset_size) 7813 { 7814 #ifdef HAVE_MESSAGES 7815 MHD_DLOG (d, 7816 _ ("MHD_OPTION_APP_FD_SETSIZE value (%d) does not match " \ 7817 "the platform FD_SETSIZE value (%d) and this platform " \ 7818 "does not support overriding of FD_SETSIZE.\n"), 7819 params->fdset_size, (int) FD_SETSIZE); 7820 #endif /* HAVE_MESSAGES */ 7821 return false; 7822 } 7823 #else /* HAS_FD_SETSIZE_OVERRIDABLE */ 7824 d->fdset_size = params->fdset_size; 7825 d->fdset_size_set_by_app = true; 7826 #endif /* HAS_FD_SETSIZE_OVERRIDABLE */ 7827 } 7828 } 7829 7830 if (params->listen_fd_set) 7831 { 7832 if (MHD_INVALID_SOCKET == params->listen_fd) 7833 { 7834 (void) 0; /* Use MHD-created socket */ 7835 } 7836 #ifdef HAS_SIGNED_SOCKET 7837 else if (0 > params->listen_fd) 7838 { 7839 #ifdef HAVE_MESSAGES 7840 MHD_DLOG (d, 7841 _ ("The value provided for MHD_OPTION_LISTEN_SOCKET " \ 7842 "is invalid.\n")); 7843 #endif /* HAVE_MESSAGES */ 7844 return false; 7845 } 7846 #endif /* HAS_SIGNED_SOCKET */ 7847 else if (0 != (d->options & MHD_USE_NO_LISTEN_SOCKET)) 7848 { 7849 #ifdef HAVE_MESSAGES 7850 MHD_DLOG (d, 7851 _ ("MHD_OPTION_LISTEN_SOCKET specified for daemon " 7852 "with MHD_USE_NO_LISTEN_SOCKET flag set.\n")); 7853 #endif /* HAVE_MESSAGES */ 7854 (void) MHD_socket_close_ (params->listen_fd); 7855 return false; 7856 } 7857 else 7858 { 7859 d->listen_fd = params->listen_fd; 7860 d->listen_is_unix = _MHD_UNKNOWN; 7861 #ifdef MHD_USE_GETSOCKNAME 7862 d->port = 0; /* Force use of autodetection */ 7863 #endif /* MHD_USE_GETSOCKNAME */ 7864 } 7865 } 7866 7867 mhd_assert (! params->server_addr_len_set || params->pserver_addr_set); 7868 if (params->pserver_addr_set) 7869 { 7870 if (NULL == params->pserver_addr) 7871 { 7872 /* The size must be zero if set */ 7873 if (params->server_addr_len_set && (0 != params->server_addr_len)) 7874 return false; 7875 /* Ignore parameter if it is NULL */ 7876 } 7877 else if (MHD_INVALID_SOCKET != d->listen_fd) 7878 { 7879 #ifdef HAVE_MESSAGES 7880 MHD_DLOG (d, 7881 _ ("MHD_OPTION_LISTEN_SOCKET cannot be used together with " \ 7882 "MHD_OPTION_SOCK_ADDR_LEN or MHD_OPTION_SOCK_ADDR.\n")); 7883 #endif /* HAVE_MESSAGES */ 7884 return false; 7885 } 7886 else if (0 != (d->options & MHD_USE_NO_LISTEN_SOCKET)) 7887 { 7888 #ifdef HAVE_MESSAGES 7889 MHD_DLOG (d, 7890 _ ("MHD_OPTION_SOCK_ADDR_LEN or MHD_OPTION_SOCK_ADDR " \ 7891 "specified for daemon with MHD_USE_NO_LISTEN_SOCKET " \ 7892 "flag set.\n")); 7893 #endif /* HAVE_MESSAGES */ 7894 if (MHD_INVALID_SOCKET != d->listen_fd) 7895 { 7896 (void) MHD_socket_close_ (params->listen_fd); 7897 params->listen_fd = MHD_INVALID_SOCKET; 7898 } 7899 return false; 7900 } 7901 else 7902 { 7903 *ppsockaddr = params->pserver_addr; 7904 if (params->server_addr_len_set) 7905 { 7906 /* The size must be non-zero if set */ 7907 if (0 == params->server_addr_len) 7908 return false; 7909 *psockaddr_len = params->server_addr_len; 7910 } 7911 else 7912 *psockaddr_len = 0; 7913 } 7914 } 7915 return true; 7916 } 7917 7918 7919 /** 7920 * Start a webserver on the given port. 7921 * 7922 * @param flags combination of `enum MHD_FLAG` values 7923 * @param port port to bind to (in host byte order), 7924 * use '0' to bind to random free port, 7925 * ignored if #MHD_OPTION_SOCK_ADDR or 7926 * #MHD_OPTION_LISTEN_SOCKET is provided 7927 * or #MHD_USE_NO_LISTEN_SOCKET is specified 7928 * @param apc callback to call to check which clients 7929 * will be allowed to connect; you can pass NULL 7930 * in which case connections from any IP will be 7931 * accepted 7932 * @param apc_cls extra argument to @a apc 7933 * @param dh handler called for all requests (repeatedly) 7934 * @param dh_cls extra argument to @a dh 7935 * @param ap list of options (type-value pairs, 7936 * terminated with #MHD_OPTION_END). 7937 * @return NULL on error, handle to daemon on success 7938 * @ingroup event 7939 */ 7940 _MHD_EXTERN struct MHD_Daemon * 7941 MHD_start_daemon_va (unsigned int flags, 7942 uint16_t port, 7943 MHD_AcceptPolicyCallback apc, 7944 void *apc_cls, 7945 MHD_AccessHandlerCallback dh, 7946 void *dh_cls, 7947 va_list ap) 7948 { 7949 const MHD_SCKT_OPT_BOOL_ on = 1; 7950 struct MHD_Daemon *daemon; 7951 const struct sockaddr *pservaddr = NULL; 7952 socklen_t addrlen; 7953 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 7954 unsigned int i; 7955 #endif 7956 enum MHD_FLAG eflags; /* same type as in MHD_Daemon */ 7957 enum MHD_FLAG *pflags; 7958 struct MHD_InterimParams_ *interim_params; 7959 7960 MHD_check_global_init_ (); 7961 eflags = (enum MHD_FLAG) flags; 7962 pflags = &eflags; 7963 7964 if (0 != (*pflags & MHD_USE_THREAD_PER_CONNECTION)) 7965 *pflags |= MHD_USE_INTERNAL_POLLING_THREAD; /* Force enable, log warning later if needed */ 7966 7967 #ifndef HAVE_INET6 7968 if (0 != (*pflags & MHD_USE_IPv6)) 7969 return NULL; 7970 #endif 7971 #ifndef HAVE_POLL 7972 if (0 != (*pflags & MHD_USE_POLL)) 7973 return NULL; 7974 #endif 7975 #ifndef EPOLL_SUPPORT 7976 if (0 != (*pflags & MHD_USE_EPOLL)) 7977 return NULL; 7978 #endif /* ! EPOLL_SUPPORT */ 7979 #ifndef HTTPS_SUPPORT 7980 if (0 != (*pflags & MHD_USE_TLS)) 7981 return NULL; 7982 #endif /* ! HTTPS_SUPPORT */ 7983 #ifndef TCP_FASTOPEN 7984 if (0 != (*pflags & MHD_USE_TCP_FASTOPEN)) 7985 return NULL; 7986 #endif 7987 if (0 != (*pflags & MHD_ALLOW_UPGRADE)) 7988 { 7989 #ifdef UPGRADE_SUPPORT 7990 *pflags |= MHD_ALLOW_SUSPEND_RESUME; 7991 #else /* ! UPGRADE_SUPPORT */ 7992 return NULL; 7993 #endif /* ! UPGRADE_SUPPORT */ 7994 } 7995 #ifdef MHD_USE_THREADS 7996 if ((MHD_USE_NO_THREAD_SAFETY | MHD_USE_INTERNAL_POLLING_THREAD) == 7997 ((MHD_USE_NO_THREAD_SAFETY | MHD_USE_INTERNAL_POLLING_THREAD) 7998 & *pflags)) 7999 return NULL; /* Cannot be thread-unsafe with multiple threads */ 8000 #else /* ! MHD_USE_THREADS */ 8001 if (0 != (*pflags & MHD_USE_INTERNAL_POLLING_THREAD)) 8002 return NULL; 8003 #endif /* ! MHD_USE_THREADS */ 8004 8005 if (NULL == dh) 8006 return NULL; 8007 8008 /* Check for invalid combinations of flags. */ 8009 if ((0 != (*pflags & MHD_USE_POLL)) && (0 != (*pflags & MHD_USE_EPOLL))) 8010 return NULL; 8011 if ((0 != (*pflags & MHD_USE_EPOLL)) && 8012 (0 != (*pflags & MHD_USE_THREAD_PER_CONNECTION))) 8013 return NULL; 8014 if ((0 != (*pflags & MHD_USE_POLL)) && 8015 (0 == (*pflags & (MHD_USE_INTERNAL_POLLING_THREAD 8016 | MHD_USE_THREAD_PER_CONNECTION)))) 8017 return NULL; 8018 if ((0 != (*pflags & MHD_USE_AUTO)) && 8019 (0 != (*pflags & (MHD_USE_POLL | MHD_USE_EPOLL)))) 8020 return NULL; 8021 8022 if (0 != (*pflags & MHD_USE_AUTO)) 8023 { 8024 #if defined(EPOLL_SUPPORT) && defined(HAVE_POLL) 8025 if (0 != (*pflags & MHD_USE_THREAD_PER_CONNECTION)) 8026 *pflags |= MHD_USE_POLL; 8027 else 8028 *pflags |= MHD_USE_EPOLL; /* Including "external select" mode */ 8029 #elif defined(HAVE_POLL) 8030 if (0 != (*pflags & MHD_USE_INTERNAL_POLLING_THREAD)) 8031 *pflags |= MHD_USE_POLL; /* Including thread-per-connection */ 8032 #elif defined(EPOLL_SUPPORT) 8033 if (0 == (*pflags & MHD_USE_THREAD_PER_CONNECTION)) 8034 *pflags |= MHD_USE_EPOLL; /* Including "external select" mode */ 8035 #else 8036 /* No choice: use select() for any mode - do not modify flags */ 8037 #endif 8038 } 8039 8040 if (0 != (*pflags & MHD_USE_NO_THREAD_SAFETY)) 8041 *pflags = (*pflags & ~((enum MHD_FLAG) MHD_USE_ITC)); /* useless in single-threaded environment */ 8042 else if (0 != (*pflags & MHD_USE_INTERNAL_POLLING_THREAD)) 8043 { 8044 #ifdef HAVE_LISTEN_SHUTDOWN 8045 if (0 != (*pflags & MHD_USE_NO_LISTEN_SOCKET)) 8046 #endif 8047 *pflags |= MHD_USE_ITC; /* yes, must use ITC to signal thread */ 8048 } 8049 8050 if (NULL == (daemon = MHD_calloc_ (1, sizeof (struct MHD_Daemon)))) 8051 return NULL; 8052 interim_params = (struct MHD_InterimParams_ *) \ 8053 MHD_calloc_ (1, sizeof (struct MHD_InterimParams_)); 8054 if (NULL == interim_params) 8055 { 8056 int err_num = errno; 8057 free (daemon); 8058 errno = err_num; 8059 return NULL; 8060 } 8061 #ifdef EPOLL_SUPPORT 8062 daemon->epoll_fd = -1; 8063 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) 8064 daemon->epoll_upgrade_fd = -1; 8065 #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ 8066 #endif 8067 /* try to open listen socket */ 8068 #ifdef HTTPS_SUPPORT 8069 daemon->priority_cache = NULL; 8070 #endif /* HTTPS_SUPPORT */ 8071 daemon->listen_fd = MHD_INVALID_SOCKET; 8072 daemon->listen_is_unix = _MHD_NO; 8073 daemon->listening_address_reuse = 0; 8074 daemon->options = *pflags; 8075 pflags = &daemon->options; 8076 daemon->client_discipline = (0 != (*pflags & MHD_USE_PEDANTIC_CHECKS)) ? 8077 1 : 0; 8078 daemon->port = port; 8079 daemon->apc = apc; 8080 daemon->apc_cls = apc_cls; 8081 daemon->default_handler = dh; 8082 daemon->default_handler_cls = dh_cls; 8083 daemon->connections = 0; 8084 daemon->connection_limit = MHD_MAX_CONNECTIONS_DEFAULT; 8085 daemon->pool_size = MHD_POOL_SIZE_DEFAULT; 8086 daemon->pool_increment = MHD_BUF_INC_SIZE; 8087 daemon->unescape_callback = &unescape_wrapper; 8088 daemon->connection_timeout_ms = 0; /* no timeout */ 8089 MHD_itc_set_invalid_ (daemon->itc); 8090 #ifdef MHD_USE_THREADS 8091 MHD_thread_handle_ID_set_invalid_ (&daemon->tid); 8092 #endif /* MHD_USE_THREADS */ 8093 #ifdef SOMAXCONN 8094 daemon->listen_backlog_size = SOMAXCONN; 8095 #else /* !SOMAXCONN */ 8096 daemon->listen_backlog_size = 511; /* should be safe value */ 8097 #endif /* !SOMAXCONN */ 8098 #ifdef HAVE_MESSAGES 8099 daemon->custom_error_log = &MHD_default_logger_; 8100 daemon->custom_error_log_cls = stderr; 8101 #endif 8102 #ifndef MHD_WINSOCK_SOCKETS 8103 daemon->sigpipe_blocked = false; 8104 #else /* MHD_WINSOCK_SOCKETS */ 8105 /* There is no SIGPIPE on W32, nothing to block. */ 8106 daemon->sigpipe_blocked = true; 8107 #endif /* _WIN32 && ! __CYGWIN__ */ 8108 #if defined(_DEBUG) && defined(HAVE_ACCEPT4) 8109 daemon->avoid_accept4 = false; 8110 #endif /* _DEBUG */ 8111 #ifdef HAS_FD_SETSIZE_OVERRIDABLE 8112 daemon->fdset_size = (int) FD_SETSIZE; 8113 daemon->fdset_size_set_by_app = false; 8114 #endif /* HAS_FD_SETSIZE_OVERRIDABLE */ 8115 8116 #ifdef DAUTH_SUPPORT 8117 daemon->digest_auth_rand_size = 0; 8118 daemon->digest_auth_random = NULL; 8119 daemon->nonce_nc_size = 4; /* tiny */ 8120 daemon->dauth_def_nonce_timeout = MHD_DAUTH_DEF_TIMEOUT_; 8121 daemon->dauth_def_max_nc = MHD_DAUTH_DEF_MAX_NC_; 8122 #endif 8123 #ifdef HTTPS_SUPPORT 8124 if (0 != (*pflags & MHD_USE_TLS)) 8125 { 8126 daemon->cred_type = GNUTLS_CRD_CERTIFICATE; 8127 } 8128 #endif /* HTTPS_SUPPORT */ 8129 8130 interim_params->num_opts = 0; 8131 interim_params->fdset_size_set = false; 8132 interim_params->fdset_size = 0; 8133 interim_params->listen_fd_set = false; 8134 interim_params->listen_fd = MHD_INVALID_SOCKET; 8135 interim_params->pserver_addr_set = false; 8136 interim_params->pserver_addr = NULL; 8137 interim_params->server_addr_len_set = false; 8138 interim_params->server_addr_len = 0; 8139 8140 if (MHD_NO == parse_options_va (daemon, 8141 interim_params, 8142 ap)) 8143 { 8144 #ifdef HTTPS_SUPPORT 8145 tls_cleanup_failed_start (daemon); 8146 #endif /* HTTPS_SUPPORT */ 8147 free (interim_params); 8148 free (daemon); 8149 return NULL; 8150 } 8151 if (! process_interim_params (daemon, 8152 &pservaddr, 8153 &addrlen, 8154 interim_params)) 8155 { 8156 #ifdef HTTPS_SUPPORT 8157 tls_cleanup_failed_start (daemon); 8158 #endif /* HTTPS_SUPPORT */ 8159 free (interim_params); 8160 free (daemon); 8161 return NULL; 8162 } 8163 free (interim_params); 8164 interim_params = NULL; 8165 #ifdef HTTPS_SUPPORT 8166 if ((0 != (*pflags & MHD_USE_TLS)) 8167 && (NULL == daemon->priority_cache) 8168 && ! daemon_tls_priorities_init_default (daemon)) 8169 { 8170 #ifdef HAVE_MESSAGES 8171 MHD_DLOG (daemon, 8172 _ ("Failed to initialise GnuTLS priorities.\n")); 8173 #endif /* HAVE_MESSAGES */ 8174 tls_cleanup_failed_start (daemon); 8175 free (daemon); 8176 return NULL; 8177 } 8178 #endif /* HTTPS_SUPPORT */ 8179 8180 #ifdef HAVE_MESSAGES 8181 if ( (0 != (flags & MHD_USE_THREAD_PER_CONNECTION)) && 8182 (0 == (flags & MHD_USE_INTERNAL_POLLING_THREAD)) ) 8183 { 8184 MHD_DLOG (daemon, 8185 _ ("Warning: MHD_USE_THREAD_PER_CONNECTION must be used " \ 8186 "only with MHD_USE_INTERNAL_POLLING_THREAD. " \ 8187 "Flag MHD_USE_INTERNAL_POLLING_THREAD was added. " \ 8188 "Consider setting MHD_USE_INTERNAL_POLLING_THREAD " \ 8189 "explicitly.\n")); 8190 } 8191 #endif 8192 8193 if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) 8194 && ((NULL != daemon->notify_completed) 8195 || (NULL != daemon->notify_connection)) ) 8196 *pflags |= MHD_USE_ITC; /* requires ITC */ 8197 8198 #ifdef _DEBUG 8199 #ifdef HAVE_MESSAGES 8200 MHD_DLOG (daemon, 8201 _ ("Using debug build of libmicrohttpd.\n") ); 8202 #endif /* HAVE_MESSAGES */ 8203 #endif /* _DEBUG */ 8204 8205 if ( (0 != (*pflags & MHD_USE_ITC)) 8206 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 8207 && (0 == daemon->worker_pool_size) 8208 #endif 8209 ) 8210 { 8211 if (! MHD_itc_init_ (daemon->itc)) 8212 { 8213 #ifdef HAVE_MESSAGES 8214 MHD_DLOG (daemon, 8215 _ ("Failed to create inter-thread communication channel: %s\n"), 8216 MHD_itc_last_strerror_ ()); 8217 #endif 8218 #ifdef HTTPS_SUPPORT 8219 if (NULL != daemon->priority_cache) 8220 gnutls_priority_deinit (daemon->priority_cache); 8221 #endif /* HTTPS_SUPPORT */ 8222 free (daemon); 8223 return NULL; 8224 } 8225 if (MHD_D_IS_USING_SELECT_ (daemon) && 8226 (! MHD_D_DOES_SCKT_FIT_FDSET_ (MHD_itc_r_fd_ (daemon->itc), daemon)) ) 8227 { 8228 #ifdef HAVE_MESSAGES 8229 MHD_DLOG (daemon, 8230 _ ("file descriptor for inter-thread communication " \ 8231 "channel exceeds maximum value.\n")); 8232 #endif 8233 MHD_itc_destroy_chk_ (daemon->itc); 8234 #ifdef HTTPS_SUPPORT 8235 if (NULL != daemon->priority_cache) 8236 gnutls_priority_deinit (daemon->priority_cache); 8237 #endif /* HTTPS_SUPPORT */ 8238 free (daemon); 8239 return NULL; 8240 } 8241 } 8242 8243 #ifdef DAUTH_SUPPORT 8244 if (NULL != daemon->digest_auth_random_copy) 8245 { 8246 mhd_assert (daemon == daemon->digest_auth_random_copy); 8247 daemon->digest_auth_random_copy = malloc (daemon->digest_auth_rand_size); 8248 if (NULL == daemon->digest_auth_random_copy) 8249 { 8250 #ifdef HTTPS_SUPPORT 8251 if (0 != (*pflags & MHD_USE_TLS)) 8252 gnutls_priority_deinit (daemon->priority_cache); 8253 #endif /* HTTPS_SUPPORT */ 8254 free (daemon); 8255 return NULL; 8256 } 8257 memcpy (daemon->digest_auth_random_copy, 8258 daemon->digest_auth_random, 8259 daemon->digest_auth_rand_size); 8260 daemon->digest_auth_random = daemon->digest_auth_random_copy; 8261 } 8262 if (daemon->nonce_nc_size > 0) 8263 { 8264 if ( ( (size_t) (daemon->nonce_nc_size * sizeof (struct MHD_NonceNc))) 8265 / sizeof(struct MHD_NonceNc) != daemon->nonce_nc_size) 8266 { 8267 #ifdef HAVE_MESSAGES 8268 MHD_DLOG (daemon, 8269 _ ("Specified value for NC_SIZE too large.\n")); 8270 #endif 8271 #ifdef HTTPS_SUPPORT 8272 if (0 != (*pflags & MHD_USE_TLS)) 8273 gnutls_priority_deinit (daemon->priority_cache); 8274 #endif /* HTTPS_SUPPORT */ 8275 free (daemon->digest_auth_random_copy); 8276 free (daemon); 8277 return NULL; 8278 } 8279 daemon->nnc = MHD_calloc_ (daemon->nonce_nc_size, 8280 sizeof (struct MHD_NonceNc)); 8281 if (NULL == daemon->nnc) 8282 { 8283 #ifdef HAVE_MESSAGES 8284 MHD_DLOG (daemon, 8285 _ ("Failed to allocate memory for nonce-nc map: %s\n"), 8286 MHD_strerror_ (errno)); 8287 #endif 8288 #ifdef HTTPS_SUPPORT 8289 if (0 != (*pflags & MHD_USE_TLS)) 8290 gnutls_priority_deinit (daemon->priority_cache); 8291 #endif /* HTTPS_SUPPORT */ 8292 free (daemon->digest_auth_random_copy); 8293 free (daemon); 8294 return NULL; 8295 } 8296 } 8297 8298 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 8299 if (! MHD_mutex_init_ (&daemon->nnc_lock)) 8300 { 8301 #ifdef HAVE_MESSAGES 8302 MHD_DLOG (daemon, 8303 _ ("MHD failed to initialize nonce-nc mutex.\n")); 8304 #endif 8305 #ifdef HTTPS_SUPPORT 8306 if (0 != (*pflags & MHD_USE_TLS)) 8307 gnutls_priority_deinit (daemon->priority_cache); 8308 #endif /* HTTPS_SUPPORT */ 8309 free (daemon->digest_auth_random_copy); 8310 free (daemon->nnc); 8311 free (daemon); 8312 return NULL; 8313 } 8314 #endif 8315 #endif 8316 8317 /* Thread polling currently works only with internal select thread mode */ 8318 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 8319 if ( (! MHD_D_IS_USING_THREADS_ (daemon)) && 8320 (daemon->worker_pool_size > 0) ) 8321 { 8322 #ifdef HAVE_MESSAGES 8323 MHD_DLOG (daemon, 8324 _ ("MHD thread polling only works with " \ 8325 "MHD_USE_INTERNAL_POLLING_THREAD.\n")); 8326 #endif 8327 goto free_and_fail; 8328 } 8329 #endif 8330 8331 if ( (MHD_INVALID_SOCKET == daemon->listen_fd) && 8332 (0 == (*pflags & MHD_USE_NO_LISTEN_SOCKET)) ) 8333 { 8334 /* try to open listen socket */ 8335 struct sockaddr_in servaddr4; 8336 #ifdef HAVE_INET6 8337 struct sockaddr_in6 servaddr6; 8338 const bool use_ipv6 = (0 != (*pflags & MHD_USE_IPv6)); 8339 #else /* ! HAVE_INET6 */ 8340 const bool use_ipv6 = false; 8341 #endif /* ! HAVE_INET6 */ 8342 int domain; 8343 8344 if (NULL != pservaddr) 8345 { 8346 #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN 8347 const socklen_t sa_len = pservaddr->sa_len; 8348 #endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */ 8349 #ifdef HAVE_INET6 8350 if (use_ipv6 && (AF_INET6 != pservaddr->sa_family)) 8351 { 8352 #ifdef HAVE_MESSAGES 8353 MHD_DLOG (daemon, 8354 _ ("MHD_USE_IPv6 is enabled, but 'struct sockaddr *' " \ 8355 "specified for MHD_OPTION_SOCK_ADDR_LEN or " \ 8356 "MHD_OPTION_SOCK_ADDR is not IPv6 address.\n")); 8357 #endif /* HAVE_MESSAGES */ 8358 goto free_and_fail; 8359 } 8360 #endif /* HAVE_INET6 */ 8361 switch (pservaddr->sa_family) 8362 { 8363 case AF_INET: 8364 if (1) 8365 { 8366 struct sockaddr_in sa4; 8367 uint16_t sa4_port; 8368 if ((0 != addrlen) 8369 && (((socklen_t) sizeof(sa4)) > addrlen)) 8370 { 8371 #ifdef HAVE_MESSAGES 8372 MHD_DLOG (daemon, 8373 _ ("The size specified for MHD_OPTION_SOCK_ADDR_LEN " \ 8374 "option is wrong.\n")); 8375 #endif /* HAVE_MESSAGES */ 8376 goto free_and_fail; 8377 } 8378 #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN 8379 if (0 != sa_len) 8380 { 8381 if (((socklen_t) sizeof(sa4)) > sa_len) 8382 { 8383 #ifdef HAVE_MESSAGES 8384 MHD_DLOG (daemon, 8385 _ ("The value of 'struct sockaddr.sa_len' provided " \ 8386 "via MHD_OPTION_SOCK_ADDR_LEN option is not zero " \ 8387 "and does not match 'sa_family' value of the " \ 8388 "same structure.\n")); 8389 #endif /* HAVE_MESSAGES */ 8390 goto free_and_fail; 8391 } 8392 if ((0 == addrlen) || (sa_len < addrlen)) 8393 addrlen = sa_len; /* Use smaller value for safety */ 8394 } 8395 #endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */ 8396 if (0 == addrlen) 8397 addrlen = sizeof(sa4); 8398 memcpy (&sa4, pservaddr, sizeof(sa4)); /* Required due to stronger alignment */ 8399 sa4_port = (uint16_t) ntohs (sa4.sin_port); 8400 #ifndef MHD_USE_GETSOCKNAME 8401 if (0 != sa4_port) 8402 #endif /* ! MHD_USE_GETSOCKNAME */ 8403 daemon->port = sa4_port; 8404 domain = PF_INET; 8405 } 8406 break; 8407 #ifdef HAVE_INET6 8408 case AF_INET6: 8409 if (1) 8410 { 8411 struct sockaddr_in6 sa6; 8412 uint16_t sa6_port; 8413 if ((0 != addrlen) 8414 && (((socklen_t) sizeof(sa6)) > addrlen)) 8415 { 8416 #ifdef HAVE_MESSAGES 8417 MHD_DLOG (daemon, 8418 _ ("The size specified for MHD_OPTION_SOCK_ADDR_LEN " \ 8419 "option is wrong.\n")); 8420 #endif /* HAVE_MESSAGES */ 8421 goto free_and_fail; 8422 } 8423 #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN 8424 if (0 != sa_len) 8425 { 8426 if (((socklen_t) sizeof(sa6)) > sa_len) 8427 { 8428 #ifdef HAVE_MESSAGES 8429 MHD_DLOG (daemon, 8430 _ ("The value of 'struct sockaddr.sa_len' provided " \ 8431 "via MHD_OPTION_SOCK_ADDR_LEN option is not zero " \ 8432 "and does not match 'sa_family' value of the " \ 8433 "same structure.\n")); 8434 #endif /* HAVE_MESSAGES */ 8435 goto free_and_fail; 8436 } 8437 if ((0 == addrlen) || (sa_len < addrlen)) 8438 addrlen = sa_len; /* Use smaller value for safety */ 8439 } 8440 #endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */ 8441 if (0 == addrlen) 8442 addrlen = sizeof(sa6); 8443 memcpy (&sa6, pservaddr, sizeof(sa6)); /* Required due to stronger alignment */ 8444 sa6_port = (uint16_t) ntohs (sa6.sin6_port); 8445 #ifndef MHD_USE_GETSOCKNAME 8446 if (0 != sa6_port) 8447 #endif /* ! MHD_USE_GETSOCKNAME */ 8448 daemon->port = sa6_port; 8449 domain = PF_INET6; 8450 *pflags |= ((enum MHD_FLAG) MHD_USE_IPv6); 8451 } 8452 break; 8453 #endif /* HAVE_INET6 */ 8454 #ifdef AF_UNIX 8455 case AF_UNIX: 8456 #endif /* AF_UNIX */ 8457 default: 8458 #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN 8459 if (0 == addrlen) 8460 addrlen = sa_len; 8461 else if ((0 != sa_len) && (sa_len < addrlen)) 8462 addrlen = sa_len; /* Use smaller value for safety */ 8463 #endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */ 8464 if (0 >= addrlen) 8465 { 8466 #ifdef HAVE_MESSAGES 8467 MHD_DLOG (daemon, 8468 _ ("The 'sa_family' of the 'struct sockaddr' provided " \ 8469 "via MHD_OPTION_SOCK_ADDR option is not supported.\n")); 8470 #endif /* HAVE_MESSAGES */ 8471 goto free_and_fail; 8472 } 8473 #ifdef AF_UNIX 8474 if (AF_UNIX == pservaddr->sa_family) 8475 { 8476 daemon->port = 0; /* special value for UNIX domain sockets */ 8477 daemon->listen_is_unix = _MHD_YES; 8478 #ifdef PF_UNIX 8479 domain = PF_UNIX; 8480 #else /* ! PF_UNIX */ 8481 domain = AF_UNIX; 8482 #endif /* ! PF_UNIX */ 8483 } 8484 else /* combined with the next 'if' */ 8485 #endif /* AF_UNIX */ 8486 if (1) 8487 { 8488 daemon->port = 0; /* ugh */ 8489 daemon->listen_is_unix = _MHD_UNKNOWN; 8490 /* Assumed the same values for AF_* and PF_* */ 8491 domain = pservaddr->sa_family; 8492 } 8493 break; 8494 } 8495 } 8496 else 8497 { 8498 if (! use_ipv6) 8499 { 8500 memset (&servaddr4, 8501 0, 8502 sizeof (struct sockaddr_in)); 8503 servaddr4.sin_family = AF_INET; 8504 servaddr4.sin_port = htons (port); 8505 if (0 != INADDR_ANY) 8506 servaddr4.sin_addr.s_addr = htonl (INADDR_ANY); 8507 #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN 8508 servaddr4.sin_len = sizeof (struct sockaddr_in); 8509 #endif 8510 pservaddr = (struct sockaddr *) &servaddr4; 8511 addrlen = (socklen_t) sizeof(servaddr4); 8512 daemon->listen_is_unix = _MHD_NO; 8513 domain = PF_INET; 8514 } 8515 #ifdef HAVE_INET6 8516 else 8517 { 8518 #ifdef IN6ADDR_ANY_INIT 8519 static const struct in6_addr static_in6any = IN6ADDR_ANY_INIT; 8520 #endif 8521 memset (&servaddr6, 8522 0, 8523 sizeof (struct sockaddr_in6)); 8524 servaddr6.sin6_family = AF_INET6; 8525 servaddr6.sin6_port = htons (port); 8526 #ifdef IN6ADDR_ANY_INIT 8527 servaddr6.sin6_addr = static_in6any; 8528 #endif 8529 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN 8530 servaddr6.sin6_len = sizeof (struct sockaddr_in6); 8531 #endif 8532 pservaddr = (struct sockaddr *) &servaddr6; 8533 addrlen = (socklen_t) sizeof (servaddr6); 8534 daemon->listen_is_unix = _MHD_NO; 8535 domain = PF_INET6; 8536 } 8537 #endif /* HAVE_INET6 */ 8538 } 8539 8540 daemon->listen_fd = MHD_socket_create_listen_ (domain); 8541 if (MHD_INVALID_SOCKET == daemon->listen_fd) 8542 { 8543 #ifdef HAVE_MESSAGES 8544 MHD_DLOG (daemon, 8545 _ ("Failed to create socket for listening: %s\n"), 8546 MHD_socket_last_strerr_ ()); 8547 #endif 8548 goto free_and_fail; 8549 } 8550 if (MHD_D_IS_USING_SELECT_ (daemon) && 8551 (! MHD_D_DOES_SCKT_FIT_FDSET_ (daemon->listen_fd, 8552 daemon)) ) 8553 { 8554 #ifdef HAVE_MESSAGES 8555 MHD_DLOG (daemon, 8556 _ ("Listen socket descriptor (%d) is not " \ 8557 "less than daemon FD_SETSIZE value (%d).\n"), 8558 (int) daemon->listen_fd, 8559 (int) MHD_D_GET_FD_SETSIZE_ (daemon)); 8560 #endif 8561 goto free_and_fail; 8562 } 8563 8564 /* Apply the socket options according to listening_address_reuse. */ 8565 if (0 == daemon->listening_address_reuse) 8566 { 8567 #ifndef MHD_WINSOCK_SOCKETS 8568 /* No user requirement, use "traditional" default SO_REUSEADDR 8569 * on non-W32 platforms, and do not fail if it doesn't work. 8570 * Don't use it on W32, because on W32 it will allow multiple 8571 * bind to the same address:port, like SO_REUSEPORT on others. */ 8572 if (0 > setsockopt (daemon->listen_fd, 8573 SOL_SOCKET, 8574 SO_REUSEADDR, 8575 (const void *) &on, sizeof (on))) 8576 { 8577 #ifdef HAVE_MESSAGES 8578 MHD_DLOG (daemon, 8579 _ ("setsockopt failed: %s\n"), 8580 MHD_socket_last_strerr_ ()); 8581 #endif 8582 } 8583 #endif /* ! MHD_WINSOCK_SOCKETS */ 8584 } 8585 else if (daemon->listening_address_reuse > 0) 8586 { 8587 /* User requested to allow reusing listening address:port. */ 8588 #ifndef MHD_WINSOCK_SOCKETS 8589 /* Use SO_REUSEADDR on non-W32 platforms, and do not fail if 8590 * it doesn't work. */ 8591 if (0 > setsockopt (daemon->listen_fd, 8592 SOL_SOCKET, 8593 SO_REUSEADDR, 8594 (const void *) &on, sizeof (on))) 8595 { 8596 #ifdef HAVE_MESSAGES 8597 MHD_DLOG (daemon, 8598 _ ("setsockopt failed: %s\n"), 8599 MHD_socket_last_strerr_ ()); 8600 #endif 8601 } 8602 #endif /* ! MHD_WINSOCK_SOCKETS */ 8603 /* Use SO_REUSEADDR on Windows and SO_REUSEPORT on most platforms. 8604 * Fail if SO_REUSEPORT is not defined or setsockopt fails. 8605 */ 8606 /* SO_REUSEADDR on W32 has the same semantics 8607 as SO_REUSEPORT on BSD/Linux */ 8608 #if defined(MHD_WINSOCK_SOCKETS) || defined(SO_REUSEPORT) 8609 if (0 > setsockopt (daemon->listen_fd, 8610 SOL_SOCKET, 8611 #ifndef MHD_WINSOCK_SOCKETS 8612 SO_REUSEPORT, 8613 #else /* MHD_WINSOCK_SOCKETS */ 8614 SO_REUSEADDR, 8615 #endif /* MHD_WINSOCK_SOCKETS */ 8616 (const void *) &on, 8617 sizeof (on))) 8618 { 8619 #ifdef HAVE_MESSAGES 8620 MHD_DLOG (daemon, 8621 _ ("setsockopt failed: %s\n"), 8622 MHD_socket_last_strerr_ ()); 8623 #endif 8624 goto free_and_fail; 8625 } 8626 #else /* !MHD_WINSOCK_SOCKETS && !SO_REUSEPORT */ 8627 /* we're supposed to allow address:port re-use, but 8628 on this platform we cannot; fail hard */ 8629 #ifdef HAVE_MESSAGES 8630 MHD_DLOG (daemon, 8631 _ ("Cannot allow listening address reuse: " \ 8632 "SO_REUSEPORT not defined.\n")); 8633 #endif 8634 goto free_and_fail; 8635 #endif /* !MHD_WINSOCK_SOCKETS && !SO_REUSEPORT */ 8636 } 8637 else /* if (daemon->listening_address_reuse < 0) */ 8638 { 8639 /* User requested to disallow reusing listening address:port. 8640 * Do nothing except for Windows where SO_EXCLUSIVEADDRUSE 8641 * is used and Solaris with SO_EXCLBIND. 8642 * Fail if MHD was compiled for W32 without SO_EXCLUSIVEADDRUSE 8643 * or setsockopt fails. 8644 */ 8645 #if (defined(MHD_WINSOCK_SOCKETS) && defined(SO_EXCLUSIVEADDRUSE)) || \ 8646 (defined(__sun) && defined(SO_EXCLBIND)) 8647 if (0 > setsockopt (daemon->listen_fd, 8648 SOL_SOCKET, 8649 #ifdef SO_EXCLUSIVEADDRUSE 8650 SO_EXCLUSIVEADDRUSE, 8651 #else /* SO_EXCLBIND */ 8652 SO_EXCLBIND, 8653 #endif /* SO_EXCLBIND */ 8654 (const void *) &on, 8655 sizeof (on))) 8656 { 8657 #ifdef HAVE_MESSAGES 8658 MHD_DLOG (daemon, 8659 _ ("setsockopt failed: %s\n"), 8660 MHD_socket_last_strerr_ ()); 8661 #endif 8662 goto free_and_fail; 8663 } 8664 #elif defined(MHD_WINSOCK_SOCKETS) /* SO_EXCLUSIVEADDRUSE not defined on W32? */ 8665 #ifdef HAVE_MESSAGES 8666 MHD_DLOG (daemon, 8667 _ ("Cannot disallow listening address reuse: " \ 8668 "SO_EXCLUSIVEADDRUSE not defined.\n")); 8669 #endif 8670 goto free_and_fail; 8671 #endif /* MHD_WINSOCK_SOCKETS */ 8672 } 8673 8674 /* check for user supplied sockaddr */ 8675 if (0 != (*pflags & MHD_USE_IPv6)) 8676 { 8677 #ifdef IPPROTO_IPV6 8678 #ifdef IPV6_V6ONLY 8679 /* Note: "IPV6_V6ONLY" is declared by Windows Vista ff., see "IPPROTO_IPV6 Socket Options" 8680 (http://msdn.microsoft.com/en-us/library/ms738574%28v=VS.85%29.aspx); 8681 and may also be missing on older POSIX systems; good luck if you have any of those, 8682 your IPv6 socket may then also bind against IPv4 anyway... */ 8683 const MHD_SCKT_OPT_BOOL_ v6_only = 8684 (MHD_USE_DUAL_STACK != (*pflags & MHD_USE_DUAL_STACK)); 8685 if (0 > setsockopt (daemon->listen_fd, 8686 IPPROTO_IPV6, IPV6_V6ONLY, 8687 (const void *) &v6_only, 8688 sizeof (v6_only))) 8689 { 8690 #ifdef HAVE_MESSAGES 8691 MHD_DLOG (daemon, 8692 _ ("setsockopt failed: %s\n"), 8693 MHD_socket_last_strerr_ ()); 8694 #endif 8695 } 8696 #endif 8697 #endif 8698 } 8699 if (0 != bind (daemon->listen_fd, 8700 pservaddr, 8701 addrlen)) 8702 { 8703 #ifdef HAVE_MESSAGES 8704 MHD_DLOG (daemon, 8705 _ ("Failed to bind to port %u: %s\n"), 8706 (unsigned int) port, 8707 MHD_socket_last_strerr_ ()); 8708 #endif 8709 goto free_and_fail; 8710 } 8711 #ifdef TCP_FASTOPEN 8712 if (0 != (*pflags & MHD_USE_TCP_FASTOPEN)) 8713 { 8714 if (0 == daemon->fastopen_queue_size) 8715 daemon->fastopen_queue_size = MHD_TCP_FASTOPEN_QUEUE_SIZE_DEFAULT; 8716 if (0 != setsockopt (daemon->listen_fd, 8717 IPPROTO_TCP, 8718 TCP_FASTOPEN, 8719 (const void *) &daemon->fastopen_queue_size, 8720 sizeof (daemon->fastopen_queue_size))) 8721 { 8722 #ifdef HAVE_MESSAGES 8723 MHD_DLOG (daemon, 8724 _ ("setsockopt failed: %s\n"), 8725 MHD_socket_last_strerr_ ()); 8726 #endif 8727 } 8728 } 8729 #endif 8730 if (0 != listen (daemon->listen_fd, 8731 (int) daemon->listen_backlog_size)) 8732 { 8733 #ifdef HAVE_MESSAGES 8734 MHD_DLOG (daemon, 8735 _ ("Failed to listen for connections: %s\n"), 8736 MHD_socket_last_strerr_ ()); 8737 #endif 8738 goto free_and_fail; 8739 } 8740 } 8741 else 8742 { 8743 if (MHD_D_IS_USING_SELECT_ (daemon) && 8744 (! MHD_D_DOES_SCKT_FIT_FDSET_ (daemon->listen_fd, 8745 daemon)) ) 8746 { 8747 #ifdef HAVE_MESSAGES 8748 MHD_DLOG (daemon, 8749 _ ("Listen socket descriptor (%d) is not " \ 8750 "less than daemon FD_SETSIZE value (%d).\n"), 8751 (int) daemon->listen_fd, 8752 (int) MHD_D_GET_FD_SETSIZE_ (daemon)); 8753 #endif 8754 goto free_and_fail; 8755 } 8756 else 8757 { 8758 #if defined(SOL_SOCKET) && (defined(SO_DOMAIN) || defined(SO_PROTOCOL_INFOW)) 8759 int af; 8760 int opt_name; 8761 void *poptval; 8762 socklen_t optval_size; 8763 #ifdef SO_DOMAIN 8764 opt_name = SO_DOMAIN; 8765 poptval = ⁡ 8766 optval_size = (socklen_t) sizeof (af); 8767 #else /* SO_PROTOCOL_INFOW */ 8768 WSAPROTOCOL_INFOW prot_info; 8769 opt_name = SO_PROTOCOL_INFOW; 8770 poptval = &prot_info; 8771 optval_size = (socklen_t) sizeof (prot_info); 8772 #endif /* SO_PROTOCOL_INFOW */ 8773 8774 if (0 == getsockopt (daemon->listen_fd, 8775 SOL_SOCKET, 8776 opt_name, 8777 poptval, 8778 &optval_size)) 8779 { 8780 #ifndef SO_DOMAIN 8781 af = prot_info.iAddressFamily; 8782 #endif /* SO_DOMAIN */ 8783 switch (af) 8784 { 8785 case AF_INET: 8786 daemon->listen_is_unix = _MHD_NO; 8787 break; 8788 #ifdef HAVE_INET6 8789 case AF_INET6: 8790 *pflags |= MHD_USE_IPv6; 8791 daemon->listen_is_unix = _MHD_NO; 8792 break; 8793 #endif /* HAVE_INET6 */ 8794 #ifdef AF_UNIX 8795 case AF_UNIX: 8796 daemon->port = 0; /* special value for UNIX domain sockets */ 8797 daemon->listen_is_unix = _MHD_YES; 8798 break; 8799 #endif /* AF_UNIX */ 8800 default: 8801 daemon->port = 0; /* ugh */ 8802 daemon->listen_is_unix = _MHD_UNKNOWN; 8803 break; 8804 } 8805 } 8806 else 8807 #endif /* SOL_SOCKET && (SO_DOMAIN || SO_PROTOCOL_INFOW)) */ 8808 daemon->listen_is_unix = _MHD_UNKNOWN; 8809 } 8810 8811 #ifdef MHD_USE_GETSOCKNAME 8812 daemon->port = 0; /* Force use of autodetection */ 8813 #endif /* MHD_USE_GETSOCKNAME */ 8814 } 8815 8816 #ifdef MHD_USE_GETSOCKNAME 8817 if ( (0 == daemon->port) && 8818 (0 == (*pflags & MHD_USE_NO_LISTEN_SOCKET)) && 8819 (_MHD_YES != daemon->listen_is_unix) ) 8820 { /* Get port number. */ 8821 struct sockaddr_storage bindaddr; 8822 8823 memset (&bindaddr, 8824 0, 8825 sizeof (struct sockaddr_storage)); 8826 addrlen = sizeof (struct sockaddr_storage); 8827 #ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN 8828 bindaddr.ss_len = (socklen_t) addrlen; 8829 #endif 8830 if (0 != getsockname (daemon->listen_fd, 8831 (struct sockaddr *) &bindaddr, 8832 &addrlen)) 8833 { 8834 #ifdef HAVE_MESSAGES 8835 MHD_DLOG (daemon, 8836 _ ("Failed to get listen port number: %s\n"), 8837 MHD_socket_last_strerr_ ()); 8838 #endif /* HAVE_MESSAGES */ 8839 } 8840 #ifdef MHD_POSIX_SOCKETS 8841 else if (sizeof (bindaddr) < addrlen) 8842 { 8843 /* should be impossible with `struct sockaddr_storage` */ 8844 #ifdef HAVE_MESSAGES 8845 MHD_DLOG (daemon, 8846 _ ("Failed to get listen port number " \ 8847 "(`struct sockaddr_storage` too small!?).\n")); 8848 #endif /* HAVE_MESSAGES */ 8849 } 8850 #ifndef __linux__ 8851 else if (0 == addrlen) 8852 { 8853 /* Many non-Linux-based platforms return zero addrlen 8854 * for AF_UNIX sockets */ 8855 daemon->port = 0; /* special value for UNIX domain sockets */ 8856 if (_MHD_UNKNOWN == daemon->listen_is_unix) 8857 daemon->listen_is_unix = _MHD_YES; 8858 } 8859 #endif /* __linux__ */ 8860 #endif /* MHD_POSIX_SOCKETS */ 8861 else 8862 { 8863 switch (bindaddr.ss_family) 8864 { 8865 case AF_INET: 8866 { 8867 struct sockaddr_in *s4 = (struct sockaddr_in *) &bindaddr; 8868 8869 daemon->port = ntohs (s4->sin_port); 8870 daemon->listen_is_unix = _MHD_NO; 8871 break; 8872 } 8873 #ifdef HAVE_INET6 8874 case AF_INET6: 8875 { 8876 struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) &bindaddr; 8877 8878 daemon->port = ntohs (s6->sin6_port); 8879 daemon->listen_is_unix = _MHD_NO; 8880 mhd_assert (0 != (*pflags & MHD_USE_IPv6)); 8881 break; 8882 } 8883 #endif /* HAVE_INET6 */ 8884 #ifdef AF_UNIX 8885 case AF_UNIX: 8886 daemon->port = 0; /* special value for UNIX domain sockets */ 8887 daemon->listen_is_unix = _MHD_YES; 8888 break; 8889 #endif 8890 default: 8891 #ifdef HAVE_MESSAGES 8892 MHD_DLOG (daemon, 8893 _ ("Listen socket has unknown address family!\n")); 8894 #endif 8895 daemon->port = 0; /* ugh */ 8896 daemon->listen_is_unix = _MHD_UNKNOWN; 8897 break; 8898 } 8899 } 8900 } 8901 #endif /* MHD_USE_GETSOCKNAME */ 8902 8903 if (MHD_INVALID_SOCKET != daemon->listen_fd) 8904 { 8905 mhd_assert (0 == (*pflags & MHD_USE_NO_LISTEN_SOCKET)); 8906 if (! MHD_socket_nonblocking_ (daemon->listen_fd)) 8907 { 8908 #ifdef HAVE_MESSAGES 8909 MHD_DLOG (daemon, 8910 _ ("Failed to set nonblocking mode on listening socket: %s\n"), 8911 MHD_socket_last_strerr_ ()); 8912 #endif 8913 if (MHD_D_IS_USING_EPOLL_ (daemon) 8914 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 8915 || (daemon->worker_pool_size > 0) 8916 #endif 8917 ) 8918 { 8919 /* Accept must be non-blocking. Multiple children may wake up 8920 * to handle a new connection, but only one will win the race. 8921 * The others must immediately return. */ 8922 goto free_and_fail; 8923 } 8924 daemon->listen_nonblk = false; 8925 } 8926 else 8927 daemon->listen_nonblk = true; 8928 } 8929 else 8930 { 8931 mhd_assert (0 != (*pflags & MHD_USE_NO_LISTEN_SOCKET)); 8932 daemon->listen_nonblk = false; /* Actually listen socket does not exist */ 8933 } 8934 8935 #ifdef EPOLL_SUPPORT 8936 if (MHD_D_IS_USING_EPOLL_ (daemon) 8937 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 8938 && (0 == daemon->worker_pool_size) 8939 #endif 8940 ) 8941 { 8942 if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) 8943 { 8944 #ifdef HAVE_MESSAGES 8945 MHD_DLOG (daemon, 8946 _ ("Combining MHD_USE_THREAD_PER_CONNECTION and " \ 8947 "MHD_USE_EPOLL is not supported.\n")); 8948 #endif 8949 goto free_and_fail; 8950 } 8951 if (MHD_NO == setup_epoll_to_listen (daemon)) 8952 goto free_and_fail; 8953 } 8954 #endif /* EPOLL_SUPPORT */ 8955 8956 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 8957 if (! MHD_mutex_init_ (&daemon->per_ip_connection_mutex)) 8958 { 8959 #ifdef HAVE_MESSAGES 8960 MHD_DLOG (daemon, 8961 _ ("MHD failed to initialize IP connection limit mutex.\n")); 8962 #endif 8963 goto free_and_fail; 8964 } 8965 #endif 8966 8967 #ifdef HTTPS_SUPPORT 8968 /* initialize HTTPS daemon certificate aspects & send / recv functions */ 8969 if ( (0 != (*pflags & MHD_USE_TLS)) && 8970 (0 != MHD_TLS_init (daemon)) ) 8971 { 8972 #ifdef HAVE_MESSAGES 8973 MHD_DLOG (daemon, 8974 _ ("Failed to initialize TLS support.\n")); 8975 #endif 8976 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 8977 MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); 8978 #endif 8979 goto free_and_fail; 8980 } 8981 #endif /* HTTPS_SUPPORT */ 8982 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 8983 /* Start threads if requested by parameters */ 8984 if (MHD_D_IS_USING_THREADS_ (daemon)) 8985 { 8986 /* Internal thread (or threads) is used. 8987 * Make sure that MHD will be able to communicate with threads. */ 8988 /* If using a thread pool ITC will be initialised later 8989 * for each individual worker thread. */ 8990 #ifdef HAVE_LISTEN_SHUTDOWN 8991 mhd_assert ((1 < daemon->worker_pool_size) || \ 8992 (MHD_ITC_IS_VALID_ (daemon->itc)) || \ 8993 (MHD_INVALID_SOCKET != daemon->listen_fd)); 8994 #else /* ! HAVE_LISTEN_SHUTDOWN */ 8995 mhd_assert ((1 < daemon->worker_pool_size) || \ 8996 (MHD_ITC_IS_VALID_ (daemon->itc))); 8997 #endif /* ! HAVE_LISTEN_SHUTDOWN */ 8998 if (0 == daemon->worker_pool_size) 8999 { 9000 if (! MHD_mutex_init_ (&daemon->cleanup_connection_mutex)) 9001 { 9002 #ifdef HAVE_MESSAGES 9003 MHD_DLOG (daemon, 9004 _ ("Failed to initialise internal lists mutex.\n")); 9005 #endif 9006 MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); 9007 goto free_and_fail; 9008 } 9009 if (! MHD_mutex_init_ (&daemon->new_connections_mutex)) 9010 { 9011 #ifdef HAVE_MESSAGES 9012 MHD_DLOG (daemon, 9013 _ ("Failed to initialise mutex.\n")); 9014 #endif 9015 MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); 9016 MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex); 9017 goto free_and_fail; 9018 } 9019 if (! MHD_mutex_init_ (&daemon->epoll_listen_mutex)) 9020 { 9021 #ifdef HAVE_MESSAGES 9022 MHD_DLOG (daemon, 9023 _ ("Failed to initialise mutex.\n")); 9024 #endif 9025 MHD_mutex_destroy_chk_ (&daemon->new_connections_mutex); 9026 MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex); 9027 MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); 9028 goto free_and_fail; 9029 } 9030 if (! MHD_create_named_thread_ (&daemon->tid, 9031 MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) ? 9032 "MHD-listen" : "MHD-single", 9033 daemon->thread_stack_size, 9034 &MHD_polling_thread, 9035 daemon) ) 9036 { 9037 #ifdef HAVE_MESSAGES 9038 #ifdef EAGAIN 9039 if (EAGAIN == errno) 9040 MHD_DLOG (daemon, 9041 _ ("Failed to create a new thread because it would have " \ 9042 "exceeded the system limit on the number of threads or " \ 9043 "no system resources available.\n")); 9044 else 9045 #endif /* EAGAIN */ 9046 MHD_DLOG (daemon, 9047 _ ("Failed to create listen thread: %s\n"), 9048 MHD_strerror_ (errno)); 9049 #endif /* HAVE_MESSAGES */ 9050 MHD_mutex_destroy_chk_ (&daemon->epoll_listen_mutex); 9051 MHD_mutex_destroy_chk_ (&daemon->new_connections_mutex); 9052 MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); 9053 MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex); 9054 goto free_and_fail; 9055 } 9056 } 9057 else /* 0 < daemon->worker_pool_size */ 9058 { 9059 /* Coarse-grained count of connections per thread (note error 9060 * due to integer division). Also keep track of how many 9061 * connections are leftover after an equal split. */ 9062 unsigned int conns_per_thread = daemon->connection_limit 9063 / daemon->worker_pool_size; 9064 unsigned int leftover_conns = daemon->connection_limit 9065 % daemon->worker_pool_size; 9066 9067 mhd_assert (2 <= daemon->worker_pool_size); 9068 i = 0; /* we need this in case fcntl or malloc fails */ 9069 9070 /* Allocate memory for pooled objects */ 9071 daemon->worker_pool = malloc (sizeof (struct MHD_Daemon) 9072 * daemon->worker_pool_size); 9073 if (NULL == daemon->worker_pool) 9074 goto thread_failed; 9075 9076 /* Start the workers in the pool */ 9077 for (i = 0; i < daemon->worker_pool_size; ++i) 9078 { 9079 /* Create copy of the Daemon object for each worker */ 9080 struct MHD_Daemon *d = &daemon->worker_pool[i]; 9081 9082 memcpy (d, daemon, sizeof (struct MHD_Daemon)); 9083 /* Adjust polling params for worker daemons; note that memcpy() 9084 has already copied MHD_USE_INTERNAL_POLLING_THREAD thread mode into 9085 the worker threads. */ 9086 d->master = daemon; 9087 d->worker_pool_size = 0; 9088 d->worker_pool = NULL; 9089 if (! MHD_mutex_init_ (&d->cleanup_connection_mutex)) 9090 { 9091 #ifdef HAVE_MESSAGES 9092 MHD_DLOG (daemon, 9093 _ ("Failed to initialise internal lists mutex.\n")); 9094 #endif 9095 goto thread_failed; 9096 } 9097 if (! MHD_mutex_init_ (&d->new_connections_mutex)) 9098 { 9099 #ifdef HAVE_MESSAGES 9100 MHD_DLOG (daemon, 9101 _ ("Failed to initialise mutex.\n")); 9102 #endif 9103 MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex); 9104 goto thread_failed; 9105 } 9106 if (! MHD_mutex_init_ (&d->epoll_listen_mutex)) 9107 { 9108 #ifdef HAVE_MESSAGES 9109 MHD_DLOG (daemon, 9110 _ ("Failed to initialise mutex.\n")); 9111 #endif 9112 MHD_mutex_destroy_chk_ (&d->new_connections_mutex); 9113 MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex); 9114 MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); 9115 goto free_and_fail; 9116 } 9117 if (0 != (*pflags & MHD_USE_ITC)) 9118 { 9119 if (! MHD_itc_init_ (d->itc)) 9120 { 9121 #ifdef HAVE_MESSAGES 9122 MHD_DLOG (daemon, 9123 _ ("Failed to create worker inter-thread " \ 9124 "communication channel: %s\n"), 9125 MHD_itc_last_strerror_ () ); 9126 #endif 9127 MHD_mutex_destroy_chk_ (&d->epoll_listen_mutex); 9128 MHD_mutex_destroy_chk_ (&d->new_connections_mutex); 9129 MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex); 9130 goto thread_failed; 9131 } 9132 if (MHD_D_IS_USING_SELECT_ (d) && 9133 (! MHD_D_DOES_SCKT_FIT_FDSET_ (MHD_itc_r_fd_ (d->itc), daemon)) ) 9134 { 9135 #ifdef HAVE_MESSAGES 9136 MHD_DLOG (daemon, 9137 _ ("File descriptor for worker inter-thread " \ 9138 "communication channel exceeds maximum value.\n")); 9139 #endif 9140 MHD_itc_destroy_chk_ (d->itc); 9141 MHD_mutex_destroy_chk_ (&d->epoll_listen_mutex); 9142 MHD_mutex_destroy_chk_ (&d->new_connections_mutex); 9143 MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex); 9144 goto thread_failed; 9145 } 9146 } 9147 else 9148 MHD_itc_set_invalid_ (d->itc); 9149 9150 #ifdef HAVE_LISTEN_SHUTDOWN 9151 mhd_assert ((MHD_ITC_IS_VALID_ (d->itc)) || \ 9152 (MHD_INVALID_SOCKET != d->listen_fd)); 9153 #else /* ! HAVE_LISTEN_SHUTDOWN */ 9154 mhd_assert (MHD_ITC_IS_VALID_ (d->itc)); 9155 #endif /* ! HAVE_LISTEN_SHUTDOWN */ 9156 9157 /* Divide available connections evenly amongst the threads. 9158 * Thread indexes in [0, leftover_conns) each get one of the 9159 * leftover connections. */ 9160 d->connection_limit = conns_per_thread; 9161 if (i < leftover_conns) 9162 ++d->connection_limit; 9163 #ifdef EPOLL_SUPPORT 9164 if (MHD_D_IS_USING_EPOLL_ (d) && 9165 (MHD_NO == setup_epoll_to_listen (d)) ) 9166 { 9167 if (MHD_ITC_IS_VALID_ (d->itc)) 9168 MHD_itc_destroy_chk_ (d->itc); 9169 MHD_mutex_destroy_chk_ (&d->epoll_listen_mutex); 9170 MHD_mutex_destroy_chk_ (&d->new_connections_mutex); 9171 MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex); 9172 goto thread_failed; 9173 } 9174 #endif 9175 /* Some members must be used only in master daemon */ 9176 #if defined(MHD_USE_THREADS) 9177 memset (&d->per_ip_connection_mutex, 0x7F, 9178 sizeof(d->per_ip_connection_mutex)); 9179 #endif /* MHD_USE_THREADS */ 9180 #ifdef DAUTH_SUPPORT 9181 d->nnc = NULL; 9182 d->nonce_nc_size = 0; 9183 d->digest_auth_random_copy = NULL; 9184 #if defined(MHD_USE_THREADS) 9185 memset (&d->nnc_lock, 0x7F, sizeof(d->nnc_lock)); 9186 #endif /* MHD_USE_THREADS */ 9187 #endif /* DAUTH_SUPPORT */ 9188 9189 /* Spawn the worker thread */ 9190 if (! MHD_create_named_thread_ (&d->tid, 9191 "MHD-worker", 9192 daemon->thread_stack_size, 9193 &MHD_polling_thread, 9194 d)) 9195 { 9196 #ifdef HAVE_MESSAGES 9197 #ifdef EAGAIN 9198 if (EAGAIN == errno) 9199 MHD_DLOG (daemon, 9200 _ ("Failed to create a new pool thread because it would " \ 9201 "have exceeded the system limit on the number of " \ 9202 "threads or no system resources available.\n")); 9203 else 9204 #endif /* EAGAIN */ 9205 MHD_DLOG (daemon, 9206 _ ("Failed to create pool thread: %s\n"), 9207 MHD_strerror_ (errno)); 9208 #endif 9209 /* Free memory for this worker; cleanup below handles 9210 * all previously-created workers. */ 9211 if (MHD_ITC_IS_VALID_ (d->itc)) 9212 MHD_itc_destroy_chk_ (d->itc); 9213 MHD_mutex_destroy_chk_ (&d->epoll_listen_mutex); 9214 MHD_mutex_destroy_chk_ (&d->new_connections_mutex); 9215 MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex); 9216 goto thread_failed; 9217 } 9218 } 9219 } 9220 } 9221 else 9222 { /* Daemon without internal threads */ 9223 if (! MHD_mutex_init_ (&daemon->cleanup_connection_mutex)) 9224 { 9225 #ifdef HAVE_MESSAGES 9226 MHD_DLOG (daemon, 9227 _ ("Failed to initialise internal lists mutex.\n")); 9228 #endif 9229 MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); 9230 goto free_and_fail; 9231 } 9232 if (! MHD_mutex_init_ (&daemon->new_connections_mutex)) 9233 { 9234 #ifdef HAVE_MESSAGES 9235 MHD_DLOG (daemon, 9236 _ ("Failed to initialise mutex.\n")); 9237 #endif 9238 MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex); 9239 MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); 9240 goto free_and_fail; 9241 } 9242 if (! MHD_mutex_init_ (&daemon->epoll_listen_mutex)) 9243 { 9244 #ifdef HAVE_MESSAGES 9245 MHD_DLOG (daemon, 9246 _ ("Failed to initialise mutex.\n")); 9247 #endif 9248 MHD_mutex_destroy_chk_ (&daemon->new_connections_mutex); 9249 MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex); 9250 MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); 9251 goto free_and_fail; 9252 } 9253 } 9254 #endif 9255 #ifdef HTTPS_SUPPORT 9256 /* API promises to never use the password after initialization, 9257 so we additionally NULL it here to not deref a dangling pointer. */ 9258 daemon->https_key_password = NULL; 9259 #endif /* HTTPS_SUPPORT */ 9260 9261 return daemon; 9262 9263 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 9264 thread_failed: 9265 /* If no worker threads created, then shut down normally. Calling 9266 MHD_stop_daemon (as we do below) doesn't work here since it 9267 assumes a 0-sized thread pool means we had been in the default 9268 MHD_USE_INTERNAL_POLLING_THREAD mode. */ 9269 if (0 == i) 9270 { 9271 MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); 9272 if (NULL != daemon->worker_pool) 9273 free (daemon->worker_pool); 9274 goto free_and_fail; 9275 } 9276 9277 /* Shutdown worker threads we've already created. Pretend 9278 as though we had fully initialized our daemon, but 9279 with a smaller number of threads than had been 9280 requested. */ 9281 daemon->worker_pool_size = i; 9282 MHD_stop_daemon (daemon); 9283 return NULL; 9284 #endif 9285 9286 free_and_fail: 9287 /* clean up basic memory state in 'daemon' and return NULL to 9288 indicate failure */ 9289 #ifdef EPOLL_SUPPORT 9290 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) 9291 if (daemon->upgrade_fd_in_epoll) 9292 { 9293 if (0 != epoll_ctl (daemon->epoll_fd, 9294 EPOLL_CTL_DEL, 9295 daemon->epoll_upgrade_fd, 9296 NULL)) 9297 MHD_PANIC (_ ("Failed to remove FD from epoll set.\n")); 9298 daemon->upgrade_fd_in_epoll = false; 9299 } 9300 #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ 9301 if (-1 != daemon->epoll_fd) 9302 close (daemon->epoll_fd); 9303 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) 9304 if (-1 != daemon->epoll_upgrade_fd) 9305 close (daemon->epoll_upgrade_fd); 9306 #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ 9307 #endif /* EPOLL_SUPPORT */ 9308 #ifdef DAUTH_SUPPORT 9309 free (daemon->digest_auth_random_copy); 9310 free (daemon->nnc); 9311 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 9312 MHD_mutex_destroy_chk_ (&daemon->nnc_lock); 9313 #endif 9314 #endif 9315 #ifdef HTTPS_SUPPORT 9316 tls_cleanup_failed_start (daemon); 9317 #endif /* HTTPS_SUPPORT */ 9318 if (MHD_ITC_IS_VALID_ (daemon->itc)) 9319 MHD_itc_destroy_chk_ (daemon->itc); 9320 if (MHD_INVALID_SOCKET != daemon->listen_fd) 9321 (void) MHD_socket_close_ (daemon->listen_fd); 9322 free (daemon); 9323 return NULL; 9324 } 9325 9326 9327 /** 9328 * Close all connections for the daemon. 9329 * Must only be called when MHD_Daemon::shutdown was set to true. 9330 * @remark To be called only from thread that process 9331 * daemon's select()/poll()/etc. 9332 * 9333 * @param daemon daemon to close down 9334 */ 9335 static void 9336 close_all_connections (struct MHD_Daemon *daemon) 9337 { 9338 struct MHD_Connection *pos; 9339 const bool used_thr_p_c = MHD_D_IS_USING_THREAD_PER_CONN_ (daemon); 9340 #ifdef UPGRADE_SUPPORT 9341 const bool upg_allowed = (0 != (daemon->options & MHD_ALLOW_UPGRADE)); 9342 #endif /* UPGRADE_SUPPORT */ 9343 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) 9344 struct MHD_UpgradeResponseHandle *urh; 9345 struct MHD_UpgradeResponseHandle *urhn; 9346 const bool used_tls = (0 != (daemon->options & MHD_USE_TLS)); 9347 #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ 9348 9349 #ifdef MHD_USE_THREADS 9350 mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \ 9351 MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) || \ 9352 MHD_thread_handle_ID_is_current_thread_ (daemon->tid) ); 9353 mhd_assert (NULL == daemon->worker_pool); 9354 #endif /* MHD_USE_THREADS */ 9355 mhd_assert (daemon->shutdown); 9356 9357 #ifdef MHD_USE_THREADS 9358 /* Remove new connections that MHD_add_connection() queued and that were 9359 * never processed. This is not limited to daemons with an internal 9360 * polling thread: internal_add_connection() queues whenever the daemon 9361 * is thread-safe, which is every daemon that was not started with 9362 * MHD_USE_NO_THREAD_SAFETY, and new_connections_list_process_() 9363 * asserts the same condition. An application driving an external 9364 * event loop can therefore call MHD_add_connection() and then 9365 * MHD_stop_daemon() before the next MHD_run(), and this list is what 9366 * holds the connection at that point. */ 9367 MHD_mutex_lock_chk_ (&daemon->new_connections_mutex); 9368 while (NULL != (pos = daemon->new_connections_tail)) 9369 { 9370 mhd_assert (MHD_D_IS_THREAD_SAFE_ (daemon)); 9371 DLL_remove (daemon->new_connections_head, 9372 daemon->new_connections_tail, 9373 pos); 9374 new_connection_close_ (daemon, pos); 9375 } 9376 MHD_mutex_unlock_chk_ (&daemon->new_connections_mutex); 9377 #endif /* MHD_USE_THREADS */ 9378 9379 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) 9380 /* give upgraded HTTPS connections a chance to finish */ 9381 /* 'daemon->urh_head' is not used in thread-per-connection mode. */ 9382 for (urh = daemon->urh_tail; NULL != urh; urh = urhn) 9383 { 9384 mhd_assert (! used_thr_p_c); 9385 urhn = urh->prev; 9386 /* call generic forwarding function for passing data 9387 with chance to detect that application is done. */ 9388 process_urh (urh); 9389 MHD_connection_finish_forward_ (urh->connection); 9390 urh->clean_ready = true; 9391 /* Resuming will move connection to cleanup list. */ 9392 MHD_resume_connection (urh->connection); 9393 } 9394 #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ 9395 9396 /* Give suspended connections a chance to resume to avoid 9397 running into the check for there not being any suspended 9398 connections left in case of a tight race with a recently 9399 resumed connection. */ 9400 if (0 != (MHD_TEST_ALLOW_SUSPEND_RESUME & daemon->options)) 9401 { 9402 daemon->resuming = true; /* Force check for pending resume. */ 9403 resume_suspended_connections (daemon); 9404 } 9405 /* first, make sure all threads are aware of shutdown; need to 9406 traverse DLLs in peace... */ 9407 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 9408 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); 9409 #endif 9410 #ifdef UPGRADE_SUPPORT 9411 if (upg_allowed) 9412 { 9413 struct MHD_Connection *susp; 9414 9415 susp = daemon->suspended_connections_tail; 9416 while (NULL != susp) 9417 { 9418 if (NULL == susp->urh) /* "Upgraded" connection? */ 9419 MHD_PANIC (_ ("MHD_stop_daemon() called while we have " \ 9420 "suspended connections.\n")); 9421 #ifdef HTTPS_SUPPORT 9422 else if (used_tls && 9423 used_thr_p_c && 9424 (! susp->urh->clean_ready) ) 9425 shutdown (susp->urh->app.socket, 9426 SHUT_RDWR); /* Wake thread by shutdown of app socket. */ 9427 #endif /* HTTPS_SUPPORT */ 9428 else 9429 { 9430 #ifdef HAVE_MESSAGES 9431 if (! susp->urh->was_closed) 9432 MHD_DLOG (daemon, 9433 _ ("Initiated daemon shutdown while \"upgraded\" " \ 9434 "connection was not closed.\n")); 9435 #endif 9436 susp->urh->was_closed = true; 9437 /* If thread-per-connection is used, connection's thread 9438 * may still processing "upgrade" (exiting). */ 9439 if (! used_thr_p_c) 9440 MHD_connection_finish_forward_ (susp); 9441 /* Do not use MHD_resume_connection() as mutex is 9442 * already locked. */ 9443 susp->resuming = true; 9444 daemon->resuming = true; 9445 } 9446 susp = susp->prev; 9447 } 9448 } 9449 else /* This 'else' is combined with next 'if' */ 9450 #endif /* UPGRADE_SUPPORT */ 9451 if (NULL != daemon->suspended_connections_head) 9452 MHD_PANIC (_ ("MHD_stop_daemon() called while we have " \ 9453 "suspended connections.\n")); 9454 #if defined(UPGRADE_SUPPORT) && defined(HTTPS_SUPPORT) 9455 #ifdef MHD_USE_THREADS 9456 if (upg_allowed && used_tls && used_thr_p_c) 9457 { 9458 /* "Upgraded" threads may be running in parallel. Connection will not be 9459 * moved to the "cleanup list" until connection's thread finishes. 9460 * We must ensure that all "upgraded" connections are finished otherwise 9461 * connection may stay in "suspended" list and will not be cleaned. */ 9462 for (pos = daemon->suspended_connections_tail; NULL != pos; pos = pos->prev) 9463 { 9464 /* Any connection found here is "upgraded" connection, normal suspended 9465 * connections are already removed from this list. */ 9466 mhd_assert (NULL != pos->urh); 9467 if (! pos->thread_joined) 9468 { 9469 /* While "cleanup" list is not manipulated by "upgraded" 9470 * connection, "cleanup" mutex is required for call of 9471 * MHD_resume_connection() during finishing of "upgraded" 9472 * thread. */ 9473 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); 9474 if (! MHD_thread_handle_ID_join_thread_ (pos->tid)) 9475 MHD_PANIC (_ ("Failed to join a thread.\n")); 9476 pos->thread_joined = true; 9477 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); 9478 } 9479 } 9480 } 9481 #endif /* MHD_USE_THREADS */ 9482 #endif 9483 for (pos = daemon->connections_tail; NULL != pos; pos = pos->prev) 9484 { 9485 shutdown (pos->socket_fd, 9486 SHUT_RDWR); 9487 #ifdef MHD_WINSOCK_SOCKETS 9488 if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) && 9489 (MHD_ITC_IS_VALID_ (daemon->itc)) && 9490 (! MHD_itc_activate_ (daemon->itc, "e")) ) 9491 MHD_PANIC (_ ("Failed to signal shutdown via inter-thread " \ 9492 "communication channel.\n")); 9493 #endif 9494 } 9495 9496 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 9497 /* now, collect per-connection threads */ 9498 if (used_thr_p_c) 9499 { 9500 pos = daemon->connections_tail; 9501 while (NULL != pos) 9502 { 9503 if (! pos->thread_joined) 9504 { 9505 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); 9506 if (! MHD_thread_handle_ID_join_thread_ (pos->tid)) 9507 MHD_PANIC (_ ("Failed to join a thread.\n")); 9508 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex); 9509 pos->thread_joined = true; 9510 /* The thread may have concurrently modified the DLL, 9511 need to restart from the beginning */ 9512 pos = daemon->connections_tail; 9513 continue; 9514 } 9515 pos = pos->prev; 9516 } 9517 } 9518 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex); 9519 #endif 9520 9521 #ifdef UPGRADE_SUPPORT 9522 /* Finished threads with "upgraded" connections need to be moved 9523 * to cleanup list by resume_suspended_connections(). */ 9524 /* "Upgraded" connections that were not closed explicitly by 9525 * application should be moved to cleanup list too. */ 9526 if (upg_allowed) 9527 { 9528 daemon->resuming = true; /* Force check for pending resume. */ 9529 resume_suspended_connections (daemon); 9530 } 9531 #endif /* UPGRADE_SUPPORT */ 9532 9533 mhd_assert (NULL == daemon->suspended_connections_head); 9534 /* now that we're alone, move everyone to cleanup */ 9535 while (NULL != (pos = daemon->connections_tail)) 9536 { 9537 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 9538 if (MHD_D_IS_USING_THREAD_PER_CONN_ (daemon) && 9539 (! pos->thread_joined) ) 9540 MHD_PANIC (_ ("Failed to join a thread.\n")); 9541 #endif 9542 close_connection (pos); 9543 } 9544 MHD_cleanup_connections (daemon); 9545 } 9546 9547 9548 /** 9549 * Shutdown an HTTP daemon. 9550 * 9551 * @param daemon daemon to stop 9552 * @ingroup event 9553 */ 9554 _MHD_EXTERN void 9555 MHD_stop_daemon (struct MHD_Daemon *daemon) 9556 { 9557 MHD_socket fd; 9558 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 9559 unsigned int i; 9560 #endif 9561 9562 if (NULL == daemon) 9563 return; 9564 if ( (daemon->shutdown) && (NULL == daemon->master) ) 9565 MHD_PANIC (_ ("MHD_stop_daemon() was called twice.")); 9566 9567 mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ 9568 (NULL != daemon->worker_pool) || \ 9569 (MHD_thread_handle_ID_is_valid_handle_ (daemon->tid))); 9570 mhd_assert (((0 != (daemon->options & MHD_USE_SELECT_INTERNALLY)) && 9571 (NULL == daemon->worker_pool)) || \ 9572 (! MHD_thread_handle_ID_is_valid_handle_ (daemon->tid))); 9573 9574 /* Slave daemons must be stopped by master daemon. */ 9575 mhd_assert ( (NULL == daemon->master) || (daemon->shutdown) ); 9576 9577 daemon->shutdown = true; 9578 if (daemon->was_quiesced) 9579 fd = MHD_INVALID_SOCKET; /* Do not use FD if daemon was quiesced */ 9580 else 9581 fd = daemon->listen_fd; 9582 9583 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 9584 if (NULL != daemon->worker_pool) 9585 { /* Master daemon with worker pool. */ 9586 mhd_assert (1 < daemon->worker_pool_size); 9587 mhd_assert (MHD_D_IS_USING_THREADS_ (daemon)); 9588 9589 /* Let workers shutdown in parallel. */ 9590 for (i = 0; i < daemon->worker_pool_size; ++i) 9591 { 9592 daemon->worker_pool[i].shutdown = true; 9593 if (MHD_ITC_IS_VALID_ (daemon->worker_pool[i].itc)) 9594 { 9595 if (! MHD_itc_activate_ (daemon->worker_pool[i].itc, 9596 "e")) 9597 MHD_PANIC (_ ("Failed to signal shutdown via inter-thread " \ 9598 "communication channel.\n")); 9599 } 9600 else 9601 mhd_assert (MHD_INVALID_SOCKET != fd); 9602 } 9603 #ifdef HAVE_LISTEN_SHUTDOWN 9604 if (MHD_INVALID_SOCKET != fd) 9605 { 9606 (void) shutdown (fd, 9607 SHUT_RDWR); 9608 } 9609 #endif /* HAVE_LISTEN_SHUTDOWN */ 9610 for (i = 0; i < daemon->worker_pool_size; ++i) 9611 { 9612 MHD_stop_daemon (&daemon->worker_pool[i]); 9613 } 9614 free (daemon->worker_pool); 9615 mhd_assert (MHD_ITC_IS_INVALID_ (daemon->itc)); 9616 #ifdef EPOLL_SUPPORT 9617 mhd_assert (-1 == daemon->epoll_fd); 9618 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) 9619 mhd_assert (-1 == daemon->epoll_upgrade_fd); 9620 #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ 9621 #endif /* EPOLL_SUPPORT */ 9622 } 9623 else 9624 #endif 9625 { /* Worker daemon or single daemon. */ 9626 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 9627 if (MHD_D_IS_USING_THREADS_ (daemon)) 9628 { /* Worker daemon or single daemon with internal thread(s). */ 9629 mhd_assert (0 == daemon->worker_pool_size); 9630 /* Separate thread(s) is used for polling sockets. */ 9631 if (MHD_ITC_IS_VALID_ (daemon->itc)) 9632 { 9633 if (! MHD_itc_activate_ (daemon->itc, 9634 "e")) 9635 MHD_PANIC (_ ("Failed to signal shutdown via inter-thread " \ 9636 "communication channel.\n")); 9637 } 9638 else 9639 { 9640 #ifdef HAVE_LISTEN_SHUTDOWN 9641 if (MHD_INVALID_SOCKET != fd) 9642 { 9643 if (NULL == daemon->master) 9644 (void) shutdown (fd, 9645 SHUT_RDWR); 9646 } 9647 else 9648 #endif /* HAVE_LISTEN_SHUTDOWN */ 9649 mhd_assert (false); /* Should never happen */ 9650 } 9651 9652 if (! MHD_thread_handle_ID_join_thread_ (daemon->tid)) 9653 { 9654 MHD_PANIC (_ ("Failed to join a thread.\n")); 9655 } 9656 /* close_all_connections() was called in daemon thread. */ 9657 } 9658 else 9659 #endif 9660 { 9661 /* No internal threads are used for polling sockets. */ 9662 close_all_connections (daemon); 9663 } 9664 mhd_assert (NULL == daemon->connections_head); 9665 mhd_assert (NULL == daemon->cleanup_head); 9666 mhd_assert (NULL == daemon->suspended_connections_head); 9667 mhd_assert (NULL == daemon->new_connections_head); 9668 #if defined(UPGRADE_SUPPORT) && defined(HTTPS_SUPPORT) 9669 mhd_assert (NULL == daemon->urh_head); 9670 #endif /* UPGRADE_SUPPORT && HTTPS_SUPPORT */ 9671 9672 if (MHD_ITC_IS_VALID_ (daemon->itc)) 9673 MHD_itc_destroy_chk_ (daemon->itc); 9674 9675 #ifdef EPOLL_SUPPORT 9676 if (MHD_D_IS_USING_EPOLL_ (daemon) && 9677 (-1 != daemon->epoll_fd) ) 9678 MHD_socket_close_chk_ (daemon->epoll_fd); 9679 #if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT) 9680 if (MHD_D_IS_USING_EPOLL_ (daemon) && 9681 (-1 != daemon->epoll_upgrade_fd) ) 9682 MHD_socket_close_chk_ (daemon->epoll_upgrade_fd); 9683 #endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */ 9684 #endif /* EPOLL_SUPPORT */ 9685 9686 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 9687 MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex); 9688 MHD_mutex_destroy_chk_ (&daemon->epoll_listen_mutex); 9689 MHD_mutex_destroy_chk_ (&daemon->new_connections_mutex); 9690 #endif 9691 } 9692 9693 if (NULL == daemon->master) 9694 { /* Cleanup that should be done only one time in master/single daemon. 9695 * Do not perform this cleanup in worker daemons. */ 9696 9697 if (MHD_INVALID_SOCKET != fd) 9698 MHD_socket_close_chk_ (fd); 9699 9700 /* TLS clean up */ 9701 #ifdef HTTPS_SUPPORT 9702 if (daemon->have_dhparams) 9703 { 9704 gnutls_dh_params_deinit (daemon->https_mem_dhparams); 9705 daemon->have_dhparams = false; 9706 } 9707 if (0 != (daemon->options & MHD_USE_TLS)) 9708 { 9709 gnutls_priority_deinit (daemon->priority_cache); 9710 if (daemon->x509_cred) 9711 gnutls_certificate_free_credentials (daemon->x509_cred); 9712 if (daemon->psk_cred) 9713 gnutls_psk_free_server_credentials (daemon->psk_cred); 9714 } 9715 #endif /* HTTPS_SUPPORT */ 9716 9717 #ifdef DAUTH_SUPPORT 9718 free (daemon->digest_auth_random_copy); 9719 free (daemon->nnc); 9720 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 9721 MHD_mutex_destroy_chk_ (&daemon->nnc_lock); 9722 #endif 9723 #endif 9724 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 9725 MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex); 9726 #endif 9727 free (daemon); 9728 } 9729 } 9730 9731 9732 /** 9733 * Obtain information about the given daemon. 9734 * The returned pointer is invalidated with the next call of this function or 9735 * when the daemon is stopped. 9736 * 9737 * @param daemon what daemon to get information about 9738 * @param info_type what information is desired? 9739 * @param ... depends on @a info_type 9740 * @return NULL if this information is not available 9741 * (or if the @a info_type is unknown) 9742 * @ingroup specialized 9743 */ 9744 _MHD_EXTERN const union MHD_DaemonInfo * 9745 MHD_get_daemon_info (struct MHD_Daemon *daemon, 9746 enum MHD_DaemonInfoType info_type, 9747 ...) 9748 { 9749 if (NULL == daemon) 9750 return NULL; 9751 9752 mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \ 9753 (NULL != daemon->worker_pool) || \ 9754 (MHD_thread_handle_ID_is_valid_handle_ (daemon->tid))); 9755 mhd_assert (((0 != (daemon->options & MHD_USE_SELECT_INTERNALLY)) && 9756 (NULL == daemon->worker_pool)) || \ 9757 (! MHD_thread_handle_ID_is_valid_handle_ (daemon->tid))); 9758 9759 switch (info_type) 9760 { 9761 case MHD_DAEMON_INFO_KEY_SIZE: 9762 return NULL; /* no longer supported */ 9763 case MHD_DAEMON_INFO_MAC_KEY_SIZE: 9764 return NULL; /* no longer supported */ 9765 case MHD_DAEMON_INFO_LISTEN_FD: 9766 daemon->daemon_info_dummy_listen_fd.listen_fd = daemon->listen_fd; 9767 return &daemon->daemon_info_dummy_listen_fd; 9768 case MHD_DAEMON_INFO_EPOLL_FD: 9769 #ifdef EPOLL_SUPPORT 9770 daemon->daemon_info_dummy_epoll_fd.epoll_fd = daemon->epoll_fd; 9771 return &daemon->daemon_info_dummy_epoll_fd; 9772 #else /* ! EPOLL_SUPPORT */ 9773 return NULL; 9774 #endif /* ! EPOLL_SUPPORT */ 9775 case MHD_DAEMON_INFO_CURRENT_CONNECTIONS: 9776 if (! MHD_D_IS_THREAD_SAFE_ (daemon)) 9777 MHD_cleanup_connections (daemon); 9778 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 9779 else if (daemon->worker_pool) 9780 { 9781 unsigned int i; 9782 /* Collect the connection information stored in the workers. */ 9783 daemon->connections = 0; 9784 for (i = 0; i < daemon->worker_pool_size; i++) 9785 { 9786 /* FIXME: next line is thread-safe only if read is atomic. */ 9787 daemon->connections += daemon->worker_pool[i].connections; 9788 } 9789 } 9790 #endif 9791 daemon->daemon_info_dummy_num_connections.num_connections 9792 = daemon->connections; 9793 return &daemon->daemon_info_dummy_num_connections; 9794 case MHD_DAEMON_INFO_FLAGS: 9795 daemon->daemon_info_dummy_flags.flags = daemon->options; 9796 return &daemon->daemon_info_dummy_flags; 9797 case MHD_DAEMON_INFO_BIND_PORT: 9798 daemon->daemon_info_dummy_port.port = daemon->port; 9799 return &daemon->daemon_info_dummy_port; 9800 default: 9801 return NULL; 9802 } 9803 } 9804 9805 9806 /** 9807 * Obtain the version of this library 9808 * 9809 * @return static version string, e.g. "0.9.9" 9810 * @ingroup specialized 9811 */ 9812 _MHD_EXTERN const char * 9813 MHD_get_version (void) 9814 { 9815 #ifdef PACKAGE_VERSION 9816 return PACKAGE_VERSION; 9817 #else /* !PACKAGE_VERSION */ 9818 static char ver[12] = "\0\0\0\0\0\0\0\0\0\0\0"; 9819 if (0 == ver[0]) 9820 { 9821 int res = MHD_snprintf_ (ver, 9822 sizeof(ver), 9823 "%x.%x.%x", 9824 (int) (((uint32_t) MHD_VERSION >> 24) & 0xFF), 9825 (int) (((uint32_t) MHD_VERSION >> 16) & 0xFF), 9826 (int) (((uint32_t) MHD_VERSION >> 8) & 0xFF)); 9827 if ((0 >= res) || (sizeof(ver) <= res)) 9828 return "0.0.0"; /* Can't return real version */ 9829 } 9830 return ver; 9831 #endif /* !PACKAGE_VERSION */ 9832 } 9833 9834 9835 /** 9836 * Obtain the version of this library as a binary value. 9837 * 9838 * @return version binary value, e.g. "0x00090900" (#MHD_VERSION of 9839 * compiled MHD binary) 9840 * @note Available since #MHD_VERSION 0x00097601 9841 * @ingroup specialized 9842 */ 9843 _MHD_EXTERN uint32_t 9844 MHD_get_version_bin (void) 9845 { 9846 return (uint32_t) MHD_VERSION; 9847 } 9848 9849 9850 /** 9851 * Get information about supported MHD features. 9852 * Indicate that MHD was compiled with or without support for 9853 * particular feature. Some features require additional support 9854 * by kernel. Kernel support is not checked by this function. 9855 * 9856 * @param feature type of requested information 9857 * @return #MHD_YES if feature is supported by MHD, #MHD_NO if 9858 * feature is not supported or feature is unknown. 9859 * @ingroup specialized 9860 */ 9861 _MHD_EXTERN enum MHD_Result 9862 MHD_is_feature_supported (enum MHD_FEATURE feature) 9863 { 9864 switch (feature) 9865 { 9866 case MHD_FEATURE_MESSAGES: 9867 #ifdef HAVE_MESSAGES 9868 return MHD_YES; 9869 #else 9870 return MHD_NO; 9871 #endif 9872 case MHD_FEATURE_TLS: 9873 #ifdef HTTPS_SUPPORT 9874 return MHD_YES; 9875 #else /* ! HTTPS_SUPPORT */ 9876 return MHD_NO; 9877 #endif /* ! HTTPS_SUPPORT */ 9878 case MHD_FEATURE_HTTPS_CERT_CALLBACK: 9879 #if defined(HTTPS_SUPPORT) && GNUTLS_VERSION_MAJOR >= 3 9880 return MHD_YES; 9881 #else /* !HTTPS_SUPPORT || GNUTLS_VERSION_MAJOR < 3 */ 9882 return MHD_NO; 9883 #endif /* !HTTPS_SUPPORT || GNUTLS_VERSION_MAJOR < 3 */ 9884 case MHD_FEATURE_HTTPS_CERT_CALLBACK2: 9885 #if defined(HTTPS_SUPPORT) && GNUTLS_VERSION_NUMBER >= 0x030603 9886 return MHD_YES; 9887 #else /* !HTTPS_SUPPORT || GNUTLS_VERSION_NUMBER < 0x030603 */ 9888 return MHD_NO; 9889 #endif /* !HTTPS_SUPPORT || GNUTLS_VERSION_NUMBER < 0x030603 */ 9890 case MHD_FEATURE_IPv6: 9891 #ifdef HAVE_INET6 9892 return MHD_YES; 9893 #else 9894 return MHD_NO; 9895 #endif 9896 case MHD_FEATURE_IPv6_ONLY: 9897 #if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY) 9898 return MHD_YES; 9899 #else 9900 return MHD_NO; 9901 #endif 9902 case MHD_FEATURE_POLL: 9903 #ifdef HAVE_POLL 9904 return MHD_YES; 9905 #else 9906 return MHD_NO; 9907 #endif 9908 case MHD_FEATURE_EPOLL: 9909 #ifdef EPOLL_SUPPORT 9910 return MHD_YES; 9911 #else 9912 return MHD_NO; 9913 #endif 9914 case MHD_FEATURE_SHUTDOWN_LISTEN_SOCKET: 9915 #ifdef HAVE_LISTEN_SHUTDOWN 9916 return MHD_YES; 9917 #else 9918 return MHD_NO; 9919 #endif 9920 case MHD_FEATURE_SOCKETPAIR: 9921 #ifdef _MHD_ITC_SOCKETPAIR 9922 return MHD_YES; 9923 #else 9924 return MHD_NO; 9925 #endif 9926 case MHD_FEATURE_TCP_FASTOPEN: 9927 #ifdef TCP_FASTOPEN 9928 return MHD_YES; 9929 #else 9930 return MHD_NO; 9931 #endif 9932 case MHD_FEATURE_BASIC_AUTH: 9933 #ifdef BAUTH_SUPPORT 9934 return MHD_YES; 9935 #else 9936 return MHD_NO; 9937 #endif 9938 case MHD_FEATURE_DIGEST_AUTH: 9939 #ifdef DAUTH_SUPPORT 9940 return MHD_YES; 9941 #else 9942 return MHD_NO; 9943 #endif 9944 case MHD_FEATURE_POSTPROCESSOR: 9945 #ifdef HAVE_POSTPROCESSOR 9946 return MHD_YES; 9947 #else 9948 return MHD_NO; 9949 #endif 9950 case MHD_FEATURE_HTTPS_KEY_PASSWORD: 9951 #if defined(HTTPS_SUPPORT) && GNUTLS_VERSION_NUMBER >= 0x030111 9952 return MHD_YES; 9953 #else /* !HTTPS_SUPPORT || GNUTLS_VERSION_NUMBER < 0x030111 */ 9954 return MHD_NO; 9955 #endif /* !HTTPS_SUPPORT || GNUTLS_VERSION_NUMBER < 0x030111 */ 9956 case MHD_FEATURE_LARGE_FILE: 9957 #if defined(HAVE_PREAD64) || defined(_WIN32) 9958 return MHD_YES; 9959 #elif defined(HAVE_PREAD) 9960 return (sizeof(uint64_t) > sizeof(off_t)) ? MHD_NO : MHD_YES; 9961 #elif defined(HAVE_LSEEK64) 9962 return MHD_YES; 9963 #else 9964 return (sizeof(uint64_t) > sizeof(off_t)) ? MHD_NO : MHD_YES; 9965 #endif 9966 case MHD_FEATURE_THREAD_NAMES: 9967 #if defined(MHD_USE_THREAD_NAME_) 9968 return MHD_YES; 9969 #else 9970 return MHD_NO; 9971 #endif 9972 case MHD_FEATURE_UPGRADE: 9973 #if defined(UPGRADE_SUPPORT) 9974 return MHD_YES; 9975 #else 9976 return MHD_NO; 9977 #endif 9978 case MHD_FEATURE_RESPONSES_SHARED_FD: 9979 #if defined(HAVE_PREAD64) || defined(HAVE_PREAD) || defined(_WIN32) 9980 return MHD_YES; 9981 #else 9982 return MHD_NO; 9983 #endif 9984 case MHD_FEATURE_AUTODETECT_BIND_PORT: 9985 #ifdef MHD_USE_GETSOCKNAME 9986 return MHD_YES; 9987 #else 9988 return MHD_NO; 9989 #endif 9990 case MHD_FEATURE_AUTOSUPPRESS_SIGPIPE: 9991 #if defined(MHD_SEND_SPIPE_SUPPRESS_POSSIBLE) || \ 9992 ! defined(MHD_SEND_SPIPE_SUPPRESS_NEEDED) 9993 return MHD_YES; 9994 #else 9995 return MHD_NO; 9996 #endif 9997 case MHD_FEATURE_SENDFILE: 9998 #ifdef _MHD_HAVE_SENDFILE 9999 return MHD_YES; 10000 #else 10001 return MHD_NO; 10002 #endif 10003 case MHD_FEATURE_THREADS: 10004 #if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS) 10005 return MHD_YES; 10006 #else 10007 return MHD_NO; 10008 #endif 10009 case MHD_FEATURE_COOKIE_PARSING: 10010 #if defined(COOKIE_SUPPORT) 10011 return MHD_YES; 10012 #else 10013 return MHD_NO; 10014 #endif 10015 case MHD_FEATURE_DIGEST_AUTH_RFC2069: 10016 #ifdef DAUTH_SUPPORT 10017 return MHD_YES; 10018 #else 10019 return MHD_NO; 10020 #endif 10021 case MHD_FEATURE_DIGEST_AUTH_MD5: 10022 #if defined(DAUTH_SUPPORT) && defined(MHD_MD5_SUPPORT) 10023 return MHD_YES; 10024 #else 10025 return MHD_NO; 10026 #endif 10027 case MHD_FEATURE_DIGEST_AUTH_SHA256: 10028 #if defined(DAUTH_SUPPORT) && defined(MHD_SHA256_SUPPORT) 10029 return MHD_YES; 10030 #else 10031 return MHD_NO; 10032 #endif 10033 case MHD_FEATURE_DIGEST_AUTH_SHA512_256: 10034 #if defined(DAUTH_SUPPORT) && defined(MHD_SHA512_256_SUPPORT) 10035 return MHD_YES; 10036 #else 10037 return MHD_NO; 10038 #endif 10039 case MHD_FEATURE_DIGEST_AUTH_AUTH_INT: 10040 #ifdef DAUTH_SUPPORT 10041 return MHD_NO; 10042 #else 10043 return MHD_NO; 10044 #endif 10045 case MHD_FEATURE_DIGEST_AUTH_ALGO_SESSION: 10046 #ifdef DAUTH_SUPPORT 10047 return MHD_NO; 10048 #else 10049 return MHD_NO; 10050 #endif 10051 case MHD_FEATURE_DIGEST_AUTH_USERHASH: 10052 #ifdef DAUTH_SUPPORT 10053 return MHD_YES; 10054 #else 10055 return MHD_NO; 10056 #endif 10057 case MHD_FEATURE_EXTERN_HASH: 10058 #if defined(MHD_MD5_TLSLIB) || defined(MHD_SHA256_TLSLIB) 10059 return MHD_YES; 10060 #else 10061 return MHD_NO; 10062 #endif 10063 case MHD_FEATURE_DEBUG_BUILD: 10064 #ifdef _DEBUG 10065 return MHD_YES; 10066 #else 10067 return MHD_NO; 10068 #endif 10069 case MHD_FEATURE_FLEXIBLE_FD_SETSIZE: 10070 #ifdef HAS_FD_SETSIZE_OVERRIDABLE 10071 return MHD_YES; 10072 #else /* ! HAS_FD_SETSIZE_OVERRIDABLE */ 10073 return MHD_NO; 10074 #endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */ 10075 10076 default: 10077 break; 10078 } 10079 return MHD_NO; 10080 } 10081 10082 10083 #ifdef MHD_HTTPS_REQUIRE_GCRYPT 10084 #if defined(HTTPS_SUPPORT) && GCRYPT_VERSION_NUMBER < 0x010600 10085 #if defined(MHD_USE_POSIX_THREADS) 10086 GCRY_THREAD_OPTION_PTHREAD_IMPL; 10087 #elif defined(MHD_W32_MUTEX_) 10088 10089 static int 10090 gcry_w32_mutex_init (void **ppmtx) 10091 { 10092 *ppmtx = malloc (sizeof (MHD_mutex_)); 10093 10094 if (NULL == *ppmtx) 10095 return ENOMEM; 10096 if (! MHD_mutex_init_ ((MHD_mutex_ *) *ppmtx)) 10097 { 10098 free (*ppmtx); 10099 *ppmtx = NULL; 10100 return EPERM; 10101 } 10102 10103 return 0; 10104 } 10105 10106 10107 static int 10108 gcry_w32_mutex_destroy (void **ppmtx) 10109 { 10110 int res = (MHD_mutex_destroy_ ((MHD_mutex_ *) *ppmtx)) ? 0 : EINVAL; 10111 free (*ppmtx); 10112 return res; 10113 } 10114 10115 10116 static int 10117 gcry_w32_mutex_lock (void **ppmtx) 10118 { 10119 return MHD_mutex_lock_ ((MHD_mutex_ *) *ppmtx) ? 0 : EINVAL; 10120 } 10121 10122 10123 static int 10124 gcry_w32_mutex_unlock (void **ppmtx) 10125 { 10126 return MHD_mutex_unlock_ ((MHD_mutex_ *) *ppmtx) ? 0 : EINVAL; 10127 } 10128 10129 10130 static struct gcry_thread_cbs gcry_threads_w32 = { 10131 (GCRY_THREAD_OPTION_USER | (GCRY_THREAD_OPTION_VERSION << 8)), 10132 NULL, gcry_w32_mutex_init, gcry_w32_mutex_destroy, 10133 gcry_w32_mutex_lock, gcry_w32_mutex_unlock, 10134 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL 10135 }; 10136 10137 #endif /* defined(MHD_W32_MUTEX_) */ 10138 #endif /* HTTPS_SUPPORT && GCRYPT_VERSION_NUMBER < 0x010600 */ 10139 #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ 10140 10141 /** 10142 * Initialize do setup work. 10143 */ 10144 void 10145 MHD_init (void) 10146 { 10147 #if defined(MHD_WINSOCK_SOCKETS) 10148 WSADATA wsd; 10149 #endif /* MHD_WINSOCK_SOCKETS */ 10150 10151 MHD_set_panic_func (NULL, NULL); 10152 10153 #if defined(MHD_WINSOCK_SOCKETS) 10154 if (0 != WSAStartup (MAKEWORD (2, 2), &wsd)) 10155 MHD_PANIC (_ ("Failed to initialize winsock.\n")); 10156 if ((2 != LOBYTE (wsd.wVersion)) && (2 != HIBYTE (wsd.wVersion))) 10157 MHD_PANIC (_ ("Winsock version 2.2 is not available.\n")); 10158 #endif /* MHD_WINSOCK_SOCKETS */ 10159 #ifdef HTTPS_SUPPORT 10160 #ifdef MHD_HTTPS_REQUIRE_GCRYPT 10161 #if GCRYPT_VERSION_NUMBER < 0x010600 10162 #if GNUTLS_VERSION_NUMBER <= 0x020b00 10163 #if defined(MHD_USE_POSIX_THREADS) 10164 if (0 != gcry_control (GCRYCTL_SET_THREAD_CBS, 10165 &gcry_threads_pthread)) 10166 MHD_PANIC (_ ("Failed to initialise multithreading in libgcrypt.\n")); 10167 #elif defined(MHD_W32_MUTEX_) 10168 if (0 != gcry_control (GCRYCTL_SET_THREAD_CBS, 10169 &gcry_threads_w32)) 10170 MHD_PANIC (_ ("Failed to initialise multithreading in libgcrypt.\n")); 10171 #endif /* defined(MHD_W32_MUTEX_) */ 10172 #endif /* GNUTLS_VERSION_NUMBER <= 0x020b00 */ 10173 gcry_check_version (NULL); 10174 #else 10175 if (NULL == gcry_check_version ("1.6.0")) 10176 MHD_PANIC (_ ("libgcrypt is too old. MHD was compiled for " \ 10177 "libgcrypt 1.6.0 or newer.\n")); 10178 #endif 10179 #endif /* MHD_HTTPS_REQUIRE_GCRYPT */ 10180 gnutls_global_init (); 10181 #endif /* HTTPS_SUPPORT */ 10182 MHD_monotonic_sec_counter_init (); 10183 MHD_send_init_static_vars_ (); 10184 MHD_init_mem_pools_ (); 10185 /* Check whether sizes were correctly detected by configure */ 10186 #ifdef _DEBUG 10187 if (1) 10188 { 10189 struct timeval tv; 10190 mhd_assert (sizeof(tv.tv_sec) == SIZEOF_STRUCT_TIMEVAL_TV_SEC); 10191 } 10192 #endif /* _DEBUG */ 10193 mhd_assert (sizeof(uint64_t) == SIZEOF_UINT64_T); 10194 } 10195 10196 10197 void 10198 MHD_fini (void) 10199 { 10200 #ifdef HTTPS_SUPPORT 10201 gnutls_global_deinit (); 10202 #endif /* HTTPS_SUPPORT */ 10203 #if defined(MHD_WINSOCK_SOCKETS) 10204 WSACleanup (); 10205 #endif /* MHD_WINSOCK_SOCKETS */ 10206 MHD_monotonic_sec_counter_finish (); 10207 } 10208 10209 10210 #ifdef _AUTOINIT_FUNCS_ARE_SUPPORTED 10211 _SET_INIT_AND_DEINIT_FUNCS (MHD_init, MHD_fini); 10212 #endif /* _AUTOINIT_FUNCS_ARE_SUPPORTED */ 10213 10214 /* end of daemon.c */