GNU libmicrohttpd 1.0.11
Loading...
Searching...
No Matches
daemon.c
Go to the documentation of this file.
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
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
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
88#define MHD_POOL_SIZE_DEFAULT (32 * 1024)
89
90
91/* Forward declarations. */
92
93
97void
98MHD_init (void);
99
103void
104MHD_fini (void);
105
114static void
115close_all_connections (struct MHD_Daemon *daemon);
116
117#ifdef EPOLL_SUPPORT
118
128static enum MHD_Result
129MHD_epoll (struct MHD_Daemon *daemon,
130 int32_t millisec);
131
132#endif /* EPOLL_SUPPORT */
133
134#ifdef _AUTOINIT_FUNCS_ARE_SUPPORTED
139#define MHD_check_global_init_() (void) 0
140#else /* ! _AUTOINIT_FUNCS_ARE_SUPPORTED */
144volatile 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_
151MHD_MUTEX_STATIC_DEFN_INIT_ (global_init_mutex_);
152#endif /* MHD_MUTEX_STATIC_DEFN_INIT_ */
153#endif
154
155
160void
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
184static void
185MHD_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
212_MHD_EXTERN void
213MHD_free (void *ptr)
214{
215 free (ptr);
216}
217
218
222struct MHD_IPCount
223{
227 int family;
228
232 union
233 {
237 struct in_addr ipv4;
238#ifdef HAVE_INET6
242 struct in6_addr ipv6;
243#endif
244 } addr;
245
249 unsigned int count;
250};
251
252
258static void
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
275static void
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
296static int
297MHD_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
315static enum MHD_Result
316MHD_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
368static enum MHD_Result
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,
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
436static void
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,
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,
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
493static int
494MHD_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
622static int
623MHD_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
664static void
665tls_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
727MHD_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)
762static bool
763urh_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
848static void
849urh_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)
861 urh->mhd.celi &= (~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_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
921static void
922urh_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
962static void
963urh_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
978static void
979urh_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)
985 urh->mhd.celi &= (~((enum MHD_EpollState) MHD_EPOLL_STATE_READ_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))
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))
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
1025static enum MHD_Result
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
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 {
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;
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;
1119 if ( (NULL == except_fd_set) ||
1121 except_fd_set,
1122 max_fd,
1123 fd_setsize))
1124 result = MHD_NO;
1125 break;
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;
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
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
1331static enum MHD_Result
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)) || \
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)) || \
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. */
1403 write_ready)
1404 {
1406 ret = MHD_connection_handle_idle (con);
1407 states_info_processed = true;
1408 }
1409 }
1410 else
1411 {
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 {
1435 {
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. */
1445 {
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) &&
1461 {
1463 con->daemon->data_already_pending = true;
1464#ifdef HTTPS_SUPPORT
1465 else if ( (con->tls_read_ready) &&
1467 con->daemon->data_already_pending = true;
1468#endif /* HTTPS_SUPPORT */
1469 }
1470 return ret;
1471}
1472
1473
1474#ifdef UPGRADE_SUPPORT
1482static void
1483cleanup_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)
1519static void
1520process_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 */
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. */
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)) &&
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)) &&
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#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
1851#ifdef UPGRADE_SUPPORT
1860static void
1861thread_main_connection_upgrade (struct MHD_Connection *con)
1862{
1863#ifdef HTTPS_SUPPORT
1864 struct MHD_UpgradeResponseHandle *urh = con->urh;
1865 struct MHD_Daemon *daemon = con->daemon;
1866
1867 mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \
1869 /* Here, we need to bi-directionally forward
1870 until the application tells us that it is done
1871 with the socket; */
1872 if ( (0 != (daemon->options & MHD_USE_TLS)) &&
1873 MHD_D_IS_USING_SELECT_ (daemon))
1874 {
1875 while ( (0 != urh->in_buffer_size) ||
1876 (0 != urh->out_buffer_size) ||
1877 (0 != urh->in_buffer_used) ||
1878 (0 != urh->out_buffer_used) )
1879 {
1880 /* use select */
1881 fd_set rs;
1882 fd_set ws;
1883 fd_set es;
1884 MHD_socket max_fd;
1885 int num_ready;
1886 bool result;
1887
1888 FD_ZERO (&rs);
1889 FD_ZERO (&ws);
1890 FD_ZERO (&es);
1891 max_fd = MHD_INVALID_SOCKET;
1892 result = urh_to_fdset (urh,
1893 &rs,
1894 &ws,
1895 &es,
1896 &max_fd,
1897 FD_SETSIZE);
1898 if (! result)
1899 {
1900#ifdef HAVE_MESSAGES
1901 MHD_DLOG (con->daemon,
1902 _ ("Error preparing select.\n"));
1903#endif
1904 break;
1905 }
1906 /* FIXME: does this check really needed? */
1907 if (MHD_INVALID_SOCKET != max_fd)
1908 {
1909 struct timeval *tvp;
1910 struct timeval tv;
1911 if (((con->tls_read_ready) &&
1912 (urh->in_buffer_used < urh->in_buffer_size)) ||
1913 (daemon->shutdown))
1914 { /* No need to wait if incoming data is already pending in TLS buffers. */
1915 tv.tv_sec = 0;
1916 tv.tv_usec = 0;
1917 tvp = &tv;
1918 }
1919 else
1920 tvp = NULL;
1921 num_ready = MHD_SYS_select_ (max_fd + 1,
1922 &rs,
1923 &ws,
1924 &es,
1925 tvp);
1926 }
1927 else
1928 num_ready = 0;
1929 if (num_ready < 0)
1930 {
1931 const int err = MHD_socket_get_error_ ();
1932
1933 if (MHD_SCKT_ERR_IS_EINTR_ (err))
1934 continue;
1935#ifdef HAVE_MESSAGES
1936 MHD_DLOG (con->daemon,
1937 _ ("Error during select (%d): `%s'\n"),
1938 err,
1939 MHD_socket_strerr_ (err));
1940#endif
1941 break;
1942 }
1943 urh_from_fdset (urh,
1944 &rs,
1945 &ws,
1946 &es,
1947 (int) FD_SETSIZE);
1948 process_urh (urh);
1949 }
1950 }
1951#ifdef HAVE_POLL
1952 else if (0 != (daemon->options & MHD_USE_TLS))
1953 {
1954 /* use poll() */
1955 struct pollfd p[2];
1956 memset (p,
1957 0,
1958 sizeof (p));
1959 p[0].fd = urh->connection->socket_fd;
1960 p[1].fd = urh->mhd.socket;
1961
1962 while ( (0 != urh->in_buffer_size) ||
1963 (0 != urh->out_buffer_size) ||
1964 (0 != urh->in_buffer_used) ||
1965 (0 != urh->out_buffer_used) )
1966 {
1967 int timeout;
1968
1969 urh_update_pollfd (urh, p);
1970
1971 if (((con->tls_read_ready) &&
1972 (urh->in_buffer_used < urh->in_buffer_size)) ||
1973 (daemon->shutdown))
1974 timeout = 0; /* No need to wait if incoming data is already pending in TLS buffers. */
1975 else
1976 timeout = -1;
1977
1978 if (MHD_sys_poll_ (p,
1979 2,
1980 timeout) < 0)
1981 {
1982 const int err = MHD_socket_get_error_ ();
1983
1984 if (MHD_SCKT_ERR_IS_EINTR_ (err))
1985 continue;
1986#ifdef HAVE_MESSAGES
1987 MHD_DLOG (con->daemon,
1988 _ ("Error during poll: `%s'\n"),
1989 MHD_socket_strerr_ (err));
1990#endif
1991 break;
1992 }
1993 urh_from_pollfd (urh,
1994 p);
1995 process_urh (urh);
1996 }
1997 }
1998 /* end POLL */
1999#endif
2000 /* end HTTPS */
2001#endif /* HTTPS_SUPPORT */
2002 /* TLS forwarding was finished. Cleanup socketpair. */
2004 /* Do not set 'urh->clean_ready' yet as 'urh' will be used
2005 * in connection thread for a little while. */
2006}
2007
2008
2009#endif /* UPGRADE_SUPPORT */
2010
2011
2019static uint64_t
2020connection_get_wait (struct MHD_Connection *c)
2021{
2022 const uint64_t now = MHD_monotonic_msec_counter ();
2023 const uint64_t since_actv = now - c->last_activity;
2024 const uint64_t timeout = c->connection_timeout_ms;
2025 uint64_t mseconds_left;
2026
2027 mhd_assert (0 != timeout);
2028 /* Keep the next lines in sync with #connection_check_timedout() to avoid
2029 * undesired side-effects like busy-waiting. */
2030 if (timeout < since_actv)
2031 {
2032 if (UINT64_MAX / 2 < since_actv)
2033 {
2034 const uint64_t jump_back = c->last_activity - now;
2035 /* Very unlikely that it is more than quarter-million years pause.
2036 * More likely that system clock jumps back. */
2037 if (5000 >= jump_back)
2038 { /* Jump back is less than 5 seconds, try to recover. */
2039 return 100; /* Set wait time to 0.1 seconds */
2040 }
2041 /* Too large jump back */
2042 }
2043 return 0; /* Connection has timed out */
2044 }
2045 else if (since_actv == timeout)
2046 {
2047 /* Exact match for timeout and time from last activity.
2048 * Maybe this is just a precise match or this happens because the timer
2049 * resolution is too low.
2050 * Set wait time to 0.1 seconds to avoid busy-waiting with low
2051 * timer resolution as connection is not timed-out yet. */
2052 return 100;
2053 }
2054 mseconds_left = timeout - since_actv;
2055
2056 return mseconds_left;
2057}
2058
2059
2074static void
2075resume_connection_own_thread_ (struct MHD_Connection *connection)
2076{
2077 struct MHD_Daemon *const daemon = connection->daemon;
2078
2080 mhd_assert (! MHD_D_IS_USING_EPOLL_ (daemon));
2081#ifdef UPGRADE_SUPPORT
2082 mhd_assert (NULL == connection->urh);
2083#endif /* UPGRADE_SUPPORT */
2084#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
2085 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
2086#endif
2087 mhd_assert (connection->suspended);
2088 mhd_assert (connection->resuming);
2091 connection);
2092 connection->suspended = false;
2094 daemon->connections_tail,
2095 connection);
2096 connection->resuming = false;
2097#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
2098 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
2099#endif
2100 /* Drop the notification that led here, as well as any notification
2101 left over from a resume that was undone by a suspend before this
2102 thread got to see it. */
2103 MHD_itc_clear_ (connection->resume_itc);
2104}
2105
2106
2114static MHD_THRD_RTRN_TYPE_ MHD_THRD_CALL_SPEC_
2115thread_main_handle_connection (void *data)
2116{
2117 struct MHD_Connection *con = data;
2118 struct MHD_Daemon *daemon = con->daemon;
2119 int num_ready;
2120 fd_set rs;
2121 fd_set ws;
2122 fd_set es;
2123 MHD_socket maxsock;
2124#ifdef WINDOWS
2125#ifdef HAVE_POLL
2126 unsigned int extra_slot;
2127#endif /* HAVE_POLL */
2128#define EXTRA_SLOTS 1
2129#else /* !WINDOWS */
2130#define EXTRA_SLOTS 0
2131#endif /* !WINDOWS */
2132#ifdef HAVE_POLL
2133 struct pollfd p[1 + EXTRA_SLOTS];
2134#endif
2135#undef EXTRA_SLOTS
2136#ifdef HAVE_POLL
2137 const bool use_poll = MHD_D_IS_USING_POLL_ (daemon);
2138#else /* ! HAVE_POLL */
2139 const bool use_poll = 0;
2140#endif /* ! HAVE_POLL */
2141 bool was_suspended = false;
2143
2144 while ( (! daemon->shutdown) &&
2145 (MHD_CONNECTION_CLOSED != con->state) )
2146 {
2147 bool use_zero_timeout;
2148#ifdef UPGRADE_SUPPORT
2149 struct MHD_UpgradeResponseHandle *const urh = con->urh;
2150#else /* ! UPGRADE_SUPPORT */
2151 static const void *const urh = NULL;
2152#endif /* ! UPGRADE_SUPPORT */
2153
2154 if ( (con->suspended) &&
2155 (NULL == urh) )
2156 {
2157 /* Connection was suspended, wait for resume. */
2158 was_suspended = true;
2159 if (con->resuming)
2160 {
2161 /* The application resumed this connection. Complete the resume
2162 right here: this thread is the only one that handles this
2163 connection, and doing it here is what keeps the wake-up below
2164 free of lost-notification races. */
2165 resume_connection_own_thread_ (con);
2166 continue;
2167 }
2168 mhd_assert (MHD_ITC_IS_VALID_ (con->resume_itc));
2169 if (! use_poll)
2170 {
2171 FD_ZERO (&rs);
2172 if (! MHD_add_to_fd_set_ (MHD_itc_r_fd_ (con->resume_itc),
2173 &rs,
2174 NULL,
2175 FD_SETSIZE))
2176 {
2177 #ifdef HAVE_MESSAGES
2178 MHD_DLOG (con->daemon,
2179 _ ("Failed to add FD to fd_set.\n"));
2180 #endif
2181 goto exit;
2182 }
2183 if (0 > MHD_SYS_select_ (MHD_itc_r_fd_ (con->resume_itc) + 1,
2184 &rs,
2185 NULL,
2186 NULL,
2187 NULL))
2188 {
2189 const int err = MHD_socket_get_error_ ();
2190
2191 if (MHD_SCKT_ERR_IS_EINTR_ (err))
2192 continue;
2193#ifdef HAVE_MESSAGES
2194 MHD_DLOG (con->daemon,
2195 _ ("Error during select (%d): `%s'\n"),
2196 err,
2197 MHD_socket_strerr_ (err));
2198#endif
2199 break;
2200 }
2201 }
2202#ifdef HAVE_POLL
2203 else /* use_poll */
2204 {
2205 p[0].events = POLLIN;
2206 p[0].fd = MHD_itc_r_fd_ (con->resume_itc);
2207 p[0].revents = 0;
2208 if (0 > MHD_sys_poll_ (p,
2209 1,
2210 -1))
2211 {
2213 continue;
2214#ifdef HAVE_MESSAGES
2215 MHD_DLOG (con->daemon,
2216 _ ("Error during poll: `%s'\n"),
2218#endif
2219 break;
2220 }
2221 }
2222#endif /* HAVE_POLL */
2223 MHD_itc_clear_ (con->resume_itc);
2224 continue; /* Check again for resume. */
2225 } /* End of "suspended" branch. */
2226
2227 if (was_suspended)
2228 {
2229 MHD_update_last_activity_ (con); /* Reset timeout timer. */
2230 /* Process response queued during suspend and update states. */
2232 was_suspended = false;
2233 }
2234
2235 use_zero_timeout =
2237#ifdef HTTPS_SUPPORT
2238 || ( (con->tls_read_ready) &&
2240#endif /* HTTPS_SUPPORT */
2241 );
2242 if (! use_poll)
2243 {
2244 /* use select */
2245 bool err_state = false;
2246 struct timeval tv;
2247 struct timeval *tvp;
2248 if (use_zero_timeout)
2249 {
2250 tv.tv_sec = 0;
2251 tv.tv_usec = 0;
2252 tvp = &tv;
2253 }
2254 else if (con->connection_timeout_ms > 0)
2255 {
2256 const uint64_t mseconds_left = connection_get_wait (con);
2257#if (SIZEOF_UINT64_T - 2) >= SIZEOF_STRUCT_TIMEVAL_TV_SEC
2258 if (mseconds_left / 1000 > TIMEVAL_TV_SEC_MAX)
2259 tv.tv_sec = TIMEVAL_TV_SEC_MAX;
2260 else
2261#endif /* (SIZEOF_UINT64_T - 2) >= SIZEOF_STRUCT_TIMEVAL_TV_SEC */
2262 tv.tv_sec = (_MHD_TIMEVAL_TV_SEC_TYPE) mseconds_left / 1000;
2263
2264 tv.tv_usec = ((uint16_t) (mseconds_left % 1000)) * ((int32_t) 1000);
2265 tvp = &tv;
2266 }
2267 else
2268 tvp = NULL;
2269
2270 FD_ZERO (&rs);
2271 FD_ZERO (&ws);
2272 FD_ZERO (&es);
2273 maxsock = MHD_INVALID_SOCKET;
2274 switch (con->event_loop_info)
2275 {
2278 if (! MHD_add_to_fd_set_ (con->socket_fd,
2279 &rs,
2280 &maxsock,
2281 FD_SETSIZE))
2282 err_state = true;
2283 break;
2285 if (! MHD_add_to_fd_set_ (con->socket_fd,
2286 &ws,
2287 &maxsock,
2288 FD_SETSIZE))
2289 err_state = true;
2290 break;
2292 if (! MHD_add_to_fd_set_ (con->socket_fd,
2293 &es,
2294 &maxsock,
2295 FD_SETSIZE))
2296 err_state = true;
2297 break;
2299 /* how did we get here!? */
2300 goto exit;
2301 }
2302#ifdef WINDOWS
2303 if (MHD_ITC_IS_VALID_ (daemon->itc) )
2304 {
2305 if (! MHD_add_to_fd_set_ (MHD_itc_r_fd_ (daemon->itc),
2306 &rs,
2307 &maxsock,
2308 FD_SETSIZE))
2309 err_state = 1;
2310 }
2311#endif
2312 if (err_state)
2313 {
2314#ifdef HAVE_MESSAGES
2315 MHD_DLOG (con->daemon,
2316 _ ("Failed to add FD to fd_set.\n"));
2317#endif
2318 goto exit;
2319 }
2320
2321 num_ready = MHD_SYS_select_ (maxsock + 1,
2322 &rs,
2323 &ws,
2324 &es,
2325 tvp);
2326 if (num_ready < 0)
2327 {
2328 const int err = MHD_socket_get_error_ ();
2329
2330 if (MHD_SCKT_ERR_IS_EINTR_ (err))
2331 continue;
2332#ifdef HAVE_MESSAGES
2333 MHD_DLOG (con->daemon,
2334 _ ("Error during select (%d): `%s'\n"),
2335 err,
2336 MHD_socket_strerr_ (err));
2337#endif
2338 break;
2339 }
2340#ifdef WINDOWS
2341 /* Clear ITC before other processing so additional
2342 * signals will trigger select() again */
2343 if ( (MHD_ITC_IS_VALID_ (daemon->itc)) &&
2344 (FD_ISSET (MHD_itc_r_fd_ (daemon->itc),
2345 &rs)) )
2346 MHD_itc_clear_ (daemon->itc);
2347#endif
2348 if (MHD_NO ==
2349 call_handlers (con,
2350 FD_ISSET (con->socket_fd,
2351 &rs),
2352 FD_ISSET (con->socket_fd,
2353 &ws),
2354 FD_ISSET (con->socket_fd,
2355 &es)) )
2356 goto exit;
2357 }
2358#ifdef HAVE_POLL
2359 else
2360 {
2361 int timeout_val;
2362 /* use poll */
2363 if (use_zero_timeout)
2364 timeout_val = 0;
2365 else if (con->connection_timeout_ms > 0)
2366 {
2367 const uint64_t mseconds_left = connection_get_wait (con);
2368#if SIZEOF_UINT64_T >= SIZEOF_INT
2369 if (mseconds_left >= INT_MAX)
2370 timeout_val = INT_MAX;
2371 else
2372#endif /* SIZEOF_UINT64_T >= SIZEOF_INT */
2373 timeout_val = (int) mseconds_left;
2374 }
2375 else
2376 timeout_val = -1;
2377 memset (&p,
2378 0,
2379 sizeof (p));
2380 p[0].fd = con->socket_fd;
2381 switch (con->event_loop_info)
2382 {
2385 p[0].events |= POLLIN | MHD_POLL_EVENTS_ERR_DISC;
2386 break;
2388 p[0].events |= POLLOUT | MHD_POLL_EVENTS_ERR_DISC;
2389 break;
2391 p[0].events |= MHD_POLL_EVENTS_ERR_DISC;
2392 break;
2394 /* how did we get here!? */
2395 goto exit;
2396 }
2397#ifdef WINDOWS
2398 extra_slot = 0;
2399 if (MHD_ITC_IS_VALID_ (daemon->itc))
2400 {
2401 p[1].events |= POLLIN;
2402 p[1].fd = MHD_itc_r_fd_ (daemon->itc);
2403 p[1].revents = 0;
2404 extra_slot = 1;
2405 }
2406#endif
2407 if (MHD_sys_poll_ (p,
2408#ifdef WINDOWS
2409 1 + extra_slot,
2410#else
2411 1,
2412#endif
2413 timeout_val) < 0)
2414 {
2416 continue;
2417#ifdef HAVE_MESSAGES
2418 MHD_DLOG (con->daemon,
2419 _ ("Error during poll: `%s'\n"),
2421#endif
2422 break;
2423 }
2424#ifdef WINDOWS
2425 /* Clear ITC before other processing so additional
2426 * signals will trigger poll() again */
2427 if ( (MHD_ITC_IS_VALID_ (daemon->itc)) &&
2428 (0 != (p[1].revents & (POLLERR | POLLHUP | POLLIN))) )
2429 MHD_itc_clear_ (daemon->itc);
2430#endif
2431 if (MHD_NO ==
2432 call_handlers (con,
2433 (0 != (p[0].revents & POLLIN)),
2434 (0 != (p[0].revents & POLLOUT)),
2435 (0 != (p[0].revents & MHD_POLL_REVENTS_ERR_DISC)) ))
2436 goto exit;
2437 }
2438#endif
2439#ifdef UPGRADE_SUPPORT
2440 if (MHD_CONNECTION_UPGRADE == con->state)
2441 {
2442 /* Normal HTTP processing is finished,
2443 * notify application. */
2444 if ( (NULL != daemon->notify_completed) &&
2445 (con->rq.client_aware) )
2446 daemon->notify_completed (daemon->notify_completed_cls,
2447 con,
2448 &con->rq.client_context,
2450 con->rq.client_aware = false;
2451
2452 thread_main_connection_upgrade (con);
2453 /* MHD_connection_finish_forward_() was called by thread_main_connection_upgrade(). */
2454
2455 /* "Upgraded" data will not be used in this thread from this point. */
2456 con->urh->clean_ready = true;
2457 /* If 'urh->was_closed' set to true, connection will be
2458 * moved immediately to cleanup list. Otherwise connection
2459 * will stay in suspended list until 'urh' will be marked
2460 * with 'was_closed' by application. */
2462
2463 /* skip usual clean up */
2464 return (MHD_THRD_RTRN_TYPE_) 0;
2465 }
2466#endif /* UPGRADE_SUPPORT */
2467 }
2468#if _MHD_DEBUG_CLOSE
2469#ifdef HAVE_MESSAGES
2470 MHD_DLOG (con->daemon,
2471 _ ("Processing thread terminating. Closing connection.\n"));
2472#endif
2473#endif
2474 if (MHD_CONNECTION_CLOSED != con->state)
2476 (daemon->shutdown) ?
2480exit:
2481 if (NULL != con->rp.response)
2482 {
2484 con->rp.response = NULL;
2485 }
2486
2487 if (MHD_INVALID_SOCKET != con->socket_fd)
2488 {
2489 shutdown (con->socket_fd,
2490 SHUT_WR);
2491 /* 'socket_fd' can be used in other thread to signal shutdown.
2492 * To avoid data races, do not close socket here. Daemon will
2493 * use more connections only after cleanup anyway. */
2494 }
2495 if ( (MHD_ITC_IS_VALID_ (daemon->itc)) &&
2496 (! MHD_itc_activate_ (daemon->itc, "t")) )
2497 {
2498#ifdef HAVE_MESSAGES
2499 MHD_DLOG (daemon,
2500 _ ("Failed to signal thread termination via inter-thread " \
2501 "communication channel.\n"));
2502#endif
2503 }
2504 return (MHD_THRD_RTRN_TYPE_) 0;
2505}
2506
2507
2508#endif
2509
2510
2518static void
2519MHD_cleanup_connections (struct MHD_Daemon *daemon);
2520
2521#if defined(HTTPS_SUPPORT)
2522#if defined(MHD_SEND_SPIPE_SUPPRESS_NEEDED) && \
2523 defined(MHD_SEND_SPIPE_SUPPRESS_POSSIBLE) && \
2524 ! defined(MHD_socket_nosignal_) && \
2525 (GNUTLS_VERSION_NUMBER + 0 < 0x030402) && defined(MSG_NOSIGNAL)
2531#define MHD_TLSLIB_NEED_PUSH_FUNC 1
2532#endif /* MHD_SEND_SPIPE_SUPPRESS_NEEDED &&
2533 MHD_SEND_SPIPE_SUPPRESS_POSSIBLE &&
2534 ! MHD_socket_nosignal_ && (GNUTLS_VERSION_NUMBER+0 < 0x030402) &&
2535 MSG_NOSIGNAL */
2536
2537#ifdef MHD_TLSLIB_NEED_PUSH_FUNC
2542static ssize_t
2543MHD_tls_push_func_ (gnutls_transport_ptr_t trnsp,
2544 const void *data,
2545 size_t data_size)
2546{
2547#if (MHD_SCKT_SEND_MAX_SIZE_ < SSIZE_MAX) || (0 == SSIZE_MAX)
2548 if (data_size > MHD_SCKT_SEND_MAX_SIZE_)
2549 data_size = MHD_SCKT_SEND_MAX_SIZE_;
2550#endif /* (MHD_SCKT_SEND_MAX_SIZE_ < SSIZE_MAX) || (0 == SSIZE_MAX) */
2551 return MHD_send_ ((MHD_socket) (intptr_t) (trnsp), data, data_size);
2552}
2553
2554
2555#endif /* MHD_TLSLIB_DONT_SUPPRESS_SIGPIPE */
2556
2557
2566#define MHD_PSK_MIN_SIZE 16
2567
2576static int
2577psk_gnutls_adapter (gnutls_session_t session,
2578 const char *username,
2579 gnutls_datum_t *key)
2580{
2581 struct MHD_Connection *connection;
2582 struct MHD_Daemon *daemon;
2583#if GNUTLS_VERSION_MAJOR >= 3
2584 void *app_psk;
2585 size_t app_psk_size;
2586#endif /* GNUTLS_VERSION_MAJOR >= 3 */
2587
2588 connection = gnutls_session_get_ptr (session);
2589 if (NULL == connection)
2590 {
2591#ifdef HAVE_MESSAGES
2592 /* Cannot use our logger, we don't even have "daemon" */
2593 MHD_PANIC (_ ("Internal server error. This should be impossible.\n"));
2594#endif
2595 return -1;
2596 }
2597 daemon = connection->daemon;
2598#if GNUTLS_VERSION_MAJOR >= 3
2599 if (NULL == daemon->cred_callback)
2600 {
2601#ifdef HAVE_MESSAGES
2602 MHD_DLOG (daemon,
2603 _ ("PSK not supported by this server.\n"));
2604#endif
2605 return -1;
2606 }
2607 if (0 != daemon->cred_callback (daemon->cred_callback_cls,
2608 connection,
2609 username,
2610 &app_psk,
2611 &app_psk_size))
2612 return -1;
2613 if (MHD_PSK_MIN_SIZE > app_psk_size)
2614 {
2615#ifdef HAVE_MESSAGES
2616 MHD_DLOG (daemon,
2617 _ ("PSK authentication failed: PSK too short.\n"));
2618#endif
2619 free (app_psk);
2620 return -1;
2621 }
2622 if (UINT_MAX < app_psk_size)
2623 {
2624#ifdef HAVE_MESSAGES
2625 MHD_DLOG (daemon,
2626 _ ("PSK authentication failed: PSK too long.\n"));
2627#endif
2628 free (app_psk);
2629 return -1;
2630 }
2631 /* @a app_psk_size is at least MHD_PSK_MIN_SIZE here, so this is never
2632 gnutls_malloc(0) -- whose result is implementation defined and would
2633 be reported below as an allocation failure. */
2634 if (NULL == (key->data = gnutls_malloc (app_psk_size)))
2635 {
2636#ifdef HAVE_MESSAGES
2637 MHD_DLOG (daemon,
2638 _ ("PSK authentication failed: gnutls_malloc failed to " \
2639 "allocate memory.\n"));
2640#endif
2641 free (app_psk);
2642 return -1;
2643 }
2644 key->size = (unsigned int) app_psk_size;
2645 memcpy (key->data,
2646 app_psk,
2647 app_psk_size);
2648 free (app_psk);
2649 return 0;
2650#else
2651 (void) username; (void) key; /* Mute compiler warning */
2652#ifdef HAVE_MESSAGES
2653 MHD_DLOG (daemon,
2654 _ ("PSK not supported by this server.\n"));
2655#endif
2656 return -1;
2657#endif
2658}
2659
2660
2661#endif /* HTTPS_SUPPORT */
2662
2663
2686static struct MHD_Connection *
2688 MHD_socket client_socket,
2689 const struct sockaddr_storage *addr,
2690 socklen_t addrlen,
2691 bool external_add,
2692 bool non_blck,
2693 bool sk_spipe_supprs,
2694 enum MHD_tristate sk_is_nonip)
2695{
2696 struct MHD_Connection *connection;
2697 int eno = 0;
2698
2699#ifdef HAVE_MESSAGES
2700#if _MHD_DEBUG_CONNECT
2701 MHD_DLOG (daemon,
2702 _ ("Accepted connection on socket %d.\n"),
2703 client_socket);
2704#endif
2705#endif
2708 addr,
2709 addrlen)) )
2710 {
2711 /* above connection limit - reject */
2712#ifdef HAVE_MESSAGES
2713 MHD_DLOG (daemon,
2714 _ ("Server reached connection limit. " \
2715 "Closing inbound connection.\n"));
2716#endif
2717 MHD_socket_close_chk_ (client_socket);
2718#if defined(ENFILE) && (ENFILE + 0 != 0)
2719 errno = ENFILE;
2720#endif
2721 return NULL;
2722 }
2723
2724 /* apply connection acceptance policy if present */
2725 if ( (NULL != daemon->apc) &&
2727 (const struct sockaddr *) addr,
2728 addrlen)) )
2729 {
2730#if _MHD_DEBUG_CLOSE
2731#ifdef HAVE_MESSAGES
2732 MHD_DLOG (daemon,
2733 _ ("Connection rejected by application. Closing connection.\n"));
2734#endif
2735#endif
2736 MHD_socket_close_chk_ (client_socket);
2738 addr,
2739 addrlen);
2740#if defined(EACCESS) && (EACCESS + 0 != 0)
2741 errno = EACCESS;
2742#endif
2743 return NULL;
2744 }
2745
2746 if (NULL == (connection = MHD_calloc_ (1, sizeof (struct MHD_Connection))))
2747 {
2748 eno = errno;
2749#ifdef HAVE_MESSAGES
2750 MHD_DLOG (daemon,
2751 _ ("Error allocating memory: %s\n"),
2752 MHD_strerror_ (errno));
2753#endif
2754 MHD_socket_close_chk_ (client_socket);
2756 addr,
2757 addrlen);
2758 errno = eno;
2759 return NULL;
2760 }
2761
2762 if (! external_add)
2763 {
2764 connection->sk_corked = _MHD_OFF;
2765 connection->sk_nodelay = _MHD_OFF;
2766 }
2767 else
2768 {
2769 connection->sk_corked = _MHD_UNKNOWN;
2770 connection->sk_nodelay = _MHD_UNKNOWN;
2771 }
2772
2773 if (0 < addrlen)
2774 {
2775 if (NULL == (connection->addr = malloc ((size_t) addrlen)))
2776 {
2777 eno = errno;
2778#ifdef HAVE_MESSAGES
2779 MHD_DLOG (daemon,
2780 _ ("Error allocating memory: %s\n"),
2781 MHD_strerror_ (errno));
2782#endif
2783 MHD_socket_close_chk_ (client_socket);
2785 addr,
2786 addrlen);
2787 free (connection);
2788 errno = eno;
2789 return NULL;
2790 }
2791 memcpy (connection->addr,
2792 addr,
2793 (size_t) addrlen);
2794 }
2795 else
2796 connection->addr = NULL;
2797 connection->addr_len = addrlen;
2798 connection->socket_fd = client_socket;
2799 connection->sk_nonblck = non_blck;
2800 connection->is_nonip = sk_is_nonip;
2801 connection->sk_spipe_suppress = sk_spipe_supprs;
2802#ifdef MHD_USE_THREADS
2803 MHD_thread_handle_ID_set_invalid_ (&connection->tid);
2804#endif /* MHD_USE_THREADS */
2805 connection->daemon = daemon;
2808 if (0 != connection->connection_timeout_ms)
2810
2811 MHD_itc_set_invalid_ (connection->resume_itc);
2814 (! MHD_itc_init_ (connection->resume_itc)) )
2815 {
2816 eno = errno;
2817#ifdef HAVE_MESSAGES
2818 MHD_DLOG (daemon,
2819 _ ("Failed to create inter-thread communication channel " \
2820 "for the connection: %s\n"),
2821 MHD_itc_last_strerror_ ());
2822#endif
2823 MHD_socket_close_chk_ (client_socket);
2825 addr,
2826 addrlen);
2827 if (NULL != connection->addr)
2828 free (connection->addr);
2829 free (connection);
2830 errno = eno;
2831 return NULL;
2832 }
2833
2834 if (0 == (daemon->options & MHD_USE_TLS))
2835 {
2836 /* set default connection handlers */
2837 MHD_set_http_callbacks_ (connection);
2838 }
2839 else
2840 {
2841#ifdef HTTPS_SUPPORT
2842#if (GNUTLS_VERSION_NUMBER + 0 >= 0x030500)
2843 gnutls_init_flags_t
2844#else
2845 unsigned int
2846#endif
2847 flags;
2848
2849 flags = GNUTLS_SERVER;
2850#if (GNUTLS_VERSION_NUMBER + 0 >= 0x030402)
2851 flags |= GNUTLS_NO_SIGNAL;
2852#endif /* GNUTLS_VERSION_NUMBER >= 0x030402 */
2853#if GNUTLS_VERSION_MAJOR >= 3
2854 flags |= GNUTLS_NONBLOCK;
2855#endif /* GNUTLS_VERSION_MAJOR >= 3*/
2856#if (GNUTLS_VERSION_NUMBER + 0 >= 0x030603)
2858 flags |= GNUTLS_POST_HANDSHAKE_AUTH;
2859#endif
2860#if (GNUTLS_VERSION_NUMBER + 0 >= 0x030605)
2862 flags |= GNUTLS_ENABLE_EARLY_DATA;
2863#endif
2864 connection->tls_state = MHD_TLS_CONN_INIT;
2865 MHD_set_https_callbacks (connection);
2866 if ((GNUTLS_E_SUCCESS != gnutls_init (&connection->tls_session, flags)) ||
2867 (GNUTLS_E_SUCCESS != gnutls_priority_set (connection->tls_session,
2868 daemon->priority_cache)))
2869 {
2870 if (NULL != connection->tls_session)
2871 gnutls_deinit (connection->tls_session);
2872 MHD_socket_close_chk_ (client_socket);
2874 addr,
2875 addrlen);
2876 if (NULL != connection->addr)
2877 free (connection->addr);
2878 free (connection);
2879#ifdef HAVE_MESSAGES
2880 MHD_DLOG (daemon,
2881 _ ("Failed to initialise TLS session.\n"));
2882#endif
2883#if defined(EPROTO) && (EPROTO + 0 != 0)
2884 errno = EPROTO;
2885#endif
2886 return NULL;
2887 }
2888#if (GNUTLS_VERSION_NUMBER + 0 >= 0x030200)
2889 if (! daemon->disable_alpn)
2890 {
2891 static const char prt1[] = "http/1.1"; /* Registered code for HTTP/1.1 */
2892 static const char prt2[] = "http/1.0"; /* Registered code for HTTP/1.0 */
2893 static const gnutls_datum_t prts[2] =
2894 { {_MHD_DROP_CONST (prt1), MHD_STATICSTR_LEN_ (prt1)},
2895 {_MHD_DROP_CONST (prt2), MHD_STATICSTR_LEN_ (prt2)} };
2896
2897 if (GNUTLS_E_SUCCESS !=
2898 gnutls_alpn_set_protocols (connection->tls_session,
2899 prts,
2900 sizeof(prts) / sizeof(prts[0]),
2901 0 /* | GNUTLS_ALPN_SERVER_PRECEDENCE */))
2902 {
2903#ifdef HAVE_MESSAGES
2904 MHD_DLOG (daemon,
2905 _ ("Failed to set ALPN protocols.\n"));
2906#else /* ! HAVE_MESSAGES */
2907 (void) 0; /* Mute compiler warning */
2908#endif /* ! HAVE_MESSAGES */
2909 }
2910 }
2911#endif /* GNUTLS_VERSION_NUMBER >= 0x030200 */
2912 gnutls_session_set_ptr (connection->tls_session,
2913 connection);
2914 switch (daemon->cred_type)
2915 {
2916 /* set needed credentials for certificate authentication. */
2917 case GNUTLS_CRD_CERTIFICATE:
2918 gnutls_credentials_set (connection->tls_session,
2919 GNUTLS_CRD_CERTIFICATE,
2920 daemon->x509_cred);
2921 break;
2922 case GNUTLS_CRD_PSK:
2923 gnutls_credentials_set (connection->tls_session,
2924 GNUTLS_CRD_PSK,
2925 daemon->psk_cred);
2926 gnutls_psk_set_server_credentials_function (daemon->psk_cred,
2927 &psk_gnutls_adapter);
2928 break;
2929 case GNUTLS_CRD_ANON:
2930 case GNUTLS_CRD_SRP:
2931 case GNUTLS_CRD_IA:
2932 default:
2933#ifdef HAVE_MESSAGES
2934 MHD_DLOG (daemon,
2935 _ ("Failed to setup TLS credentials: " \
2936 "unknown credential type %d.\n"),
2937 daemon->cred_type);
2938#endif
2939 gnutls_deinit (connection->tls_session);
2940 MHD_socket_close_chk_ (client_socket);
2942 addr,
2943 addrlen);
2944 if (NULL != connection->addr)
2945 free (connection->addr);
2946 free (connection);
2947 MHD_PANIC (_ ("Unknown credential type.\n"));
2948#if defined(EINVAL) && (EINVAL + 0 != 0)
2949 errno = EINVAL;
2950#endif
2951 return NULL;
2952 }
2953#if (GNUTLS_VERSION_NUMBER + 0 >= 0x030109) && ! defined(_WIN64)
2954 gnutls_transport_set_int (connection->tls_session,
2955 (int) (client_socket));
2956#else /* GnuTLS before 3.1.9 or Win x64 */
2957 gnutls_transport_set_ptr (connection->tls_session,
2958 (gnutls_transport_ptr_t) \
2959 (intptr_t) client_socket);
2960#endif /* GnuTLS before 3.1.9 or Win x64 */
2961#ifdef MHD_TLSLIB_NEED_PUSH_FUNC
2962 gnutls_transport_set_push_function (connection->tls_session,
2963 MHD_tls_push_func_);
2964#endif /* MHD_TLSLIB_NEED_PUSH_FUNC */
2965 if (daemon->https_mem_trust)
2966 gnutls_certificate_server_set_request (connection->tls_session,
2967 GNUTLS_CERT_REQUEST);
2968#else /* ! HTTPS_SUPPORT */
2969 MHD_socket_close_chk_ (client_socket);
2971 addr,
2972 addrlen);
2973 free (connection->addr);
2974 free (connection);
2975 MHD_PANIC (_ ("TLS connection on non-TLS daemon.\n"));
2976#if 0
2977 /* Unreachable code */
2978 eno = EINVAL;
2979 return NULL;
2980#endif
2981#endif /* ! HTTPS_SUPPORT */
2982 }
2983
2984 return connection;
2985}
2986
2987
2988#ifdef MHD_USE_THREADS
2994static void
2995new_connection_close_ (struct MHD_Daemon *daemon,
2996 struct MHD_Connection *connection)
2997{
2998 mhd_assert (connection->daemon == daemon);
2999 mhd_assert (! connection->in_cleanup);
3000 mhd_assert (NULL == connection->next);
3001 mhd_assert (NULL == connection->nextX);
3002#ifdef EPOLL_SUPPORT
3003 mhd_assert (NULL == connection->nextE);
3004#endif /* EPOLL_SUPPORT */
3005
3006#ifdef HTTPS_SUPPORT
3007 if (NULL != connection->tls_session)
3008 {
3010 gnutls_deinit (connection->tls_session);
3011 }
3012#endif /* HTTPS_SUPPORT */
3013 MHD_socket_close_chk_ (connection->socket_fd);
3014 if (MHD_ITC_IS_VALID_ (connection->resume_itc))
3015 MHD_itc_destroy_chk_ (connection->resume_itc);
3017 connection->addr,
3018 connection->addr_len);
3019 if (NULL != connection->addr)
3020 free (connection->addr);
3021 free (connection);
3022}
3023
3024
3025#endif /* MHD_USE_THREADS */
3026
3027
3038static enum MHD_Result
3040 struct MHD_Connection *connection)
3041{
3042 int eno = 0;
3043
3044 mhd_assert (connection->daemon == daemon);
3045
3046#ifdef MHD_USE_THREADS
3047 /* Function manipulate connection and timeout DL-lists,
3048 * must be called only within daemon thread. */
3051 mhd_assert (NULL == daemon->worker_pool);
3052#endif /* MHD_USE_THREADS */
3053
3054 /* Allocate memory pool in the processing thread so
3055 * intensively used memory area is allocated in "good"
3056 * (for the thread) memory region. It is important with
3057 * NUMA and/or complex cache hierarchy. */
3058 connection->pool = MHD_pool_create (daemon->pool_size);
3059 if (NULL == connection->pool)
3060 { /* 'pool' creation failed */
3061#ifdef HAVE_MESSAGES
3062 MHD_DLOG (daemon,
3063 _ ("Error allocating memory: %s\n"),
3064 MHD_strerror_ (errno));
3065#endif
3066#if defined(ENOMEM) && (ENOMEM + 0 != 0)
3067 eno = ENOMEM;
3068#endif
3069 (void) 0; /* Mute possible compiler warning */
3070 }
3071 else
3072 { /* 'pool' creation succeed */
3073 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
3074 /* Firm check under lock. */
3076 { /* Connections limit */
3077 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
3078#ifdef HAVE_MESSAGES
3079 MHD_DLOG (daemon,
3080 _ ("Server reached connection limit. "
3081 "Closing inbound connection.\n"));
3082#endif
3083#if defined(ENFILE) && (ENFILE + 0 != 0)
3084 eno = ENFILE;
3085#endif
3086 (void) 0; /* Mute possible compiler warning */
3087 }
3088 else
3089 { /* Have space for new connection */
3093 connection);
3095 {
3098 connection);
3099 }
3100 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
3101
3103
3106 connection,
3107 &connection->socket_context,
3109#ifdef MHD_USE_THREADS
3111 {
3113 if (! MHD_create_named_thread_ (&connection->tid,
3114 "MHD-connection",
3115 daemon->thread_stack_size,
3116 &thread_main_handle_connection,
3117 connection))
3118 {
3119 eno = errno;
3120#ifdef HAVE_MESSAGES
3121#ifdef EAGAIN
3122 if (EAGAIN == eno)
3123 MHD_DLOG (daemon,
3124 _ ("Failed to create a new thread because it would "
3125 "have exceeded the system limit on the number of "
3126 "threads or no system resources available.\n"));
3127 else
3128#endif /* EAGAIN */
3129 MHD_DLOG (daemon,
3130 _ ("Failed to create a thread: %s\n"),
3131 MHD_strerror_ (eno));
3132#endif /* HAVE_MESSAGES */
3133 }
3134 else /* New thread has been created successfully */
3135 return MHD_YES; /* *** Function success exit point *** */
3136 }
3137 else
3138#else /* ! MHD_USE_THREADS */
3139 if (1)
3140#endif /* ! MHD_USE_THREADS */
3141 { /* No 'thread-per-connection' */
3142#ifdef MHD_USE_THREADS
3143 connection->tid = daemon->tid;
3144#endif /* MHD_USE_THREADS */
3145#ifdef EPOLL_SUPPORT
3147 {
3148 if (0 == (daemon->options & MHD_USE_TURBO))
3149 {
3150 struct epoll_event event;
3151
3152 event.events = EPOLLIN | EPOLLOUT | EPOLLPRI | EPOLLET | EPOLLRDHUP;
3153 event.data.ptr = connection;
3154 if (0 != epoll_ctl (daemon->epoll_fd,
3155 EPOLL_CTL_ADD,
3156 connection->socket_fd,
3157 &event))
3158 {
3159 eno = errno;
3160#ifdef HAVE_MESSAGES
3161 MHD_DLOG (daemon,
3162 _ ("Call to epoll_ctl failed: %s\n"),
3164#endif
3165 }
3166 else
3167 { /* 'socket_fd' has been added to 'epool' */
3168 connection->epoll_state |= MHD_EPOLL_STATE_IN_EPOLL_SET;
3169
3170 return MHD_YES; /* *** Function success exit point *** */
3171 }
3172 }
3173 else
3174 {
3175 connection->epoll_state |= MHD_EPOLL_STATE_READ_READY
3178 EDLL_insert (daemon->eready_head,
3179 daemon->eready_tail,
3180 connection);
3181
3182 return MHD_YES; /* *** Function success exit point *** */
3183 }
3184 }
3185 else /* No 'epoll' */
3186#endif /* EPOLL_SUPPORT */
3187 return MHD_YES; /* *** Function success exit point *** */
3188 }
3189
3190 /* ** Below is a cleanup path ** */
3191 if (NULL != daemon->notify_connection)
3193 connection,
3194 &connection->socket_context,
3196 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
3197 if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon))
3198 {
3200 daemon->normal_timeout_tail,
3201 connection);
3202 }
3204 daemon->connections_tail,
3205 connection);
3206 daemon->connections--;
3207 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
3208 }
3209 MHD_pool_destroy (connection->pool);
3210 }
3211 /* Free resources allocated before the call of this functions */
3212#ifdef HTTPS_SUPPORT
3213 if (NULL != connection->tls_session)
3214 gnutls_deinit (connection->tls_session);
3215#endif /* HTTPS_SUPPORT */
3216 MHD_ip_limit_del (daemon,
3217 connection->addr,
3218 connection->addr_len);
3219 if (NULL != connection->addr)
3220 free (connection->addr);
3221 MHD_socket_close_chk_ (connection->socket_fd);
3222 free (connection);
3223 if (0 != eno)
3224 errno = eno;
3225#ifdef EINVAL
3226 else
3227 errno = EINVAL;
3228#endif /* EINVAL */
3229 return MHD_NO; /* *** Function failure exit point *** */
3230}
3231
3232
3261static enum MHD_Result
3263 MHD_socket client_socket,
3264 const struct sockaddr_storage *addr,
3265 socklen_t addrlen,
3266 bool external_add,
3267 bool non_blck,
3268 bool sk_spipe_supprs,
3269 enum MHD_tristate sk_is_nonip)
3270{
3271 struct MHD_Connection *connection;
3272
3273#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
3274 /* Direct add to master daemon could never happen. */
3275 mhd_assert (NULL == daemon->worker_pool);
3276#endif
3277
3279 (! MHD_D_DOES_SCKT_FIT_FDSET_ (client_socket, daemon)) )
3280 {
3281#ifdef HAVE_MESSAGES
3282 MHD_DLOG (daemon,
3283 _ ("New connection socket descriptor (%d) is not less " \
3284 "than FD_SETSIZE (%d).\n"),
3285 (int) client_socket,
3287#endif
3288 MHD_socket_close_chk_ (client_socket);
3289#if defined(ENFILE) && (ENFILE + 0 != 0)
3290 errno = ENFILE;
3291#endif
3292 return MHD_NO;
3293 }
3294
3296 (! non_blck) )
3297 {
3298#ifdef HAVE_MESSAGES
3299 MHD_DLOG (daemon,
3300 _ ("Epoll mode supports only non-blocking sockets\n"));
3301#endif
3302 MHD_socket_close_chk_ (client_socket);
3303#if defined(EINVAL) && (EINVAL + 0 != 0)
3304 errno = EINVAL;
3305#endif
3306 return MHD_NO;
3307 }
3308
3309 connection = new_connection_prepare_ (daemon,
3310 client_socket,
3311 addr, addrlen,
3312 external_add,
3313 non_blck,
3314 sk_spipe_supprs,
3315 sk_is_nonip);
3316 if (NULL == connection)
3317 return MHD_NO;
3318
3319 if ((external_add) &&
3321 {
3322 /* Connection is added externally and MHD is thread safe mode. */
3323 MHD_mutex_lock_chk_ (&daemon->new_connections_mutex);
3326 connection);
3327 daemon->have_new = true;
3328 MHD_mutex_unlock_chk_ (&daemon->new_connections_mutex);
3329
3330 /* The rest of connection processing must be handled in
3331 * the daemon thread. */
3332 if ((MHD_ITC_IS_VALID_ (daemon->itc)) &&
3333 (! MHD_itc_activate_ (daemon->itc, "n")))
3334 {
3335#ifdef HAVE_MESSAGES
3336 MHD_DLOG (daemon,
3337 _ ("Failed to signal new connection via inter-thread " \
3338 "communication channel.\n"));
3339#endif
3340 }
3341 return MHD_YES;
3342 }
3343
3344 return new_connection_process_ (daemon, connection);
3345}
3346
3347
3348static void
3350{
3351 struct MHD_Connection *local_head;
3352 struct MHD_Connection *local_tail;
3355
3356 /* Detach DL-list of new connections from the daemon for
3357 * following local processing. */
3358 MHD_mutex_lock_chk_ (&daemon->new_connections_mutex);
3360 local_head = daemon->new_connections_head;
3361 local_tail = daemon->new_connections_tail;
3364 daemon->have_new = false;
3365 MHD_mutex_unlock_chk_ (&daemon->new_connections_mutex);
3366 (void) local_head; /* Mute compiler warning */
3367
3368 /* Process new connections in FIFO order. */
3369 do
3370 {
3371 struct MHD_Connection *c;
3372
3373 c = local_tail;
3374 DLL_remove (local_head,
3375 local_tail,
3376 c);
3377 mhd_assert (daemon == c->daemon);
3379 {
3380#ifdef HAVE_MESSAGES
3381 MHD_DLOG (daemon,
3382 _ ("Failed to start serving new connection.\n"));
3383#endif
3384 (void) 0;
3385 }
3386 } while (NULL != local_tail);
3387
3388}
3389
3390
3400void
3402{
3403 struct MHD_Daemon *daemon = connection->daemon;
3404 mhd_assert (NULL == daemon->worker_pool);
3405
3406#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
3407 mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \
3410 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
3411#endif
3412 if (connection->resuming)
3413 {
3414 /* suspending again while we didn't even complete resuming yet */
3415 connection->resuming = false;
3416#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
3417 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
3418#endif
3419 return;
3420 }
3421 if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon))
3422 {
3423 if (connection->connection_timeout_ms == daemon->connection_timeout_ms)
3425 daemon->normal_timeout_tail,
3426 connection);
3427 else
3429 daemon->manual_timeout_tail,
3430 connection);
3431 }
3433 daemon->connections_tail,
3434 connection);
3435 mhd_assert (! connection->suspended);
3438 connection);
3439 connection->suspended = true;
3440#ifdef EPOLL_SUPPORT
3441 if (MHD_D_IS_USING_EPOLL_ (daemon))
3442 {
3443 if (0 != (connection->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL))
3444 {
3445 EDLL_remove (daemon->eready_head,
3446 daemon->eready_tail,
3447 connection);
3448 connection->epoll_state &=
3450 }
3451 if (0 != (connection->epoll_state & MHD_EPOLL_STATE_IN_EPOLL_SET))
3452 {
3453 if (0 != epoll_ctl (daemon->epoll_fd,
3454 EPOLL_CTL_DEL,
3455 connection->socket_fd,
3456 NULL))
3457 MHD_PANIC (_ ("Failed to remove FD from epoll set.\n"));
3458 connection->epoll_state &=
3460 }
3461 connection->epoll_state |= MHD_EPOLL_STATE_SUSPENDED;
3462 }
3463#endif
3464#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
3465 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
3466#endif
3467}
3468
3469
3498_MHD_EXTERN void
3500{
3501 struct MHD_Daemon *const daemon = connection->daemon;
3502
3503#ifdef MHD_USE_THREADS
3504 mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \
3507#endif /* MHD_USE_THREADS */
3508
3509 if (0 == (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME))
3510 MHD_PANIC (_ ("Cannot suspend connections without " \
3511 "enabling MHD_ALLOW_SUSPEND_RESUME!\n"));
3512#ifdef UPGRADE_SUPPORT
3513 if (NULL != connection->urh)
3514 {
3515#ifdef HAVE_MESSAGES
3516 MHD_DLOG (daemon,
3517 _ ("Error: connection scheduled for \"upgrade\" cannot " \
3518 "be suspended.\n"));
3519#endif /* HAVE_MESSAGES */
3520 return;
3521 }
3522#endif /* UPGRADE_SUPPORT */
3523 internal_suspend_connection_ (connection);
3524}
3525
3526
3541_MHD_EXTERN void
3543{
3544 struct MHD_Daemon *daemon = connection->daemon;
3545 bool own_thread;
3546#if defined(MHD_USE_THREADS)
3547 mhd_assert (NULL == daemon->worker_pool);
3548#endif /* MHD_USE_THREADS */
3549
3550 if (0 == (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME))
3551 MHD_PANIC (_ ("Cannot resume connections without enabling " \
3552 "MHD_ALLOW_SUSPEND_RESUME!\n"));
3553#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
3554 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
3555#endif
3556 connection->resuming = true;
3557 /* An "upgraded" connection is resumed only to be moved to the cleanup
3558 list, which is the daemon thread's job even with a thread per
3559 connection. */
3560 own_thread = MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)
3561#ifdef UPGRADE_SUPPORT
3562 && (NULL == connection->urh)
3563#endif /* UPGRADE_SUPPORT */
3564 ;
3565 if (! own_thread)
3566 daemon->resuming = true;
3567#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
3568 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
3569#endif
3570 if (own_thread)
3571 {
3572 /* Wake the connection's own thread. See the description of
3573 @e resume_itc for why the daemon-wide ITC will not do. */
3574 mhd_assert (MHD_ITC_IS_VALID_ (connection->resume_itc));
3575 if (! MHD_itc_activate_ (connection->resume_itc, "r"))
3576 {
3577#ifdef HAVE_MESSAGES
3578 MHD_DLOG (daemon,
3579 _ ("Failed to signal resume via the connection's " \
3580 "inter-thread communication channel.\n"));
3581#endif
3582 }
3583 }
3584 else if ( (MHD_ITC_IS_VALID_ (daemon->itc)) &&
3585 (! MHD_itc_activate_ (daemon->itc, "r")) )
3586 {
3587#ifdef HAVE_MESSAGES
3588 MHD_DLOG (daemon,
3589 _ ("Failed to signal resume via inter-thread " \
3590 "communication channel.\n"));
3591#endif
3592 }
3593}
3594
3595
3596#ifdef UPGRADE_SUPPORT
3604void
3605MHD_upgraded_connection_mark_app_closed_ (struct MHD_Connection *connection)
3606{
3607 /* Cache 'daemon' here to avoid data races */
3608 struct MHD_Daemon *const daemon = connection->daemon;
3609#if defined(MHD_USE_THREADS)
3610 mhd_assert (NULL == daemon->worker_pool);
3611#endif /* MHD_USE_THREADS */
3612 mhd_assert (NULL != connection->urh);
3614
3615 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
3616 connection->urh->was_closed = true;
3617 connection->resuming = true;
3618 daemon->resuming = true;
3619 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
3620 if ( (MHD_ITC_IS_VALID_ (daemon->itc)) &&
3621 (! MHD_itc_activate_ (daemon->itc, "r")) )
3622 {
3623#ifdef HAVE_MESSAGES
3624 MHD_DLOG (daemon,
3625 _ ("Failed to signal resume via " \
3626 "inter-thread communication channel.\n"));
3627#endif
3628 }
3629}
3630
3631
3632#endif /* UPGRADE_SUPPORT */
3633
3643static enum MHD_Result
3645{
3646 struct MHD_Connection *pos;
3647 struct MHD_Connection *prev = NULL;
3648 enum MHD_Result ret;
3649 const bool used_thr_p_c = (0 != (daemon->options
3651#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
3652 mhd_assert (NULL == daemon->worker_pool);
3655#endif
3656
3657 ret = MHD_NO;
3658#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
3659 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
3660#endif
3661
3662 if (daemon->resuming)
3663 {
3665 /* During shutdown check for resuming is forced. */
3666 mhd_assert ((NULL != prev) || (daemon->shutdown) || \
3667 (0 != (daemon->options & MHD_ALLOW_UPGRADE)));
3668 }
3669
3670 daemon->resuming = false;
3671
3672 while (NULL != (pos = prev))
3673 {
3674#ifdef UPGRADE_SUPPORT
3675 struct MHD_UpgradeResponseHandle *const urh = pos->urh;
3676#else /* ! UPGRADE_SUPPORT */
3677 static const void *const urh = NULL;
3678#endif /* ! UPGRADE_SUPPORT */
3679 prev = pos->prev;
3680 if ( (! pos->resuming)
3681#ifdef UPGRADE_SUPPORT
3682 || ( (NULL != urh) &&
3683 ( (! urh->was_closed) ||
3684 (! urh->clean_ready) ) )
3685#endif /* UPGRADE_SUPPORT */
3686 )
3687 continue;
3688 ret = MHD_YES;
3689 mhd_assert (pos->suspended);
3692 pos);
3693 pos->suspended = false;
3694 if (NULL == urh)
3695 {
3697 daemon->connections_tail,
3698 pos);
3699 if (! used_thr_p_c)
3700 {
3701 /* The states of a suspended connection are not updated, so they
3702 are stale now that it is running again. Updating them here
3703 would mean running the state machine under the cleanup mutex,
3704 which is what 0ecf4f26e4c1a4c03d66e1d04bf4cae62bd236a0 backed
3705 out of; flag the connection instead and let call_handlers()
3706 update it before it acts on @e event_loop_info. Thread-per-
3707 connection does the same for itself, in
3708 thread_main_handle_connection(). */
3709 pos->resumed = true;
3710
3711 /* Reset timeout timer on resume. */
3712 if (0 != pos->connection_timeout_ms)
3714
3715 if (pos->connection_timeout_ms == daemon->connection_timeout_ms)
3717 daemon->normal_timeout_tail,
3718 pos);
3719 else
3721 daemon->manual_timeout_tail,
3722 pos);
3723 }
3724#ifdef EPOLL_SUPPORT
3725 if (MHD_D_IS_USING_EPOLL_ (daemon))
3726 {
3727 if (0 != (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL))
3728 MHD_PANIC ("Resumed connection was already in EREADY set.\n");
3729 /* we always mark resumed connections as ready, as we
3730 might have missed the edge poll event during suspension */
3731 EDLL_insert (daemon->eready_head,
3732 daemon->eready_tail,
3733 pos);
3734 pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL \
3737 pos->epoll_state &= ~((enum MHD_EpollState) MHD_EPOLL_STATE_SUSPENDED);
3738 }
3739#endif
3740 }
3741#ifdef UPGRADE_SUPPORT
3742 else
3743 {
3744 /* Data forwarding was finished (for TLS connections) AND
3745 * application was closed upgraded connection.
3746 * Insert connection into cleanup list. */
3747 if ( (NULL != daemon->notify_completed) &&
3748 (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) &&
3749 (pos->rq.client_aware) )
3750 {
3751 daemon->notify_completed (daemon->notify_completed_cls,
3752 pos,
3753 &pos->rq.client_context,
3755 pos->rq.client_aware = false;
3756 }
3757 DLL_insert (daemon->cleanup_head,
3758 daemon->cleanup_tail,
3759 pos);
3760 daemon->data_already_pending = true;
3761 }
3762#endif /* UPGRADE_SUPPORT */
3763 pos->resuming = false;
3764 }
3765#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
3766 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
3767#endif
3768 if ( (used_thr_p_c) &&
3769 (MHD_NO != ret) )
3770 { /* Wake up suspended connections. */
3771 if (! MHD_itc_activate_ (daemon->itc,
3772 "w"))
3773 {
3774#ifdef HAVE_MESSAGES
3775 MHD_DLOG (daemon,
3776 _ ("Failed to signal resume of connection via " \
3777 "inter-thread communication channel.\n"));
3778#endif
3779 }
3780 }
3781 return ret;
3782}
3783
3784
3814 MHD_socket client_socket,
3815 const struct sockaddr *addr,
3816 socklen_t addrlen)
3817{
3818 bool sk_nonbl;
3819 bool sk_spipe_supprs;
3820 struct sockaddr_storage addrstorage;
3821
3822 /* TODO: fix atomic value reading */
3823 if ((! MHD_D_IS_THREAD_SAFE_ (daemon)) &&
3824 (daemon->connection_limit <= daemon->connections))
3825 MHD_cleanup_connections (daemon);
3826
3827#ifdef HAVE_MESSAGES
3828 if (MHD_D_IS_USING_THREADS_ (daemon) &&
3829 (0 == (daemon->options & MHD_USE_ITC)))
3830 {
3831 MHD_DLOG (daemon,
3832 _ ("MHD_add_connection() has been called for daemon started"
3833 " without MHD_USE_ITC flag.\nDaemon will not process newly"
3834 " added connection until any activity occurs in already"
3835 " added sockets.\n"));
3836 }
3837#endif /* HAVE_MESSAGES */
3838 if (0 != addrlen)
3839 {
3840 if (AF_INET == addr->sa_family)
3841 {
3842 if (sizeof(struct sockaddr_in) > (size_t) addrlen)
3843 {
3844#ifdef HAVE_MESSAGES
3845 MHD_DLOG (daemon,
3846 _ ("MHD_add_connection() has been called with "
3847 "incorrect 'addrlen' value.\n"));
3848#endif /* HAVE_MESSAGES */
3849 return MHD_NO;
3850 }
3851#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
3852 if ((0 != addr->sa_len) &&
3853 (sizeof(struct sockaddr_in) > (size_t) addr->sa_len) )
3854 {
3855#ifdef HAVE_MESSAGES
3856 MHD_DLOG (daemon,
3857 _ ("MHD_add_connection() has been called with " \
3858 "non-zero value of 'sa_len' member of " \
3859 "'struct sockaddr' which does not match 'sa_family'.\n"));
3860#endif /* HAVE_MESSAGES */
3861 return MHD_NO;
3862 }
3863#endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */
3864 }
3865#ifdef HAVE_INET6
3866 if (AF_INET6 == addr->sa_family)
3867 {
3868 if (sizeof(struct sockaddr_in6) > (size_t) addrlen)
3869 {
3870#ifdef HAVE_MESSAGES
3871 MHD_DLOG (daemon,
3872 _ ("MHD_add_connection() has been called with "
3873 "incorrect 'addrlen' value.\n"));
3874#endif /* HAVE_MESSAGES */
3875 return MHD_NO;
3876 }
3877#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
3878 if ((0 != addr->sa_len) &&
3879 (sizeof(struct sockaddr_in6) > (size_t) addr->sa_len) )
3880 {
3881#ifdef HAVE_MESSAGES
3882 MHD_DLOG (daemon,
3883 _ ("MHD_add_connection() has been called with " \
3884 "non-zero value of 'sa_len' member of " \
3885 "'struct sockaddr' which does not match 'sa_family'.\n"));
3886#endif /* HAVE_MESSAGES */
3887 return MHD_NO;
3888 }
3889#endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */
3890 }
3891#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
3892 if ((0 != addr->sa_len) &&
3893 (addrlen > addr->sa_len))
3894 addrlen = (socklen_t) addr->sa_len; /* Use safest value */
3895#endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */
3896#endif /* HAVE_INET6 */
3897 }
3898
3899 if (! MHD_socket_nonblocking_ (client_socket))
3900 {
3901#ifdef HAVE_MESSAGES
3902 MHD_DLOG (daemon,
3903 _ ("Failed to set nonblocking mode on new client socket: %s\n"),
3905#endif
3906 sk_nonbl = false;
3907 }
3908 else
3909 sk_nonbl = true;
3910
3911#ifndef MHD_WINSOCK_SOCKETS
3912 sk_spipe_supprs = false;
3913#else /* MHD_WINSOCK_SOCKETS */
3914 sk_spipe_supprs = true; /* Nothing to suppress on W32 */
3915#endif /* MHD_WINSOCK_SOCKETS */
3916#if defined(MHD_socket_nosignal_)
3917 if (! sk_spipe_supprs)
3918 sk_spipe_supprs = MHD_socket_nosignal_ (client_socket);
3919 if (! sk_spipe_supprs)
3920 {
3921#ifdef HAVE_MESSAGES
3922 MHD_DLOG (daemon,
3923 _ ("Failed to suppress SIGPIPE on new client socket: %s\n"),
3925#else /* ! HAVE_MESSAGES */
3926 (void) 0; /* Mute compiler warning */
3927#endif /* ! HAVE_MESSAGES */
3928#ifndef MSG_NOSIGNAL
3929 /* Application expects that SIGPIPE will be suppressed,
3930 * but suppression failed and SIGPIPE cannot be suppressed with send(). */
3931 if (! daemon->sigpipe_blocked)
3932 {
3933 int err = MHD_socket_get_error_ ();
3934 MHD_socket_close_ (client_socket);
3936 return MHD_NO;
3937 }
3938#endif /* MSG_NOSIGNAL */
3939 }
3940#endif /* MHD_socket_nosignal_ */
3941
3942 if ( (0 != (daemon->options & MHD_USE_TURBO)) &&
3943 (! MHD_socket_noninheritable_ (client_socket)) )
3944 {
3945#ifdef HAVE_MESSAGES
3946 MHD_DLOG (daemon,
3947 _ ("Failed to set noninheritable mode on new client socket.\n"));
3948#endif
3949 }
3950
3951 /* Copy to sockaddr_storage structure to avoid alignment problems */
3952 if (0 < addrlen)
3953 memcpy (&addrstorage, addr, (size_t) addrlen);
3954#ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN
3955 addrstorage.ss_len = addrlen; /* Force set the right length */
3956#endif /* HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN */
3957
3958#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
3959 if (NULL != daemon->worker_pool)
3960 {
3961 unsigned int i;
3962 /* have a pool, try to find a pool with capacity; we use the
3963 socket as the initial offset into the pool for load
3964 balancing */
3965 for (i = 0; i < daemon->worker_pool_size; ++i)
3966 {
3967 struct MHD_Daemon *const worker =
3968 &daemon->worker_pool[(i + (unsigned int) client_socket)
3969 % daemon->worker_pool_size];
3970 if (worker->connections < worker->connection_limit)
3971 return internal_add_connection (worker,
3972 client_socket,
3973 &addrstorage,
3974 addrlen,
3975 true,
3976 sk_nonbl,
3977 sk_spipe_supprs,
3978 _MHD_UNKNOWN);
3979 }
3980 /* all pools are at their connection limit, must refuse */
3981 MHD_socket_close_chk_ (client_socket);
3982#if defined(ENFILE) && (ENFILE + 0 != 0)
3983 errno = ENFILE;
3984#endif
3985 return MHD_NO;
3986 }
3987#endif /* MHD_USE_POSIX_THREADS || MHD_USE_W32_THREADS */
3988
3989 return internal_add_connection (daemon,
3990 client_socket,
3991 &addrstorage,
3992 addrlen,
3993 true,
3994 sk_nonbl,
3995 sk_spipe_supprs,
3996 _MHD_UNKNOWN);
3997}
3998
3999
4014static enum MHD_Result
4016{
4017 struct sockaddr_storage addrstorage;
4018 socklen_t addrlen;
4019 MHD_socket s;
4020 MHD_socket fd;
4021 bool sk_nonbl;
4022 bool sk_spipe_supprs;
4023 bool sk_cloexec;
4024 enum MHD_tristate sk_non_ip;
4025#if defined(_DEBUG) && defined (USE_ACCEPT4)
4026 const bool use_accept4 = ! daemon->avoid_accept4;
4027#elif defined (USE_ACCEPT4)
4028 static const bool use_accept4 = true;
4029#else /* ! USE_ACCEPT4 && ! _DEBUG */
4030 static const bool use_accept4 = false;
4031#endif /* ! USE_ACCEPT4 && ! _DEBUG */
4032
4033#ifdef MHD_USE_THREADS
4034 mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \
4036 mhd_assert (NULL == daemon->worker_pool);
4037#endif /* MHD_USE_THREADS */
4038
4039 if ( (MHD_INVALID_SOCKET == (fd = daemon->listen_fd)) ||
4040 (daemon->was_quiesced) )
4041 return MHD_NO;
4042
4043 addrlen = (socklen_t) sizeof (addrstorage);
4044 memset (&addrstorage,
4045 0,
4046 (size_t) addrlen);
4047#ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN
4048 addrstorage.ss_len = addrlen;
4049#endif /* HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN */
4050
4051 /* Initialise with default values to avoid compiler warnings */
4052 sk_nonbl = false;
4053 sk_spipe_supprs = false;
4054 sk_cloexec = false;
4056
4057#ifdef USE_ACCEPT4
4058 if (use_accept4 &&
4060 (s = accept4 (fd,
4061 (struct sockaddr *) &addrstorage,
4062 &addrlen,
4065 {
4066 sk_nonbl = (SOCK_NONBLOCK_OR_ZERO != 0);
4067#ifndef MHD_WINSOCK_SOCKETS
4068 sk_spipe_supprs = (SOCK_NOSIGPIPE_OR_ZERO != 0);
4069#else /* MHD_WINSOCK_SOCKETS */
4070 sk_spipe_supprs = true; /* Nothing to suppress on W32 */
4071#endif /* MHD_WINSOCK_SOCKETS */
4072 sk_cloexec = (SOCK_CLOEXEC_OR_ZERO != 0);
4073 }
4074#endif /* USE_ACCEPT4 */
4075#if defined(_DEBUG) || ! defined(USE_ACCEPT4)
4076 if (! use_accept4 &&
4078 (s = accept (fd,
4079 (struct sockaddr *) &addrstorage,
4080 &addrlen))))
4081 {
4082#ifdef MHD_ACCEPT_INHERIT_NONBLOCK
4083 sk_nonbl = daemon->listen_nonblk;
4084#else /* ! MHD_ACCEPT_INHERIT_NONBLOCK */
4085 sk_nonbl = false;
4086#endif /* ! MHD_ACCEPT_INHERIT_NONBLOCK */
4087#ifndef MHD_WINSOCK_SOCKETS
4088 sk_spipe_supprs = false;
4089#else /* MHD_WINSOCK_SOCKETS */
4090 sk_spipe_supprs = true; /* Nothing to suppress on W32 */
4091#endif /* MHD_WINSOCK_SOCKETS */
4092 sk_cloexec = false;
4093 }
4094#endif /* _DEBUG || !USE_ACCEPT4 */
4095
4096 if (MHD_INVALID_SOCKET == s)
4097 {
4098 const int err = MHD_socket_get_error_ ();
4099
4100 /* This could be a common occurrence with multiple worker threads */
4101 if (MHD_SCKT_ERR_IS_ (err,
4103 return MHD_NO; /* can happen during shutdown */
4105 return MHD_NO; /* do not print error if client just disconnected early */
4106#ifdef HAVE_MESSAGES
4107 if (! MHD_SCKT_ERR_IS_EAGAIN_ (err) )
4108 MHD_DLOG (daemon,
4109 _ ("Error accepting connection: %s\n"),
4110 MHD_socket_strerr_ (err));
4111#endif
4113 {
4114 /* system/process out of resources */
4115 if (0 == daemon->connections)
4116 {
4117#ifdef HAVE_MESSAGES
4118 /* Not setting 'at_limit' flag, as there is no way it
4119 would ever be cleared. Instead trying to produce
4120 bit fat ugly warning. */
4121 MHD_DLOG (daemon,
4122 _ ("Hit process or system resource limit at FIRST " \
4123 "connection. This is really bad as there is no sane " \
4124 "way to proceed. Will try busy waiting for system " \
4125 "resources to become magically available.\n"));
4126#endif
4127 }
4128 else
4129 {
4130#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
4131 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
4132#endif
4133 daemon->at_limit = true;
4134#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
4135 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
4136#endif
4137#ifdef HAVE_MESSAGES
4138 MHD_DLOG (daemon,
4139 _ ("Hit process or system resource limit at %u " \
4140 "connections, temporarily suspending accept(). " \
4141 "Consider setting a lower MHD_OPTION_CONNECTION_LIMIT.\n"),
4142 (unsigned int) daemon->connections);
4143#endif
4144 }
4145 }
4146 return MHD_NO;
4147 }
4148
4149 sk_non_ip = daemon->listen_is_unix;
4150 if (0 >= addrlen)
4151 {
4152#ifdef HAVE_MESSAGES
4153 if (_MHD_NO != daemon->listen_is_unix)
4154 MHD_DLOG (daemon,
4155 _ ("Accepted socket has zero-length address. "
4156 "Processing the new socket as a socket with " \
4157 "unknown type.\n"));
4158#endif
4159 addrlen = 0;
4160 sk_non_ip = _MHD_YES; /* IP-type addresses have non-zero length */
4161 }
4162 if (((socklen_t) sizeof (addrstorage)) < addrlen)
4163 {
4164 /* Should not happen as 'sockaddr_storage' must be large enough to
4165 * store any address supported by the system. */
4166#ifdef HAVE_MESSAGES
4167 MHD_DLOG (daemon,
4168 _ ("Accepted socket address is larger than expected by " \
4169 "system headers. Processing the new socket as a socket with " \
4170 "unknown type.\n"));
4171#endif
4172 addrlen = 0;
4173 sk_non_ip = _MHD_YES; /* IP-type addresses must fit */
4174 }
4175
4176 if (! sk_nonbl && ! MHD_socket_nonblocking_ (s))
4177 {
4178#ifdef HAVE_MESSAGES
4179 MHD_DLOG (daemon,
4180 _ ("Failed to set nonblocking mode on incoming connection " \
4181 "socket: %s\n"),
4183#else /* ! HAVE_MESSAGES */
4184 (void) 0; /* Mute compiler warning */
4185#endif /* ! HAVE_MESSAGES */
4186 }
4187 else
4188 sk_nonbl = true;
4189
4190 if (! sk_cloexec && ! MHD_socket_noninheritable_ (s))
4191 {
4192#ifdef HAVE_MESSAGES
4193 MHD_DLOG (daemon,
4194 _ ("Failed to set noninheritable mode on incoming connection " \
4195 "socket.\n"));
4196#else /* ! HAVE_MESSAGES */
4197 (void) 0; /* Mute compiler warning */
4198#endif /* ! HAVE_MESSAGES */
4199 }
4200
4201#if defined(MHD_socket_nosignal_)
4202 if (! sk_spipe_supprs && ! MHD_socket_nosignal_ (s))
4203 {
4204#ifdef HAVE_MESSAGES
4205 MHD_DLOG (daemon,
4206 _ ("Failed to suppress SIGPIPE on incoming connection " \
4207 "socket: %s\n"),
4209#else /* ! HAVE_MESSAGES */
4210 (void) 0; /* Mute compiler warning */
4211#endif /* ! HAVE_MESSAGES */
4212#ifndef MSG_NOSIGNAL
4213 /* Application expects that SIGPIPE will be suppressed,
4214 * but suppression failed and SIGPIPE cannot be suppressed with send(). */
4215 if (! daemon->sigpipe_blocked)
4216 {
4217 (void) MHD_socket_close_ (s);
4218 return MHD_NO;
4219 }
4220#endif /* MSG_NOSIGNAL */
4221 }
4222 else
4223 sk_spipe_supprs = true;
4224#endif /* MHD_socket_nosignal_ */
4225#ifdef HAVE_MESSAGES
4226#if _MHD_DEBUG_CONNECT
4227 MHD_DLOG (daemon,
4228 _ ("Accepted connection on socket %d\n"),
4229 s);
4230#endif
4231#endif
4232 (void) internal_add_connection (daemon,
4233 s,
4234 &addrstorage,
4235 addrlen,
4236 false,
4237 sk_nonbl,
4238 sk_spipe_supprs,
4239 sk_non_ip);
4240 return MHD_YES;
4241}
4242
4243
4253static void
4255{
4256 struct MHD_Connection *pos;
4257#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
4260 mhd_assert (NULL == daemon->worker_pool);
4261
4262 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
4263#endif
4264 while (NULL != (pos = daemon->cleanup_tail))
4265 {
4268 pos);
4269#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
4270 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
4272 (! pos->thread_joined) &&
4273 (! MHD_thread_handle_ID_join_thread_ (pos->tid)) )
4274 MHD_PANIC (_ ("Failed to join a thread.\n"));
4275#endif
4276#ifdef UPGRADE_SUPPORT
4277 cleanup_upgraded_connection (pos);
4278#endif /* UPGRADE_SUPPORT */
4279 MHD_pool_destroy (pos->pool);
4280#ifdef HTTPS_SUPPORT
4281 if (NULL != pos->tls_session)
4282 gnutls_deinit (pos->tls_session);
4283#endif /* HTTPS_SUPPORT */
4284
4285 /* clean up the connection */
4288 pos,
4289 &pos->socket_context,
4292 pos->addr,
4293 pos->addr_len);
4294#ifdef EPOLL_SUPPORT
4296 {
4297 if (0 != (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL))
4298 {
4299 EDLL_remove (daemon->eready_head,
4300 daemon->eready_tail,
4301 pos);
4302 pos->epoll_state &=
4304 }
4305 if ( (-1 != daemon->epoll_fd) &&
4306 (0 != (pos->epoll_state & MHD_EPOLL_STATE_IN_EPOLL_SET)) )
4307 {
4308 /* epoll documentation suggests that closing a FD
4309 automatically removes it from the epoll set; however,
4310 this is not true as if we fail to do manually remove it,
4311 we are still seeing an event for this fd in epoll,
4312 causing grief (use-after-free...) --- at least on my
4313 system. */
4314 if (0 != epoll_ctl (daemon->epoll_fd,
4315 EPOLL_CTL_DEL,
4316 pos->socket_fd,
4317 NULL))
4318 MHD_PANIC (_ ("Failed to remove FD from epoll set.\n"));
4319 pos->epoll_state &=
4320 ~((enum MHD_EpollState)
4322 }
4323 }
4324#endif
4325 if (NULL != pos->rp.response)
4326 {
4328 pos->rp.response = NULL;
4329 }
4330 if (MHD_INVALID_SOCKET != pos->socket_fd)
4332 if (MHD_ITC_IS_VALID_ (pos->resume_itc))
4334 if (NULL != pos->addr)
4335 free (pos->addr);
4336 free (pos);
4337
4338#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
4339 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
4340#endif
4342 daemon->at_limit = false;
4343 }
4344#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
4345 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
4346#endif
4347}
4348
4349
4386 MHD_UNSIGNED_LONG_LONG *timeout)
4387{
4388 uint64_t t64;
4389 if (MHD_NO == MHD_get_timeout64 (daemon, &t64))
4390 return MHD_NO;
4391
4392#if SIZEOF_UINT64_T > SIZEOF_UNSIGNED_LONG_LONG
4393 if (ULLONG_MAX <= t64)
4394 *timeout = ULLONG_MAX;
4395 else
4396#endif /* SIZEOF_UINT64_T > SIZEOF_UNSIGNED_LONG_LONG */
4397 *timeout = (MHD_UNSIGNED_LONG_LONG) t64;
4398 return MHD_YES;
4399}
4400
4401
4440 uint64_t *timeout64)
4441{
4442 uint64_t earliest_deadline;
4443 struct MHD_Connection *pos;
4444 struct MHD_Connection *earliest_tmot_conn;
4445 bool resuming;
4446
4447#ifdef MHD_USE_THREADS
4450#endif /* MHD_USE_THREADS */
4451
4453 {
4454#ifdef HAVE_MESSAGES
4455 MHD_DLOG (daemon,
4456 _ ("Illegal call to MHD_get_timeout.\n"));
4457#endif
4458 return MHD_NO;
4459 }
4460 /* Unlike the other flags checked below, which are touched only by the
4461 thread that processes this daemon's polling, 'resuming' is set by
4462 #MHD_resume_connection(), which the application may legally call from
4463 any thread. It is guarded by 'cleanup_connection_mutex' everywhere. */
4464#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
4465 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
4466#endif
4468#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
4469 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
4470#endif
4472 || (NULL != daemon->cleanup_head)
4473 || resuming
4474 || daemon->have_new
4475 || daemon->shutdown)
4476 {
4477 /* Some data or connection statuses already waiting to be processed. */
4478 *timeout64 = 0;
4479 return MHD_YES;
4480 }
4481#ifdef EPOLL_SUPPORT
4483 ((NULL != daemon->eready_head)
4484#if defined(UPGRADE_SUPPORT) && defined(HTTPS_SUPPORT)
4485 || (NULL != daemon->eready_urh_head)
4486#endif /* UPGRADE_SUPPORT && HTTPS_SUPPORT */
4487 ) )
4488 {
4489 /* Some connection(s) already have some data pending. */
4490 *timeout64 = 0;
4491 return MHD_YES;
4492 }
4493#endif /* EPOLL_SUPPORT */
4494
4495 earliest_tmot_conn = NULL;
4496 earliest_deadline = 0; /* mute compiler warning */
4497 /* normal timeouts are sorted, so we only need to look at the 'tail' (oldest) */
4499 if ( (NULL != pos) &&
4500 (0 != pos->connection_timeout_ms) )
4501 {
4502 earliest_tmot_conn = pos;
4503 earliest_deadline = pos->last_activity + pos->connection_timeout_ms;
4504 }
4505
4506 for (pos = daemon->manual_timeout_tail;
4507 NULL != pos;
4508 pos = pos->prevX)
4509 {
4510 if (0 != pos->connection_timeout_ms)
4511 {
4512 if ( (NULL == earliest_tmot_conn) ||
4513 (earliest_deadline >
4515 {
4516 earliest_tmot_conn = pos;
4517 earliest_deadline = pos->last_activity + pos->connection_timeout_ms;
4518 }
4519 }
4520 }
4521
4522 if (NULL != earliest_tmot_conn)
4523 {
4524 *timeout64 = connection_get_wait (earliest_tmot_conn);
4525 return MHD_YES;
4526 }
4527 return MHD_NO;
4528}
4529
4530
4531#if defined(HAVE_POLL) || defined(EPOLL_SUPPORT)
4570_MHD_EXTERN int64_t
4572{
4573 uint64_t utimeout;
4574 if (MHD_NO == MHD_get_timeout64 (daemon, &utimeout))
4575 return -1;
4576 if (INT64_MAX < utimeout)
4577 return INT64_MAX;
4578
4579 return (int64_t) utimeout;
4580}
4581
4582
4622_MHD_EXTERN int
4624{
4625#if SIZEOF_INT >= SIZEOF_INT64_T
4626 return MHD_get_timeout64s (daemon);
4627#else /* SIZEOF_INT < SIZEOF_INT64_T */
4628 const int64_t to64 = MHD_get_timeout64s (daemon);
4629 if (INT_MAX >= to64)
4630 return (int) to64;
4631 return INT_MAX;
4632#endif /* SIZEOF_INT < SIZEOF_INT64_T */
4633}
4634
4635
4646static int64_t
4647get_timeout_millisec_ (struct MHD_Daemon *daemon,
4648 int32_t max_timeout)
4649{
4650 uint64_t d_timeout;
4651 mhd_assert (0 <= max_timeout || -1 == max_timeout);
4652 if (0 == max_timeout)
4653 return 0;
4654
4655 if (MHD_NO == MHD_get_timeout64 (daemon, &d_timeout))
4656 return max_timeout;
4657
4658 if ((0 < max_timeout) && ((uint64_t) max_timeout < d_timeout))
4659 return max_timeout;
4660
4661 if (INT64_MAX <= d_timeout)
4662 return INT64_MAX;
4663
4664 return (int64_t) d_timeout;
4665}
4666
4667
4679static int
4680get_timeout_millisec_int (struct MHD_Daemon *daemon,
4681 int32_t max_timeout)
4682{
4683 int64_t res;
4684
4685 res = get_timeout_millisec_ (daemon, max_timeout);
4686#if SIZEOF_INT < SIZEOF_INT64_T
4687 if (INT_MAX <= res)
4688 return INT_MAX;
4689#endif /* SIZEOF_INT < SIZEOF_INT64_T */
4690 return (int) res;
4691}
4692
4693
4694#endif /* HAVE_POLL || EPOLL_SUPPORT */
4695
4707static enum MHD_Result
4709 const fd_set *read_fd_set,
4710 const fd_set *write_fd_set,
4711 const fd_set *except_fd_set,
4712 int fd_setsize)
4713{
4714 MHD_socket ds;
4715#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
4716 struct MHD_UpgradeResponseHandle *urh;
4717 struct MHD_UpgradeResponseHandle *urhn;
4718#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
4719
4720 mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \
4721 (MHD_thread_handle_ID_is_valid_ID_ (daemon->tid)));
4722 mhd_assert ((0 != (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \
4723 (! MHD_thread_handle_ID_is_valid_ID_ (daemon->tid)));
4724 mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \
4726
4727 mhd_assert (0 < fd_setsize);
4728 (void) fd_setsize; /* Mute compiler warning */
4729#ifndef HAS_FD_SETSIZE_OVERRIDABLE
4730 (void) fd_setsize; /* Mute compiler warning */
4731 mhd_assert (((int) FD_SETSIZE) <= fd_setsize);
4732 fd_setsize = FD_SETSIZE; /* Help compiler to optimise */
4733#endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */
4734
4735 /* Clear ITC to avoid spinning select */
4736 /* Do it before any other processing so new signals
4737 will trigger select again and will be processed */
4738 if (MHD_ITC_IS_VALID_ (daemon->itc))
4739 { /* Have ITC */
4740 bool need_to_clear_itc = true; /* ITC is always non-blocking, it is safe to clear even if ITC not activated */
4741 if (MHD_SCKT_FD_FITS_FDSET_SETSIZE_ (MHD_itc_r_fd_ (daemon->itc),
4742 NULL, fd_setsize))
4743 need_to_clear_itc = FD_ISSET (MHD_itc_r_fd_ (daemon->itc), \
4744 (fd_set *) _MHD_DROP_CONST (read_fd_set)); /* Skip clearing, if not needed */
4745 if (need_to_clear_itc)
4746 MHD_itc_clear_ (daemon->itc);
4747 }
4748
4749 /* Reset. New value will be set when connections are processed. */
4750 /* Note: no-op for thread-per-connection as it is always false in that mode. */
4751 daemon->data_already_pending = false;
4752
4753 /* Process externally added connection if any */
4754 if (daemon->have_new)
4756
4757 /* select connection thread handling type */
4758 ds = daemon->listen_fd;
4759 if ( (MHD_INVALID_SOCKET != ds) &&
4760 (! daemon->was_quiesced) )
4761 {
4762 bool need_to_accept;
4763 if (MHD_SCKT_FD_FITS_FDSET_SETSIZE_ (ds, NULL, fd_setsize))
4764 need_to_accept = FD_ISSET (ds,
4765 (fd_set *) _MHD_DROP_CONST (read_fd_set));
4766 else /* Cannot check whether new connection are pending */
4767 need_to_accept = daemon->listen_nonblk; /* Try to accept if non-blocking */
4768
4769 if (need_to_accept)
4770 (void) MHD_accept_connection (daemon);
4771 }
4772
4773 if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon))
4774 {
4775 /* do not have a thread per connection, process all connections now */
4776 struct MHD_Connection *pos;
4777 struct MHD_Connection *prev;
4778
4779 for (pos = daemon->connections_tail; NULL != pos; pos = prev)
4780 {
4781 MHD_socket cs;
4782 bool r_ready;
4783 bool w_ready;
4784 bool has_err;
4785
4786 prev = pos->prev;
4787 cs = pos->socket_fd;
4788 if (MHD_INVALID_SOCKET == cs)
4789 continue;
4790
4791 if (MHD_SCKT_FD_FITS_FDSET_SETSIZE_ (cs, NULL, fd_setsize))
4792 {
4793 r_ready = FD_ISSET (cs,
4794 (fd_set *) _MHD_DROP_CONST (read_fd_set));
4795 w_ready = FD_ISSET (cs,
4796 (fd_set *) _MHD_DROP_CONST (write_fd_set));
4797 has_err = (NULL != except_fd_set) &&
4798 FD_ISSET (cs,
4799 (fd_set *) _MHD_DROP_CONST (except_fd_set));
4800 }
4801 else
4802 { /* Cannot check the real readiness */
4803 r_ready = pos->sk_nonblck;
4804 w_ready = r_ready;
4805 has_err = false;
4806 }
4807 call_handlers (pos,
4808 r_ready,
4809 w_ready,
4810 has_err);
4811 }
4812 }
4813
4814#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
4815 /* handle upgraded HTTPS connections */
4816 for (urh = daemon->urh_tail; NULL != urh; urh = urhn)
4817 {
4818 urhn = urh->prev;
4819 /* update urh state based on select() output */
4820 urh_from_fdset (urh,
4821 read_fd_set,
4822 write_fd_set,
4823 except_fd_set,
4824 fd_setsize);
4825 /* call generic forwarding function for passing data */
4826 process_urh (urh);
4827 /* Finished forwarding? */
4828 if ( (0 == urh->in_buffer_size) &&
4829 (0 == urh->out_buffer_size) &&
4830 (0 == urh->in_buffer_used) &&
4831 (0 == urh->out_buffer_used) )
4832 {
4833 MHD_connection_finish_forward_ (urh->connection);
4834 urh->clean_ready = true;
4835 /* Resuming will move connection to cleanup list. */
4836 MHD_resume_connection (urh->connection);
4837 }
4838 }
4839#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
4841 return MHD_YES;
4842}
4843
4844
4845#undef MHD_run_from_select
4846
4880 const fd_set *read_fd_set,
4881 const fd_set *write_fd_set,
4882 const fd_set *except_fd_set,
4883 unsigned int fd_setsize)
4884{
4887 return MHD_NO;
4888 if ((NULL == read_fd_set) || (NULL == write_fd_set))
4889 return MHD_NO;
4890#ifdef HAVE_MESSAGES
4891 if (NULL == except_fd_set)
4892 {
4893 MHD_DLOG (daemon,
4894 _ ("MHD_run_from_select() called with except_fd_set "
4895 "set to NULL. Such behavior is deprecated.\n"));
4896 }
4897#endif /* HAVE_MESSAGES */
4898
4899#ifdef HAS_FD_SETSIZE_OVERRIDABLE
4900 if (0 == fd_setsize)
4901 return MHD_NO;
4902 else if (((unsigned int) INT_MAX) < fd_setsize)
4903 fd_setsize = (unsigned int) INT_MAX;
4904#ifdef HAVE_MESSAGES
4905 else if (daemon->fdset_size > ((int) fd_setsize))
4906 {
4907 if (daemon->fdset_size_set_by_app)
4908 {
4909 MHD_DLOG (daemon,
4910 _ ("%s() called with fd_setsize (%u) " \
4911 "less than value set by MHD_OPTION_APP_FD_SETSIZE (%d). " \
4912 "Some socket FDs may be not processed. " \
4913 "Use MHD_OPTION_APP_FD_SETSIZE with the correct value.\n"),
4914 "MHD_run_from_select2", fd_setsize, daemon->fdset_size);
4915 }
4916 else
4917 {
4918 MHD_DLOG (daemon,
4919 _ ("%s() called with fd_setsize (%u) " \
4920 "less than FD_SETSIZE used by MHD (%d). " \
4921 "Some socket FDs may be not processed. " \
4922 "Consider using MHD_OPTION_APP_FD_SETSIZE option.\n"),
4923 "MHD_run_from_select2", fd_setsize, daemon->fdset_size);
4924 }
4925 }
4926#endif /* HAVE_MESSAGES */
4927#else /* ! HAS_FD_SETSIZE_OVERRIDABLE */
4928 if (((unsigned int) FD_SETSIZE) > fd_setsize)
4929 {
4930#ifdef HAVE_MESSAGES
4931 MHD_DLOG (daemon,
4932 _ ("%s() called with fd_setsize (%u) " \
4933 "less than fixed FD_SETSIZE value (%d) used on the " \
4934 "platform.\n"),
4935 "MHD_run_from_select2", fd_setsize, (int) FD_SETSIZE);
4936#endif /* HAVE_MESSAGES */
4937 return MHD_NO;
4938 }
4939#endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */
4940
4942 {
4943#ifdef EPOLL_SUPPORT
4944 enum MHD_Result ret = MHD_epoll (daemon,
4945 0);
4946
4948 return ret;
4949#else /* ! EPOLL_SUPPORT */
4950 return MHD_NO;
4951#endif /* ! EPOLL_SUPPORT */
4952 }
4953
4954 /* Resuming external connections when using an extern mainloop */
4957
4959 read_fd_set,
4960 write_fd_set,
4961 except_fd_set,
4962 (int) fd_setsize);
4963}
4964
4965
4994 const fd_set *read_fd_set,
4995 const fd_set *write_fd_set,
4996 const fd_set *except_fd_set)
4997{
4999 read_fd_set,
5000 write_fd_set,
5001 except_fd_set,
5002#ifdef HAS_FD_SETSIZE_OVERRIDABLE
5003 daemon->fdset_size_set_by_app ?
5004 ((unsigned int) daemon->fdset_size) :
5005 ((unsigned int) _MHD_SYS_DEFAULT_FD_SETSIZE)
5006#else /* ! HAS_FD_SETSIZE_OVERRIDABLE */
5007 ((unsigned int) _MHD_SYS_DEFAULT_FD_SETSIZE)
5008#endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */
5009 );
5010}
5011
5012
5023static enum MHD_Result
5025 int32_t millisec)
5026{
5027 int num_ready;
5028 fd_set rs;
5029 fd_set ws;
5030 fd_set es;
5031 MHD_socket maxsock;
5032 struct timeval timeout;
5033 struct timeval *tv;
5034 int err_state;
5035 MHD_socket ls;
5036
5037 timeout.tv_sec = 0;
5038 timeout.tv_usec = 0;
5039 if (daemon->shutdown)
5040 return MHD_NO;
5041 FD_ZERO (&rs);
5042 FD_ZERO (&ws);
5043 FD_ZERO (&es);
5044 maxsock = MHD_INVALID_SOCKET;
5045 err_state = MHD_NO;
5046 if ( (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) &&
5047 (MHD_NO != resume_suspended_connections (daemon)) &&
5048 (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) )
5049 millisec = 0;
5050
5051 if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon))
5052 {
5053 /* single-threaded, go over everything */
5054 if (MHD_NO ==
5055 internal_get_fdset2 (daemon,
5056 &rs,
5057 &ws,
5058 &es,
5059 &maxsock,
5060 (int) FD_SETSIZE))
5061 {
5062#ifdef HAVE_MESSAGES
5063 MHD_DLOG (daemon,
5064 _ ("Could not obtain daemon fdsets.\n"));
5065#endif
5066 err_state = MHD_YES;
5067 }
5068 }
5069 else
5070 {
5071 bool itc_added;
5072 /* accept only, have one thread per connection */
5073 itc_added = false;
5074 if (MHD_ITC_IS_VALID_ (daemon->itc))
5075 {
5076 itc_added = MHD_add_to_fd_set_ (MHD_itc_r_fd_ (daemon->itc),
5077 &rs,
5078 &maxsock,
5079 (int) FD_SETSIZE);
5080 if (! itc_added)
5081 {
5082#ifdef HAVE_MESSAGES
5083 MHD_DLOG (daemon, _ ("Could not add control inter-thread " \
5084 "communication channel FD to fdset.\n"));
5085#endif
5086 err_state = MHD_YES;
5087 }
5088 }
5089 if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) &&
5090 (! daemon->was_quiesced) )
5091 {
5092 /* Stop listening if we are at the configured connection limit */
5093 /* If we're at the connection limit, no point in really
5094 accepting new connections; however, make sure we do not miss
5095 the shutdown OR the termination of an existing connection; so
5096 only do this optimisation if we have a signaling ITC in
5097 place. */
5098 if (! itc_added ||
5099 ((daemon->connections < daemon->connection_limit) &&
5100 ! daemon->at_limit))
5101 {
5102 if (! MHD_add_to_fd_set_ (ls,
5103 &rs,
5104 &maxsock,
5105 (int) FD_SETSIZE))
5106 {
5107#ifdef HAVE_MESSAGES
5108 MHD_DLOG (daemon,
5109 _ ("Could not add listen socket to fdset.\n"));
5110#endif
5111 err_state = MHD_YES;
5112 }
5113 }
5114 }
5115 }
5116
5117 if (MHD_NO != err_state)
5118 millisec = 0;
5119 if (0 == millisec)
5120 {
5121 timeout.tv_usec = 0;
5122 timeout.tv_sec = 0;
5123 tv = &timeout;
5124 }
5125 else
5126 {
5127 uint64_t mhd_tmo;
5128 uint64_t select_tmo;
5129
5130 if ( (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon)) &&
5131 (MHD_NO != MHD_get_timeout64 (daemon, &mhd_tmo)) )
5132 {
5133 if ( (0 < millisec) &&
5134 (mhd_tmo > (uint64_t) millisec) )
5135 select_tmo = (uint64_t) millisec;
5136 else
5137 select_tmo = mhd_tmo;
5138 tv = &timeout; /* have timeout value */
5139 }
5140 else if (0 < millisec)
5141 {
5142 select_tmo = (uint64_t) millisec;
5143 tv = &timeout; /* have timeout value */
5144 }
5145 else
5146 {
5147 select_tmo = 0; /* Not actually used, silent compiler warning */
5148 tv = NULL;
5149 }
5150
5151 if (NULL != tv)
5152 { /* have timeout value */
5153#if (SIZEOF_UINT64_T - 2) >= SIZEOF_STRUCT_TIMEVAL_TV_SEC
5154 if (select_tmo / 1000 > TIMEVAL_TV_SEC_MAX)
5155 timeout.tv_sec = TIMEVAL_TV_SEC_MAX;
5156 else
5157#endif /* (SIZEOF_UINT64_T - 2) >= SIZEOF_STRUCT_TIMEVAL_TV_SEC */
5158 timeout.tv_sec = (_MHD_TIMEVAL_TV_SEC_TYPE) (select_tmo / 1000);
5159
5160 timeout.tv_usec = ((uint16_t) (select_tmo % 1000)) * ((int32_t) 1000);
5161 }
5162 }
5163 num_ready = MHD_SYS_select_ (maxsock + 1,
5164 &rs,
5165 &ws,
5166 &es,
5167 tv);
5168 if (daemon->shutdown)
5169 return MHD_NO;
5170 if (num_ready < 0)
5171 {
5172 const int err = MHD_socket_get_error_ ();
5173 if (MHD_SCKT_ERR_IS_EINTR_ (err))
5174 return (MHD_NO == err_state) ? MHD_YES : MHD_NO;
5175#ifdef HAVE_MESSAGES
5176 MHD_DLOG (daemon,
5177 _ ("select failed: %s\n"),
5178 MHD_socket_strerr_ (err));
5179#endif
5180 return MHD_NO;
5181 }
5182 if (MHD_NO != internal_run_from_select (daemon,
5183 &rs,
5184 &ws,
5185 &es,
5186 (int) FD_SETSIZE))
5187 return (MHD_NO == err_state) ? MHD_YES : MHD_NO;
5188 return MHD_NO;
5189}
5190
5191
5192#ifdef HAVE_POLL
5203static enum MHD_Result
5204MHD_poll_all (struct MHD_Daemon *daemon,
5205 int32_t millisec)
5206{
5207 unsigned int num_connections;
5208 struct MHD_Connection *pos;
5209 struct MHD_Connection *prev;
5210#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
5211 struct MHD_UpgradeResponseHandle *urh;
5212 struct MHD_UpgradeResponseHandle *urhn;
5213#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
5214
5215 mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \
5216 (MHD_thread_handle_ID_is_valid_ID_ (daemon->tid)));
5217 mhd_assert ((0 != (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \
5218 (! MHD_thread_handle_ID_is_valid_ID_ (daemon->tid)));
5219 mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \
5221
5222 if ( (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) &&
5223 (MHD_NO != resume_suspended_connections (daemon)) )
5224 millisec = 0;
5225
5226 /* count number of connections and thus determine poll set size */
5227 num_connections = 0;
5228 for (pos = daemon->connections_head; NULL != pos; pos = pos->next)
5229 num_connections++;
5230#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
5231 for (urh = daemon->urh_head; NULL != urh; urh = urh->next)
5232 num_connections += 2;
5233#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
5234 {
5235 unsigned int i;
5236 int timeout;
5237 unsigned int poll_server;
5238 int poll_listen;
5239 int poll_itc_idx;
5240 struct pollfd *p;
5241 MHD_socket ls;
5242
5243 p = MHD_calloc_ ((2 + (size_t) num_connections),
5244 sizeof (struct pollfd));
5245 if (NULL == p)
5246 {
5247#ifdef HAVE_MESSAGES
5248 MHD_DLOG (daemon,
5249 _ ("Error allocating memory: %s\n"),
5250 MHD_strerror_ (errno));
5251#endif
5252 return MHD_NO;
5253 }
5254 poll_server = 0;
5255 poll_listen = -1;
5256 if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) &&
5257 (! daemon->was_quiesced) &&
5258 (daemon->connections < daemon->connection_limit) &&
5259 (! daemon->at_limit) )
5260 {
5261 /* only listen if we are not at the connection limit */
5262 p[poll_server].fd = ls;
5263 p[poll_server].events = POLLIN;
5264 p[poll_server].revents = 0;
5265 poll_listen = (int) poll_server;
5266 poll_server++;
5267 }
5268 poll_itc_idx = -1;
5269 if (MHD_ITC_IS_VALID_ (daemon->itc))
5270 {
5271 p[poll_server].fd = MHD_itc_r_fd_ (daemon->itc);
5272 p[poll_server].events = POLLIN;
5273 p[poll_server].revents = 0;
5274 poll_itc_idx = (int) poll_server;
5275 poll_server++;
5276 }
5277
5278 timeout = get_timeout_millisec_int (daemon, millisec);
5279
5280 i = 0;
5281 for (pos = daemon->connections_tail; NULL != pos; pos = pos->prev)
5282 {
5283 p[poll_server + i].fd = pos->socket_fd;
5284 switch (pos->event_loop_info)
5285 {
5288 p[poll_server + i].events |= POLLIN | MHD_POLL_EVENTS_ERR_DISC;
5289 break;
5291 p[poll_server + i].events |= POLLOUT | MHD_POLL_EVENTS_ERR_DISC;
5292 break;
5294 p[poll_server + i].events |= MHD_POLL_EVENTS_ERR_DISC;
5295 break;
5297 timeout = 0; /* clean up "pos" immediately */
5298 break;
5299 }
5300 i++;
5301 }
5302#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
5303 for (urh = daemon->urh_tail; NULL != urh; urh = urh->prev)
5304 {
5305 urh_to_pollfd (urh, &(p[poll_server + i]));
5306 i += 2;
5307 }
5308#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
5309 if (0 == poll_server + num_connections)
5310 {
5311 free (p);
5312 return MHD_YES;
5313 }
5314 if (MHD_sys_poll_ (p,
5315 poll_server + num_connections,
5316 timeout) < 0)
5317 {
5318 const int err = MHD_socket_get_error_ ();
5319 if (MHD_SCKT_ERR_IS_EINTR_ (err))
5320 {
5321 free (p);
5322 return MHD_YES;
5323 }
5324#ifdef HAVE_MESSAGES
5325 MHD_DLOG (daemon,
5326 _ ("poll failed: %s\n"),
5327 MHD_socket_strerr_ (err));
5328#endif
5329 free (p);
5330 return MHD_NO;
5331 }
5332
5333 /* handle ITC FD */
5334 /* do it before any other processing so
5335 new signals will be processed in next loop */
5336 if ( (-1 != poll_itc_idx) &&
5337 (0 != (p[poll_itc_idx].revents & POLLIN)) )
5338 MHD_itc_clear_ (daemon->itc);
5339
5340 /* handle shutdown */
5341 if (daemon->shutdown)
5342 {
5343 free (p);
5344 return MHD_NO;
5345 }
5346
5347 /* Process externally added connection if any */
5348 if (daemon->have_new)
5350
5351 /* handle 'listen' FD */
5352 if ( (-1 != poll_listen) &&
5353 (0 != (p[poll_listen].revents & POLLIN)) )
5354 (void) MHD_accept_connection (daemon);
5355
5356 /* Reset. New value will be set when connections are processed. */
5357 daemon->data_already_pending = false;
5358
5359 i = 0;
5360 prev = daemon->connections_tail;
5361 while (NULL != (pos = prev))
5362 {
5363 prev = pos->prev;
5364 /* first, sanity checks */
5365 if (i >= num_connections)
5366 break; /* connection list changed somehow, retry later ... */
5367 if (p[poll_server + i].fd != pos->socket_fd)
5368 continue; /* fd mismatch, something else happened, retry later ... */
5369 call_handlers (pos,
5370 0 != (p[poll_server + i].revents & POLLIN),
5371 0 != (p[poll_server + i].revents & POLLOUT),
5372 0 != (p[poll_server + i].revents
5373 & MHD_POLL_REVENTS_ERR_DISC));
5374 i++;
5375 }
5376#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
5377 for (urh = daemon->urh_tail; NULL != urh; urh = urhn)
5378 {
5379 if (i >= num_connections)
5380 break; /* connection list changed somehow, retry later ... */
5381
5382 /* Get next connection here as connection can be removed
5383 * from 'daemon->urh_head' list. */
5384 urhn = urh->prev;
5385 /* Check for fd mismatch. FIXME: required for safety? */
5386 if ((p[poll_server + i].fd != urh->connection->socket_fd) ||
5387 (p[poll_server + i + 1].fd != urh->mhd.socket))
5388 break;
5389 urh_from_pollfd (urh,
5390 &p[poll_server + i]);
5391 i += 2;
5392 process_urh (urh);
5393 /* Finished forwarding? */
5394 if ( (0 == urh->in_buffer_size) &&
5395 (0 == urh->out_buffer_size) &&
5396 (0 == urh->in_buffer_used) &&
5397 (0 == urh->out_buffer_used) )
5398 {
5399 /* MHD_connection_finish_forward_() will remove connection from
5400 * 'daemon->urh_head' list. */
5401 MHD_connection_finish_forward_ (urh->connection);
5402 urh->clean_ready = true;
5403 /* If 'urh->was_closed' already was set to true, connection will be
5404 * moved immediately to cleanup list. Otherwise connection
5405 * will stay in suspended list until 'urh' will be marked
5406 * with 'was_closed' by application. */
5407 MHD_resume_connection (urh->connection);
5408 }
5409 }
5410#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
5411
5412 free (p);
5413 }
5414 return MHD_YES;
5415}
5416
5417
5425static enum MHD_Result
5426MHD_poll_listen_socket (struct MHD_Daemon *daemon,
5427 int may_block)
5428{
5429 struct pollfd p[2];
5430 int timeout;
5431 unsigned int poll_count;
5432 int poll_listen;
5433 int poll_itc_idx;
5434 MHD_socket ls;
5435
5438
5439 memset (&p,
5440 0,
5441 sizeof (p));
5442 poll_count = 0;
5443 poll_listen = -1;
5444 poll_itc_idx = -1;
5445 if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) &&
5446 (! daemon->was_quiesced) )
5447
5448 {
5449 p[poll_count].fd = ls;
5450 p[poll_count].events = POLLIN;
5451 p[poll_count].revents = 0;
5452 poll_listen = (int) poll_count;
5453 poll_count++;
5454 }
5455 if (MHD_ITC_IS_VALID_ (daemon->itc))
5456 {
5457 p[poll_count].fd = MHD_itc_r_fd_ (daemon->itc);
5458 p[poll_count].events = POLLIN;
5459 p[poll_count].revents = 0;
5460 poll_itc_idx = (int) poll_count;
5461 poll_count++;
5462 }
5463
5464 if (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME))
5465 (void) resume_suspended_connections (daemon);
5466
5467 if (MHD_NO == may_block)
5468 timeout = 0;
5469 else
5470 timeout = -1;
5471 if (0 == poll_count)
5472 return MHD_YES;
5473 if (MHD_sys_poll_ (p,
5474 poll_count,
5475 timeout) < 0)
5476 {
5477 const int err = MHD_socket_get_error_ ();
5478
5479 if (MHD_SCKT_ERR_IS_EINTR_ (err))
5480 return MHD_YES;
5481#ifdef HAVE_MESSAGES
5482 MHD_DLOG (daemon,
5483 _ ("poll failed: %s\n"),
5484 MHD_socket_strerr_ (err));
5485#endif
5486 return MHD_NO;
5487 }
5488 if ( (0 <= poll_itc_idx) &&
5489 (0 != (p[poll_itc_idx].revents & POLLIN)) )
5490 MHD_itc_clear_ (daemon->itc);
5491
5492 /* handle shutdown */
5493 if (daemon->shutdown)
5494 return MHD_NO;
5495
5496 /* Process externally added connection if any */
5497 if (daemon->have_new)
5499
5500 if ( (0 <= poll_listen) &&
5501 (0 != (p[poll_listen].revents & POLLIN)) )
5502 (void) MHD_accept_connection (daemon);
5503 return MHD_YES;
5504}
5505
5506
5507#endif
5508
5509#ifdef HAVE_POLL
5510
5518static enum MHD_Result
5519MHD_poll (struct MHD_Daemon *daemon,
5520 int may_block)
5521{
5522 if (! MHD_D_IS_USING_THREAD_PER_CONN_ (daemon))
5523 return MHD_poll_all (daemon,
5524 may_block ? -1 : 0);
5525 return MHD_poll_listen_socket (daemon,
5526 may_block);
5527}
5528
5529
5530#endif /* HAVE_POLL */
5531
5532
5533#ifdef EPOLL_SUPPORT
5534
5543#define MAX_EVENTS 128
5544
5545
5546#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
5547
5555static bool
5556is_urh_ready (struct MHD_UpgradeResponseHandle *const urh)
5557{
5558 const struct MHD_Connection *const connection = urh->connection;
5559
5560 if ( (0 == urh->in_buffer_size) &&
5561 (0 == urh->out_buffer_size) &&
5562 (0 == urh->in_buffer_used) &&
5563 (0 == urh->out_buffer_used) )
5564 return false;
5565 if (connection->daemon->shutdown)
5566 return true;
5568 & urh->app.celi)) ||
5569 (connection->tls_read_ready) ) &&
5570 (urh->in_buffer_used < urh->in_buffer_size) )
5571 return true;
5573 & urh->mhd.celi)) ||
5574 urh->was_closed) &&
5575 (urh->out_buffer_used < urh->out_buffer_size) )
5576 return true;
5577 if ( (0 != (MHD_EPOLL_STATE_WRITE_READY & urh->app.celi)) &&
5578 (urh->out_buffer_used > 0) )
5579 return true;
5580 if ( (0 != (MHD_EPOLL_STATE_WRITE_READY & urh->mhd.celi)) &&
5581 (urh->in_buffer_used > 0) )
5582 return true;
5583 return false;
5584}
5585
5586
5595static enum MHD_Result
5596run_epoll_for_upgrade (struct MHD_Daemon *daemon)
5597{
5598 struct epoll_event events[MAX_EVENTS];
5599 int num_events;
5600 struct MHD_UpgradeResponseHandle *pos;
5601 struct MHD_UpgradeResponseHandle *prev;
5602
5603#ifdef MHD_USE_THREADS
5604 mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \
5606#endif /* MHD_USE_THREADS */
5607
5608 num_events = MAX_EVENTS;
5609 while (0 != num_events)
5610 {
5611 unsigned int i;
5612 /* update event masks */
5613 num_events = epoll_wait (daemon->epoll_upgrade_fd,
5614 events,
5615 MAX_EVENTS,
5616 0);
5617 if (-1 == num_events)
5618 {
5619 const int err = MHD_socket_get_error_ ();
5620
5621 if (MHD_SCKT_ERR_IS_EINTR_ (err))
5622 return MHD_YES;
5623#ifdef HAVE_MESSAGES
5624 MHD_DLOG (daemon,
5625 _ ("Call to epoll_wait failed: %s\n"),
5626 MHD_socket_strerr_ (err));
5627#endif
5628 return MHD_NO;
5629 }
5630 for (i = 0; i < (unsigned int) num_events; i++)
5631 {
5632 struct UpgradeEpollHandle *const ueh = events[i].data.ptr;
5633 struct MHD_UpgradeResponseHandle *const urh = ueh->urh;
5634 bool new_err_state = false;
5635
5636 if (urh->clean_ready)
5637 continue;
5638
5639 /* Update ueh state based on what is ready according to epoll() */
5640 if (0 != (events[i].events & EPOLLIN))
5641 {
5642 ueh->celi |= MHD_EPOLL_STATE_READ_READY;
5643 }
5644 if (0 != (events[i].events & EPOLLOUT))
5645 {
5646 ueh->celi |= MHD_EPOLL_STATE_WRITE_READY;
5647 }
5648 if (0 != (events[i].events & EPOLLHUP))
5649 {
5651 }
5652
5653 if ( (0 == (ueh->celi & MHD_EPOLL_STATE_ERROR)) &&
5654 (0 != (events[i].events & (EPOLLERR | EPOLLPRI))) )
5655 {
5656 /* Process new error state only one time and avoid continuously
5657 * marking this connection as 'ready'. */
5658 ueh->celi |= MHD_EPOLL_STATE_ERROR;
5659 new_err_state = true;
5660 }
5661 if (! urh->in_eready_list)
5662 {
5663 if (new_err_state ||
5664 is_urh_ready (urh))
5665 {
5666 EDLL_insert (daemon->eready_urh_head,
5667 daemon->eready_urh_tail,
5668 urh);
5669 urh->in_eready_list = true;
5670 }
5671 }
5672 }
5673 }
5674 prev = daemon->eready_urh_tail;
5675 while (NULL != (pos = prev))
5676 {
5677 prev = pos->prevE;
5678 process_urh (pos);
5679 if (! is_urh_ready (pos))
5680 {
5681 EDLL_remove (daemon->eready_urh_head,
5682 daemon->eready_urh_tail,
5683 pos);
5684 pos->in_eready_list = false;
5685 }
5686 /* Finished forwarding? */
5687 if ( (0 == pos->in_buffer_size) &&
5688 (0 == pos->out_buffer_size) &&
5689 (0 == pos->in_buffer_used) &&
5690 (0 == pos->out_buffer_used) )
5691 {
5692 MHD_connection_finish_forward_ (pos->connection);
5693 pos->clean_ready = true;
5694 /* If 'pos->was_closed' already was set to true, connection
5695 * will be moved immediately to cleanup list. Otherwise
5696 * connection will stay in suspended list until 'pos' will
5697 * be marked with 'was_closed' by application. */
5698 MHD_resume_connection (pos->connection);
5699 }
5700 }
5701
5702 return MHD_YES;
5703}
5704
5705
5706#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
5707
5708
5712static const char *const epoll_itc_marker = "itc_marker";
5713
5714
5724static enum MHD_Result
5725MHD_epoll (struct MHD_Daemon *daemon,
5726 int32_t millisec)
5727{
5728#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
5729 static const char *const upgrade_marker = "upgrade_ptr";
5730#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
5731 struct MHD_Connection *pos;
5732 struct MHD_Connection *prev;
5733 struct epoll_event events[MAX_EVENTS];
5734 struct epoll_event event;
5735 int timeout_ms;
5736 int num_events;
5737 unsigned int i;
5738 MHD_socket ls;
5739#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
5740 bool run_upgraded = false;
5741#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
5742 bool need_to_accept;
5743
5744 mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \
5745 (MHD_thread_handle_ID_is_valid_ID_ (daemon->tid)));
5746 mhd_assert ((0 != (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \
5747 (! MHD_thread_handle_ID_is_valid_ID_ (daemon->tid)));
5748 mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \
5750
5751 if (-1 == daemon->epoll_fd)
5752 return MHD_NO; /* we're down! */
5753 if (daemon->shutdown)
5754 return MHD_NO;
5755 /* 'listen_socket_in_epoll', 'was_quiesced' and the epoll set itself
5756 are shared with MHD_quiesce_daemon(), which runs on the
5757 application's thread. Testing them and acting on the result has to
5758 be one atomic step. */
5759#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
5760 MHD_mutex_lock_chk_ (&daemon->epoll_listen_mutex);
5761#endif
5762 if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) &&
5763 (! daemon->was_quiesced) &&
5764 (daemon->connections < daemon->connection_limit) &&
5765 (! daemon->listen_socket_in_epoll) &&
5766 (! daemon->at_limit) )
5767 {
5768 event.events = EPOLLIN | EPOLLRDHUP;
5769 event.data.ptr = daemon;
5770 if (0 != epoll_ctl (daemon->epoll_fd,
5771 EPOLL_CTL_ADD,
5772 ls,
5773 &event))
5774 {
5775#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
5776 MHD_mutex_unlock_chk_ (&daemon->epoll_listen_mutex);
5777#endif
5778#ifdef HAVE_MESSAGES
5779 MHD_DLOG (daemon,
5780 _ ("Call to epoll_ctl failed: %s\n"),
5782#endif
5783 return MHD_NO;
5784 }
5785 daemon->listen_socket_in_epoll = true;
5786 }
5787 if ( (daemon->was_quiesced) &&
5788 (daemon->listen_socket_in_epoll) )
5789 {
5790 if (0 != epoll_ctl (daemon->epoll_fd,
5791 EPOLL_CTL_DEL,
5792 ls,
5793 NULL))
5794 MHD_PANIC ("Failed to remove listen FD from epoll set.\n");
5795 daemon->listen_socket_in_epoll = false;
5796 }
5797#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
5798 MHD_mutex_unlock_chk_ (&daemon->epoll_listen_mutex);
5799#endif
5800
5801#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
5802 if ( ( (! daemon->upgrade_fd_in_epoll) &&
5803 (-1 != daemon->epoll_upgrade_fd) ) )
5804 {
5805 event.events = EPOLLIN | EPOLLOUT | EPOLLRDHUP;
5806 event.data.ptr = _MHD_DROP_CONST (upgrade_marker);
5807 if (0 != epoll_ctl (daemon->epoll_fd,
5808 EPOLL_CTL_ADD,
5809 daemon->epoll_upgrade_fd,
5810 &event))
5811 {
5812#ifdef HAVE_MESSAGES
5813 MHD_DLOG (daemon,
5814 _ ("Call to epoll_ctl failed: %s\n"),
5816#endif
5817 return MHD_NO;
5818 }
5819 daemon->upgrade_fd_in_epoll = true;
5820 }
5821#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
5822#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
5823 MHD_mutex_lock_chk_ (&daemon->epoll_listen_mutex);
5824#endif
5825 if ( (daemon->listen_socket_in_epoll) &&
5826 ( (daemon->connections == daemon->connection_limit) ||
5827 (daemon->at_limit) ||
5828 (daemon->was_quiesced) ) )
5829 {
5830 /* we're at the connection limit, disable listen socket
5831 for event loop for now */
5832 if (0 != epoll_ctl (daemon->epoll_fd,
5833 EPOLL_CTL_DEL,
5834 ls,
5835 NULL))
5836 MHD_PANIC (_ ("Failed to remove listen FD from epoll set.\n"));
5837 daemon->listen_socket_in_epoll = false;
5838 }
5839#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
5840 MHD_mutex_unlock_chk_ (&daemon->epoll_listen_mutex);
5841#endif
5842
5843 if ( (0 != (daemon->options & MHD_TEST_ALLOW_SUSPEND_RESUME)) &&
5844 (MHD_NO != resume_suspended_connections (daemon)) )
5845 millisec = 0;
5846
5847 timeout_ms = get_timeout_millisec_int (daemon,
5848 millisec);
5849
5850 /* Reset. New value will be set when connections are processed. */
5851 /* Note: Used mostly for uniformity here as same situation is
5852 * signaled in epoll mode by non-empty eready DLL. */
5853 daemon->data_already_pending = false;
5854
5855 need_to_accept = false;
5856 /* drain 'epoll' event queue; need to iterate as we get at most
5857 MAX_EVENTS in one system call here; in practice this should
5858 pretty much mean only one round, but better an extra loop here
5859 than unfair behavior... */
5860 num_events = MAX_EVENTS;
5861 while (MAX_EVENTS == num_events)
5862 {
5863 /* update event masks */
5864 num_events = epoll_wait (daemon->epoll_fd,
5865 events,
5866 MAX_EVENTS,
5867 timeout_ms);
5868 /* A full batch may have been the last of the pending events: the next
5869 call only drains what is left, it must not wait. With edge-triggered
5870 connections nothing new arrives until they are processed, so waiting
5871 here would stall every connection until the timeout. */
5872 timeout_ms = 0;
5873 if (-1 == num_events)
5874 {
5875 const int err = MHD_socket_get_error_ ();
5876 if (MHD_SCKT_ERR_IS_EINTR_ (err))
5877 return MHD_YES;
5878#ifdef HAVE_MESSAGES
5879 MHD_DLOG (daemon,
5880 _ ("Call to epoll_wait failed: %s\n"),
5881 MHD_socket_strerr_ (err));
5882#endif
5883 return MHD_NO;
5884 }
5885 for (i = 0; i < (unsigned int) num_events; i++)
5886 {
5887 /* First, check for the values of `ptr` that would indicate
5888 that this event is not about a normal connection. */
5889 if (NULL == events[i].data.ptr)
5890 continue; /* shutdown signal! */
5891#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
5892 if (upgrade_marker == events[i].data.ptr)
5893 {
5894 /* activity on an upgraded connection, we process
5895 those in a separate epoll() */
5896 run_upgraded = true;
5897 continue;
5898 }
5899#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
5900 if (epoll_itc_marker == events[i].data.ptr)
5901 {
5902 /* It's OK to clear ITC here as all external
5903 conditions will be processed later. */
5904 MHD_itc_clear_ (daemon->itc);
5905 continue;
5906 }
5907 if (daemon == events[i].data.ptr)
5908 {
5909 /* Check for error conditions on listen socket. */
5910 /* FIXME: Initiate MHD_quiesce_daemon() to prevent busy waiting? */
5911 if (0 == (events[i].events & (EPOLLERR | EPOLLHUP)))
5912 need_to_accept = true;
5913 continue;
5914 }
5915 /* this is an event relating to a 'normal' connection,
5916 remember the event and if appropriate mark the
5917 connection as 'eready'. */
5918 pos = events[i].data.ptr;
5919 /* normal processing: update read/write data */
5920 if (0 != (events[i].events & (EPOLLPRI | EPOLLERR | EPOLLHUP)))
5921 {
5922 pos->epoll_state |= MHD_EPOLL_STATE_ERROR;
5923 if (0 == (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL))
5924 {
5925 EDLL_insert (daemon->eready_head,
5926 daemon->eready_tail,
5927 pos);
5928 pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL;
5929 }
5930 }
5931 else
5932 {
5933 if (0 != (events[i].events & EPOLLIN))
5934 {
5935 pos->epoll_state |= MHD_EPOLL_STATE_READ_READY;
5936 if ( ( (0 != (MHD_EVENT_LOOP_INFO_READ & pos->event_loop_info)) ||
5937 (pos->read_buffer_size > pos->read_buffer_offset) ) &&
5938 (0 == (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL) ) )
5939 {
5940 EDLL_insert (daemon->eready_head,
5941 daemon->eready_tail,
5942 pos);
5943 pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL;
5944 }
5945 }
5946 if (0 != (events[i].events & EPOLLOUT))
5947 {
5948 pos->epoll_state |= MHD_EPOLL_STATE_WRITE_READY;
5950 (0 == (pos->epoll_state & MHD_EPOLL_STATE_IN_EREADY_EDLL) ) )
5951 {
5952 EDLL_insert (daemon->eready_head,
5953 daemon->eready_tail,
5954 pos);
5955 pos->epoll_state |= MHD_EPOLL_STATE_IN_EREADY_EDLL;
5956 }
5957 }
5958 }
5959 }
5960 }
5961
5962 /* Process externally added connection if any */
5963 if (daemon->have_new)
5965
5966 if (need_to_accept)
5967 {
5968 unsigned int series_length = 0;
5969
5970 /* Run 'accept' until it fails or daemon at limit of connections.
5971 * Do not accept more then 10 connections at once. The rest will
5972 * be accepted on next turn (level trigger is used for listen
5973 * socket). */
5974 while ( (MHD_NO != MHD_accept_connection (daemon)) &&
5975 (series_length < 10) &&
5976 (daemon->connections < daemon->connection_limit) &&
5977 (! daemon->at_limit) )
5978 series_length++;
5979 }
5980
5981 /* Handle timed-out connections; we need to do this here
5982 as the epoll mechanism won't call the 'MHD_connection_handle_idle()' on everything,
5983 as the other event loops do. As timeouts do not get an explicit
5984 event, we need to find those connections that might have timed out
5985 here.
5986
5987 Connections with custom timeouts must all be looked at, as we
5988 do not bother to sort that (presumably very short) list. */
5989 prev = daemon->manual_timeout_tail;
5990 while (NULL != (pos = prev))
5991 {
5992 prev = pos->prevX;
5994 }
5995 /* Connections with the default timeout are sorted by prepending
5996 them to the head of the list whenever we touch the connection;
5997 thus it suffices to iterate from the tail until the first
5998 connection is NOT timed out */
5999 prev = daemon->normal_timeout_tail;
6000 while (NULL != (pos = prev))
6001 {
6002 prev = pos->prevX;
6004 if (MHD_CONNECTION_CLOSED != pos->state)
6005 break; /* sorted by timeout, no need to visit the rest! */
6006 }
6007
6008#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
6009 if (run_upgraded || (NULL != daemon->eready_urh_head))
6010 run_epoll_for_upgrade (daemon);
6011#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
6012
6013 /* process events for connections */
6014 prev = daemon->eready_tail;
6015 while (NULL != (pos = prev))
6016 {
6017 prev = pos->prevE;
6018 call_handlers (pos,
6019 0 != (pos->epoll_state & MHD_EPOLL_STATE_READ_READY),
6020 0 != (pos->epoll_state & MHD_EPOLL_STATE_WRITE_READY),
6021 0 != (pos->epoll_state & MHD_EPOLL_STATE_ERROR));
6023 (pos->epoll_state & (MHD_EPOLL_STATE_SUSPENDED
6025 {
6026 if ( ((MHD_EVENT_LOOP_INFO_READ == pos->event_loop_info) &&
6027 (0 == (pos->epoll_state & MHD_EPOLL_STATE_READ_READY)) ) ||
6029 (0 == (pos->epoll_state & MHD_EPOLL_STATE_WRITE_READY)) ) ||
6031 {
6032 EDLL_remove (daemon->eready_head,
6033 daemon->eready_tail,
6034 pos);
6035 pos->epoll_state &=
6037 }
6038 }
6039 }
6040
6041 return MHD_YES;
6042}
6043
6044
6045#endif
6046
6047
6076MHD_run (struct MHD_Daemon *daemon)
6077{
6078 if ( (daemon->shutdown) ||
6079 MHD_D_IS_USING_THREADS_ (daemon) )
6080 return MHD_NO;
6081
6082 (void) MHD_run_wait (daemon, 0);
6083 return MHD_YES;
6084}
6085
6086
6126MHD_run_wait (struct MHD_Daemon *daemon,
6127 int32_t millisec)
6128{
6129 enum MHD_Result res;
6130 if ( (daemon->shutdown) ||
6131 MHD_D_IS_USING_THREADS_ (daemon) )
6132 return MHD_NO;
6133
6135
6136 if (0 > millisec)
6137 millisec = -1;
6138#ifdef HAVE_POLL
6139 if (MHD_D_IS_USING_POLL_ (daemon))
6140 {
6141 res = MHD_poll_all (daemon, millisec);
6142 MHD_cleanup_connections (daemon);
6143 }
6144 else
6145#endif /* HAVE_POLL */
6146#ifdef EPOLL_SUPPORT
6147 if (MHD_D_IS_USING_EPOLL_ (daemon))
6148 {
6149 res = MHD_epoll (daemon, millisec);
6150 MHD_cleanup_connections (daemon);
6151 }
6152 else
6153#endif
6154 if (1)
6155 {
6157#ifdef HAS_FD_SETSIZE_OVERRIDABLE
6158#ifdef HAVE_MESSAGES
6159 if (daemon->fdset_size_set_by_app
6160 && (((int) FD_SETSIZE) < daemon->fdset_size))
6161 {
6162 MHD_DLOG (daemon,
6163 _ ("MHD_run()/MHD_run_wait() called for daemon started with " \
6164 "MHD_OPTION_APP_FD_SETSIZE option (%d). " \
6165 "The library was compiled with smaller FD_SETSIZE (%d). " \
6166 "Some socket FDs may be not processed. " \
6167 "Use MHD_run_from_select2() instead of MHD_run() or " \
6168 "do not use MHD_OPTION_APP_FD_SETSIZE option.\n"),
6169 daemon->fdset_size, (int) FD_SETSIZE);
6170 }
6171#endif /* HAVE_MESSAGES */
6172#endif /* HAS_FD_SETSIZE_OVERRIDABLE */
6173
6174 res = MHD_select (daemon, millisec);
6175 /* MHD_select does MHD_cleanup_connections already */
6176 }
6177 return res;
6178}
6179
6180
6189static void
6191{
6192 struct MHD_Daemon *daemon = pos->daemon;
6193
6194#ifdef MHD_USE_THREADS
6195 mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \
6197 mhd_assert (NULL == daemon->worker_pool);
6198#endif /* MHD_USE_THREADS */
6199
6201 {
6203 return; /* must let thread to do the rest */
6204 }
6207#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
6208 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
6209#endif
6210 mhd_assert (! pos->suspended);
6211 mhd_assert (! pos->resuming);
6212 if (pos->connection_timeout_ms == daemon->connection_timeout_ms)
6214 daemon->normal_timeout_tail,
6215 pos);
6216 else
6218 daemon->manual_timeout_tail,
6219 pos);
6221 daemon->connections_tail,
6222 pos);
6223 DLL_insert (daemon->cleanup_head,
6224 daemon->cleanup_tail,
6225 pos);
6226 daemon->data_already_pending = true;
6227#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
6228 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
6229#endif
6230}
6231
6232
6233#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
6241static MHD_THRD_RTRN_TYPE_ MHD_THRD_CALL_SPEC_
6242MHD_polling_thread (void *cls)
6243{
6244 struct MHD_Daemon *daemon = cls;
6245#ifdef HAVE_PTHREAD_SIGMASK
6246 sigset_t s_mask;
6247 int err;
6248#endif /* HAVE_PTHREAD_SIGMASK */
6249
6251#ifdef HAVE_PTHREAD_SIGMASK
6252 if ((0 == sigemptyset (&s_mask)) &&
6253 (0 == sigaddset (&s_mask, SIGPIPE)))
6254 {
6255 err = pthread_sigmask (SIG_BLOCK, &s_mask, NULL);
6256 }
6257 else
6258 err = errno;
6259 if (0 == err)
6260 daemon->sigpipe_blocked = true;
6261#ifdef HAVE_MESSAGES
6262 else
6263 MHD_DLOG (daemon,
6264 _ ("Failed to block SIGPIPE on daemon thread: %s\n"),
6265 MHD_strerror_ (errno));
6266#endif /* HAVE_MESSAGES */
6267#endif /* HAVE_PTHREAD_SIGMASK */
6268 while (! daemon->shutdown)
6269 {
6270#ifdef HAVE_POLL
6271 if (MHD_D_IS_USING_POLL_ (daemon))
6272 MHD_poll (daemon, MHD_YES);
6273 else
6274#endif /* HAVE_POLL */
6275#ifdef EPOLL_SUPPORT
6276 if (MHD_D_IS_USING_EPOLL_ (daemon))
6277 MHD_epoll (daemon, -1);
6278 else
6279#endif
6280 MHD_select (daemon, -1);
6281 MHD_cleanup_connections (daemon);
6282 }
6283
6284 /* Resume any pending for resume connections, join
6285 * all connection's threads (if any) and finally cleanup
6286 * everything. */
6287 if (0 != (MHD_TEST_ALLOW_SUSPEND_RESUME & daemon->options))
6289 close_all_connections (daemon);
6290
6291 return (MHD_THRD_RTRN_TYPE_) 0;
6292}
6293
6294
6295#endif
6296
6297
6309static size_t
6311 struct MHD_Connection *connection,
6312 char *val)
6313{
6314 bool broken;
6315 size_t res;
6316 (void) cls; /* Mute compiler warning. */
6317
6318 /* TODO: add individual parameter */
6319 if (0 <= connection->daemon->client_discipline)
6321
6322 res = MHD_str_pct_decode_in_place_lenient_ (val, &broken);
6323#ifdef HAVE_MESSAGES
6324 if (broken)
6325 {
6326 MHD_DLOG (connection->daemon,
6327 _ ("The URL encoding is broken.\n"));
6328 }
6329#endif /* HAVE_MESSAGES */
6330 return res;
6331}
6332
6333
6354_MHD_EXTERN struct MHD_Daemon *
6355MHD_start_daemon (unsigned int flags,
6356 uint16_t port,
6358 void *apc_cls,
6360 void *dh_cls,
6361 ...)
6362{
6363 struct MHD_Daemon *daemon;
6364 va_list ap;
6365
6366 va_start (ap,
6367 dh_cls);
6368 daemon = MHD_start_daemon_va (flags,
6369 port,
6370 apc,
6371 apc_cls,
6372 dh,
6373 dh_cls,
6374 ap);
6375 va_end (ap);
6376 return daemon;
6377}
6378
6379
6401{
6402#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
6403 unsigned int i;
6404#endif
6405 MHD_socket ret;
6406
6407 ret = daemon->listen_fd;
6408 if ((MHD_INVALID_SOCKET == ret)
6409 || daemon->was_quiesced)
6410 return MHD_INVALID_SOCKET;
6411 if ( (0 == (daemon->options & (MHD_USE_ITC))) &&
6412 MHD_D_IS_USING_THREADS_ (daemon) )
6413 {
6414#ifdef HAVE_MESSAGES
6415 MHD_DLOG (daemon,
6416 _ ("Using MHD_quiesce_daemon in this mode " \
6417 "requires MHD_USE_ITC.\n"));
6418#endif
6419 return MHD_INVALID_SOCKET;
6420 }
6421
6422#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
6423 if (NULL != daemon->worker_pool)
6424 for (i = 0; i < daemon->worker_pool_size; i++)
6425 {
6426 /* Each worker is an independent daemon with its own epoll set and
6427 its own lock; they are taken one at a time and never nested, so
6428 there is no ordering to get wrong. Holding the worker's lock
6429 is what stops it removing the same descriptor concurrently from
6430 its own MHD_epoll(). */
6431#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
6432 MHD_mutex_lock_chk_ (&daemon->worker_pool[i].epoll_listen_mutex);
6433#endif
6434 daemon->worker_pool[i].was_quiesced = true;
6435#ifdef EPOLL_SUPPORT
6436 if (MHD_D_IS_USING_EPOLL_ (daemon) &&
6437 (-1 != daemon->worker_pool[i].epoll_fd) &&
6438 (daemon->worker_pool[i].listen_socket_in_epoll) )
6439 {
6440 if (0 != epoll_ctl (daemon->worker_pool[i].epoll_fd,
6441 EPOLL_CTL_DEL,
6442 ret,
6443 NULL))
6444 MHD_PANIC (_ ("Failed to remove listen FD from epoll set.\n"));
6445 daemon->worker_pool[i].listen_socket_in_epoll = false;
6446 }
6447 else
6448#endif
6449 if (MHD_ITC_IS_VALID_ (daemon->worker_pool[i].itc))
6450 {
6451 if (! MHD_itc_activate_ (daemon->worker_pool[i].itc, "q"))
6452 MHD_PANIC (_ ("Failed to signal quiesce via inter-thread " \
6453 "communication channel.\n"));
6454 }
6455#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
6456 MHD_mutex_unlock_chk_ (&daemon->worker_pool[i].epoll_listen_mutex);
6457#endif
6458 }
6459#endif
6460#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
6461 MHD_mutex_lock_chk_ (&daemon->epoll_listen_mutex);
6462#endif
6463 daemon->was_quiesced = true;
6464#ifdef EPOLL_SUPPORT
6465 if (MHD_D_IS_USING_EPOLL_ (daemon) &&
6466 (-1 != daemon->epoll_fd) &&
6467 (daemon->listen_socket_in_epoll) )
6468 {
6469 if (0 != epoll_ctl (daemon->epoll_fd,
6470 EPOLL_CTL_DEL,
6471 ret,
6472 NULL))
6473 MHD_PANIC ("Failed to remove listen FD from epoll set.\n");
6474 daemon->listen_socket_in_epoll = false;
6475 }
6476#endif
6477#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
6478 MHD_mutex_unlock_chk_ (&daemon->epoll_listen_mutex);
6479#endif
6480 if ( (MHD_ITC_IS_VALID_ (daemon->itc)) &&
6481 (! MHD_itc_activate_ (daemon->itc, "q")) )
6482 MHD_PANIC (_ ("failed to signal quiesce via inter-thread " \
6483 "communication channel.\n"));
6484 return ret;
6485}
6486
6487
6493struct MHD_InterimParams_
6494{
6502 size_t num_opts;
6506 bool fdset_size_set;
6510 int fdset_size;
6514 bool listen_fd_set;
6518 MHD_socket listen_fd;
6522 bool pserver_addr_set;
6526 const struct sockaddr *pserver_addr;
6530 bool server_addr_len_set;
6534 socklen_t server_addr_len;
6535};
6536
6544typedef void
6545(*VfprintfFunctionPointerType)(void *cls,
6546 const char *format,
6547 va_list va);
6548
6549
6559static enum MHD_Result
6560parse_options_va (struct MHD_Daemon *daemon,
6561 struct MHD_InterimParams_ *params,
6562 va_list ap);
6563
6564
6574static enum MHD_Result
6576 struct MHD_InterimParams_ *params,
6577 ...)
6578{
6579 va_list ap;
6580 enum MHD_Result ret;
6581
6582 va_start (ap, params);
6583 ret = parse_options_va (daemon,
6584 params,
6585 ap);
6586 va_end (ap);
6587 return ret;
6588}
6589
6590
6591#ifdef HTTPS_SUPPORT
6595enum MHD_TlsPrioritiesBaseType
6596{
6597 MHD_TLS_PRIO_BASE_LIBMHD = 0,
6598 MHD_TLS_PRIO_BASE_SYSTEM = 1,
6599#if GNUTLS_VERSION_NUMBER >= 0x030300
6600 MHD_TLS_PRIO_BASE_DEFAULT,
6601#endif /* GNUTLS_VERSION_NUMBER >= 0x030300 */
6602 MHD_TLS_PRIO_BASE_NORMAL
6603};
6604
6605static const struct _MHD_cstr_w_len MHD_TlsBasePriotities[] = {
6606 _MHD_S_STR_W_LEN ("@LIBMICROHTTPD"),
6607 _MHD_S_STR_W_LEN ("@SYSTEM"),
6608#if GNUTLS_VERSION_NUMBER >= 0x030300
6609 {NULL, 0},
6610#endif /* GNUTLS_VERSION_NUMBER >= 0x030300 */
6611 _MHD_S_STR_W_LEN ("NORMAL")
6612};
6613
6619static bool
6620daemon_tls_priorities_init_default (struct MHD_Daemon *daemon)
6621{
6622 unsigned int p;
6623 int res;
6624
6625 mhd_assert (0 != (((unsigned int) daemon->options) & MHD_USE_TLS));
6626 mhd_assert (NULL == daemon->priority_cache);
6627 mhd_assert (MHD_TLS_PRIO_BASE_NORMAL + 1 == \
6628 sizeof(MHD_TlsBasePriotities) / sizeof(MHD_TlsBasePriotities[0]));
6629
6630 res = GNUTLS_E_SUCCESS; /* Mute compiler warning */
6631
6632 for (p = 0;
6633 p < sizeof(MHD_TlsBasePriotities) / sizeof(MHD_TlsBasePriotities[0]);
6634 ++p)
6635 {
6636 res = gnutls_priority_init (&daemon->priority_cache,
6637 MHD_TlsBasePriotities[p].str, NULL);
6638 if (GNUTLS_E_SUCCESS == res)
6639 {
6640#ifdef _DEBUG
6641#ifdef HAVE_MESSAGES
6642 switch ((enum MHD_TlsPrioritiesBaseType) p)
6643 {
6644 case MHD_TLS_PRIO_BASE_LIBMHD:
6645 MHD_DLOG (daemon,
6646 _ ("GnuTLS priorities have been initialised with " \
6647 "@LIBMICROHTTPD application-specific system-wide " \
6648 "configuration.\n") );
6649 break;
6650 case MHD_TLS_PRIO_BASE_SYSTEM:
6651 MHD_DLOG (daemon,
6652 _ ("GnuTLS priorities have been initialised with " \
6653 "@SYSTEM system-wide configuration.\n") );
6654 break;
6655#if GNUTLS_VERSION_NUMBER >= 0x030300
6656 case MHD_TLS_PRIO_BASE_DEFAULT:
6657 MHD_DLOG (daemon,
6658 _ ("GnuTLS priorities have been initialised with " \
6659 "GnuTLS default configuration.\n") );
6660 break;
6661#endif /* GNUTLS_VERSION_NUMBER >= 0x030300 */
6662 case MHD_TLS_PRIO_BASE_NORMAL:
6663 MHD_DLOG (daemon,
6664 _ ("GnuTLS priorities have been initialised with " \
6665 "NORMAL configuration.\n") );
6666 break;
6667 default:
6668 mhd_assert (0);
6669 }
6670#endif /* HAVE_MESSAGES */
6671#endif /* _DEBUG */
6672 return true;
6673 }
6674 }
6675#ifdef HAVE_MESSAGES
6676 MHD_DLOG (daemon,
6677 _ ("Failed to set GnuTLS priorities. Last error: %s\n"),
6678 gnutls_strerror (res));
6679#endif /* HAVE_MESSAGES */
6680 return false;
6681}
6682
6683
6693static bool
6694daemon_tls_priorities_init_append_inner_ (struct MHD_Daemon *daemon,
6695 const char *prio,
6696 size_t prio_len,
6697 char *buf,
6698 const size_t buf_size)
6699{
6700 unsigned int p;
6701 int res;
6702 const char *err_pos;
6703
6704 (void) buf_size; /* Mute compiler warning for non-Debug builds */
6705 mhd_assert (0 != (((unsigned int) daemon->options) & MHD_USE_TLS));
6706 mhd_assert (NULL == daemon->priority_cache);
6707 mhd_assert (MHD_TLS_PRIO_BASE_NORMAL + 1 == \
6708 sizeof(MHD_TlsBasePriotities) / sizeof(MHD_TlsBasePriotities[0]));
6709
6710 res = GNUTLS_E_SUCCESS; /* Mute compiler warning */
6711
6712 for (p = 0;
6713 p < sizeof(MHD_TlsBasePriotities) / sizeof(MHD_TlsBasePriotities[0]);
6714 ++p)
6715 {
6716
6717#if GNUTLS_VERSION_NUMBER >= 0x030300
6718#if GNUTLS_VERSION_NUMBER >= 0x030603
6719 if (NULL == MHD_TlsBasePriotities[p].str)
6720 res = gnutls_priority_init2 (&daemon->priority_cache, prio, &err_pos,
6721 GNUTLS_PRIORITY_INIT_DEF_APPEND);
6722 else
6723#else /* 0x030300 <= GNUTLS_VERSION_NUMBER
6724 && GNUTLS_VERSION_NUMBER < 0x030603 */
6725 if (NULL == MHD_TlsBasePriotities[p].str)
6726 continue; /* Skip the value, no way to append priorities to the default string */
6727 else
6728#endif /* GNUTLS_VERSION_NUMBER < 0x030603 */
6729#endif /* GNUTLS_VERSION_NUMBER >= 0x030300 */
6730 if (1)
6731 {
6732 size_t buf_pos;
6733
6734 mhd_assert (NULL != MHD_TlsBasePriotities[p].str);
6735 buf_pos = 0;
6736 memcpy (buf + buf_pos, MHD_TlsBasePriotities[p].str,
6737 MHD_TlsBasePriotities[p].len);
6738 buf_pos += MHD_TlsBasePriotities[p].len;
6739 buf[buf_pos++] = ':';
6740 memcpy (buf + buf_pos, prio, prio_len + 1);
6741#ifdef _DEBUG
6742 buf_pos += prio_len + 1;
6743 mhd_assert (buf_size >= buf_pos);
6744#endif /* _DEBUG */
6745 res = gnutls_priority_init (&daemon->priority_cache, buf, &err_pos);
6746 }
6747 if (GNUTLS_E_SUCCESS == res)
6748 {
6749#ifdef _DEBUG
6750#ifdef HAVE_MESSAGES
6751 switch ((enum MHD_TlsPrioritiesBaseType) p)
6752 {
6753 case MHD_TLS_PRIO_BASE_LIBMHD:
6754 MHD_DLOG (daemon,
6755 _ ("GnuTLS priorities have been initialised with " \
6756 "priorities specified by application appended to " \
6757 "@LIBMICROHTTPD application-specific system-wide " \
6758 "configuration.\n") );
6759 break;
6760 case MHD_TLS_PRIO_BASE_SYSTEM:
6761 MHD_DLOG (daemon,
6762 _ ("GnuTLS priorities have been initialised with " \
6763 "priorities specified by application appended to " \
6764 "@SYSTEM system-wide configuration.\n") );
6765 break;
6766#if GNUTLS_VERSION_NUMBER >= 0x030300
6767 case MHD_TLS_PRIO_BASE_DEFAULT:
6768 MHD_DLOG (daemon,
6769 _ ("GnuTLS priorities have been initialised with " \
6770 "priorities specified by application appended to " \
6771 "GnuTLS default configuration.\n") );
6772 break;
6773#endif /* GNUTLS_VERSION_NUMBER >= 0x030300 */
6774 case MHD_TLS_PRIO_BASE_NORMAL:
6775 MHD_DLOG (daemon,
6776 _ ("GnuTLS priorities have been initialised with " \
6777 "priorities specified by application appended to " \
6778 "NORMAL configuration.\n") );
6779 break;
6780 default:
6781 mhd_assert (0);
6782 }
6783#endif /* HAVE_MESSAGES */
6784#endif /* _DEBUG */
6785 return true;
6786 }
6787 }
6788#ifdef HAVE_MESSAGES
6789 MHD_DLOG (daemon,
6790 _ ("Failed to set GnuTLS priorities. Last error: %s. " \
6791 "The problematic part starts at: %s\n"),
6792 gnutls_strerror (res), err_pos);
6793#endif /* HAVE_MESSAGES */
6794 return false;
6795}
6796
6797
6798#define LOCAL_BUFF_SIZE 128
6799
6808static bool
6809daemon_tls_priorities_init_append (struct MHD_Daemon *daemon, const char *prio)
6810{
6811 static const size_t longest_base_prio = MHD_STATICSTR_LEN_ ("@LIBMICROHTTPD");
6812 bool ret;
6813 size_t prio_len;
6814 size_t buf_size_needed;
6815
6816 if (NULL == prio)
6817 return daemon_tls_priorities_init_default (daemon);
6818
6819 if (':' == prio[0])
6820 ++prio;
6821
6822 prio_len = strlen (prio);
6823
6824 buf_size_needed = longest_base_prio + 1 + prio_len + 1;
6825
6826 if (LOCAL_BUFF_SIZE >= buf_size_needed)
6827 {
6828 char local_buffer[LOCAL_BUFF_SIZE];
6829 ret = daemon_tls_priorities_init_append_inner_ (daemon, prio, prio_len,
6830 local_buffer,
6831 LOCAL_BUFF_SIZE);
6832 }
6833 else
6834 {
6835 char *allocated_buffer;
6836 allocated_buffer = (char *) malloc (buf_size_needed);
6837 if (NULL == allocated_buffer)
6838 {
6839#ifdef HAVE_MESSAGES
6840 MHD_DLOG (daemon,
6841 _ ("Error allocating memory: %s\n"),
6842 MHD_strerror_ (errno));
6843#endif
6844 return false;
6845 }
6846 ret = daemon_tls_priorities_init_append_inner_ (daemon, prio, prio_len,
6847 allocated_buffer,
6848 buf_size_needed);
6849 free (allocated_buffer);
6850 }
6851 return ret;
6852}
6853
6854
6855#endif /* HTTPS_SUPPORT */
6856
6857
6866static enum MHD_Result
6868 struct MHD_InterimParams_ *params,
6869 va_list ap)
6870{
6871 enum MHD_OPTION opt;
6872 struct MHD_OptionItem *oa;
6873 unsigned int i;
6874 unsigned int uv;
6875#ifdef HTTPS_SUPPORT
6876 const char *pstr;
6877#if GNUTLS_VERSION_MAJOR >= 3
6878 gnutls_certificate_retrieve_function2 * pgcrf;
6879#endif
6880#if GNUTLS_VERSION_NUMBER >= 0x030603
6881 gnutls_certificate_retrieve_function3 * pgcrf2;
6882#endif
6883#endif /* HTTPS_SUPPORT */
6884
6885 while (MHD_OPTION_END != (opt = (enum MHD_OPTION) va_arg (ap, int)))
6886 {
6887 /* Increase counter at start, so resulting value is number of
6888 * processed options, including any failed ones. */
6889 params->num_opts++;
6890 switch (opt)
6891 {
6893 if (1)
6894 {
6895 size_t val;
6896
6897 val = va_arg (ap,
6898 size_t);
6899 if (0 != val)
6900 {
6901 daemon->pool_size = val;
6902 if (64 > daemon->pool_size)
6903 {
6904#ifdef HAVE_MESSAGES
6905 MHD_DLOG (daemon,
6906 _ ("Warning: specified " \
6907 "MHD_OPTION_CONNECTION_MEMORY_LIMIT " \
6908 "value is too small and rounded up to 64.\n"));
6909#endif /* HAVE_MESSAGES */
6910 daemon->pool_size = 64;
6911 }
6912 if (daemon->pool_size / 4 < daemon->pool_increment)
6913 daemon->pool_increment = daemon->pool_size / 4;
6914 }
6915 }
6916 break;
6918 if (1)
6919 {
6920 size_t val;
6921
6922 val = va_arg (ap,
6923 size_t);
6924
6925 if (0 != val)
6926 {
6927 daemon->pool_increment = val;
6928 if (daemon->pool_size / 4 < daemon->pool_increment)
6929 {
6930#ifdef HAVE_MESSAGES
6931 MHD_DLOG (daemon,
6932 _ ("Warning: specified " \
6933 "MHD_OPTION_CONNECTION_MEMORY_INCREMENT value is " \
6934 "too large and rounded down to 1/4 of " \
6935 "MHD_OPTION_CONNECTION_MEMORY_LIMIT.\n"));
6936#endif /* HAVE_MESSAGES */
6937 daemon->pool_increment = daemon->pool_size / 4;
6938 }
6939 }
6940 }
6941 break;
6943 daemon->connection_limit = va_arg (ap,
6944 unsigned int);
6945 break;
6947 uv = va_arg (ap,
6948 unsigned int);
6949#if (SIZEOF_UINT64_T - 2) <= SIZEOF_UNSIGNED_INT
6950 if ((UINT64_MAX / 4000 - 1) < uv)
6951 {
6952#ifdef HAVE_MESSAGES
6953 MHD_DLOG (daemon,
6954 _ ("The specified connection timeout (%u) is too large. " \
6955 "Maximum allowed value (%" PRIu64 ") will be used " \
6956 "instead.\n"),
6957 uv,
6958 (UINT64_MAX / 4000 - 1));
6959#endif
6960 uv = UINT64_MAX / 4000 - 1;
6961 }
6962#endif /* (SIZEOF_UINT64_T - 2) <= SIZEOF_UNSIGNED_INT */
6963 daemon->connection_timeout_ms = ((uint64_t) uv) * 1000;
6964 break;
6966 daemon->notify_completed = va_arg (ap,
6968 daemon->notify_completed_cls = va_arg (ap,
6969 void *);
6970 break;
6972 daemon->notify_connection = va_arg (ap,
6974 daemon->notify_connection_cls = va_arg (ap,
6975 void *);
6976 break;
6978 daemon->per_ip_connection_limit = va_arg (ap,
6979 unsigned int);
6980 break;
6982 params->server_addr_len = va_arg (ap,
6983 socklen_t);
6984 params->server_addr_len_set = true;
6985 params->pserver_addr = va_arg (ap,
6986 const struct sockaddr *);
6987 params->pserver_addr_set = true;
6988 break;
6990 params->server_addr_len_set = false;
6991 params->pserver_addr = va_arg (ap,
6992 const struct sockaddr *);
6993 params->pserver_addr_set = true;
6994 break;
6996 daemon->uri_log_callback = va_arg (ap,
6997 LogCallback);
6998 daemon->uri_log_callback_cls = va_arg (ap,
6999 void *);
7000 break;
7002 daemon->insanity_level = (enum MHD_DisableSanityCheck)
7003 va_arg (ap,
7004 unsigned int);
7005 break;
7006#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
7008 daemon->worker_pool_size = va_arg (ap,
7009 unsigned int);
7010 if (0 == daemon->worker_pool_size)
7011 {
7012 (void) 0; /* MHD_OPTION_THREAD_POOL_SIZE ignored, do nothing */
7013 }
7014 else if (1 == daemon->worker_pool_size)
7015 {
7016#ifdef HAVE_MESSAGES
7017 MHD_DLOG (daemon,
7018 _ ("Warning: value \"1\", specified as the thread pool " \
7019 "size, is ignored. Thread pool is not used.\n"));
7020#endif
7021 daemon->worker_pool_size = 0;
7022 }
7023#if SIZEOF_UNSIGNED_INT >= (SIZEOF_SIZE_T - 2)
7024 /* Next comparison could be always false on some platforms and whole branch will
7025 * be optimized out on these platforms. On others it will be compiled into real
7026 * check. */
7027 else if (daemon->worker_pool_size >=
7028 (SIZE_MAX / sizeof (struct MHD_Daemon))) /* Compiler may warn on some platforms, ignore warning. */
7029 {
7030#ifdef HAVE_MESSAGES
7031 MHD_DLOG (daemon,
7032 _ ("Specified thread pool size (%u) too big.\n"),
7033 daemon->worker_pool_size);
7034#endif
7035 return MHD_NO;
7036 }
7037#endif /* SIZEOF_UNSIGNED_INT >= (SIZEOF_SIZE_T - 2) */
7038 else
7039 {
7040 if (! MHD_D_IS_USING_THREADS_ (daemon))
7041 {
7042#ifdef HAVE_MESSAGES
7043 MHD_DLOG (daemon,
7044 _ ("MHD_OPTION_THREAD_POOL_SIZE option is specified but "
7045 "MHD_USE_INTERNAL_POLLING_THREAD flag is not specified.\n"));
7046#endif
7047 return MHD_NO;
7048 }
7050 {
7051#ifdef HAVE_MESSAGES
7052 MHD_DLOG (daemon,
7053 _ ("Both MHD_OPTION_THREAD_POOL_SIZE option and "
7054 "MHD_USE_THREAD_PER_CONNECTION flag are specified.\n"));
7055#endif
7056 return MHD_NO;
7057 }
7058 }
7059 break;
7060#endif
7061#ifdef HTTPS_SUPPORT
7063 pstr = va_arg (ap,
7064 const char *);
7065 if (0 != (daemon->options & MHD_USE_TLS))
7066 daemon->https_mem_key = pstr;
7067#ifdef HAVE_MESSAGES
7068 else
7069 MHD_DLOG (daemon,
7070 _ ("MHD HTTPS option %d passed to MHD but " \
7071 "MHD_USE_TLS not set.\n"),
7072 opt);
7073#endif
7074 break;
7076 pstr = va_arg (ap,
7077 const char *);
7078 if (0 != (daemon->options & MHD_USE_TLS))
7079 daemon->https_key_password = pstr;
7080#ifdef HAVE_MESSAGES
7081 else
7082 MHD_DLOG (daemon,
7083 _ ("MHD HTTPS option %d passed to MHD but " \
7084 "MHD_USE_TLS not set.\n"),
7085 opt);
7086#endif
7087 break;
7089 pstr = va_arg (ap,
7090 const char *);
7091 if (0 != (daemon->options & MHD_USE_TLS))
7092 daemon->https_mem_cert = pstr;
7093#ifdef HAVE_MESSAGES
7094 else
7095 MHD_DLOG (daemon,
7096 _ ("MHD HTTPS option %d passed to MHD but " \
7097 "MHD_USE_TLS not set.\n"),
7098 opt);
7099#endif
7100 break;
7102 pstr = va_arg (ap,
7103 const char *);
7104 if (0 != (daemon->options & MHD_USE_TLS))
7105 daemon->https_mem_trust = pstr;
7106#ifdef HAVE_MESSAGES
7107 else
7108 MHD_DLOG (daemon,
7109 _ ("MHD HTTPS option %d passed to MHD but " \
7110 "MHD_USE_TLS not set.\n"),
7111 opt);
7112#endif
7113 break;
7115 daemon->cred_type = (gnutls_credentials_type_t) va_arg (ap,
7116 int);
7117 break;
7119 pstr = va_arg (ap,
7120 const char *);
7121 if (0 != (daemon->options & MHD_USE_TLS))
7122 {
7123 gnutls_datum_t dhpar;
7124 size_t pstr_len;
7125
7126 if (gnutls_dh_params_init (&daemon->https_mem_dhparams) < 0)
7127 {
7128#ifdef HAVE_MESSAGES
7129 MHD_DLOG (daemon,
7130 _ ("Error initializing DH parameters.\n"));
7131#endif
7132 return MHD_NO;
7133 }
7134 dhpar.data = (unsigned char *) _MHD_DROP_CONST (pstr);
7135 pstr_len = strlen (pstr);
7136 if (UINT_MAX < pstr_len)
7137 {
7138#ifdef HAVE_MESSAGES
7139 MHD_DLOG (daemon,
7140 _ ("Diffie-Hellman parameters string too long.\n"));
7141#endif
7142 return MHD_NO;
7143 }
7144 dhpar.size = (unsigned int) pstr_len;
7145 if (gnutls_dh_params_import_pkcs3 (daemon->https_mem_dhparams,
7146 &dhpar,
7147 GNUTLS_X509_FMT_PEM) < 0)
7148 {
7149#ifdef HAVE_MESSAGES
7150 MHD_DLOG (daemon,
7151 _ ("Bad Diffie-Hellman parameters format.\n"));
7152#endif
7153 gnutls_dh_params_deinit (daemon->https_mem_dhparams);
7154 return MHD_NO;
7155 }
7156 daemon->have_dhparams = true;
7157 }
7158#ifdef HAVE_MESSAGES
7159 else
7160 MHD_DLOG (daemon,
7161 _ ("MHD HTTPS option %d passed to MHD but " \
7162 "MHD_USE_TLS not set.\n"),
7163 opt);
7164#endif
7165 break;
7168 pstr = va_arg (ap,
7169 const char *);
7170 if (0 != (daemon->options & MHD_USE_TLS))
7171 {
7172 if (NULL != daemon->priority_cache)
7173 gnutls_priority_deinit (daemon->priority_cache);
7174
7175 if (MHD_OPTION_HTTPS_PRIORITIES == opt)
7176 {
7177 int init_res;
7178 const char *err_pos;
7179 init_res = gnutls_priority_init (&daemon->priority_cache,
7180 pstr,
7181 &err_pos);
7182 if (GNUTLS_E_SUCCESS != init_res)
7183 {
7184#ifdef HAVE_MESSAGES
7185 MHD_DLOG (daemon,
7186 _ ("Setting priorities to '%s' failed: %s " \
7187 "The problematic part starts at: %s\n"),
7188 pstr,
7189 gnutls_strerror (init_res),
7190 err_pos);
7191#endif
7192 daemon->priority_cache = NULL;
7193 return MHD_NO;
7194 }
7195 }
7196 else
7197 {
7198 /* The cache has been deinited */
7199 daemon->priority_cache = NULL;
7200 if (! daemon_tls_priorities_init_append (daemon, pstr))
7201 return MHD_NO;
7202 }
7203 }
7204#ifdef HAVE_MESSAGES
7205 else
7206 MHD_DLOG (daemon,
7207 _ ("MHD HTTPS option %d passed to MHD but " \
7208 "MHD_USE_TLS not set.\n"),
7209 opt);
7210#endif
7211 break;
7213#if GNUTLS_VERSION_MAJOR < 3
7214#ifdef HAVE_MESSAGES
7215 MHD_DLOG (daemon,
7216 _ ("MHD_OPTION_HTTPS_CERT_CALLBACK requires building " \
7217 "MHD with GnuTLS >= 3.0.\n"));
7218#endif
7219 return MHD_NO;
7220#else
7221 pgcrf = va_arg (ap,
7222 gnutls_certificate_retrieve_function2 *);
7223 if (0 != (daemon->options & MHD_USE_TLS))
7224 daemon->cert_callback = pgcrf;
7225#ifdef HAVE_MESSAGES
7226 else
7227 MHD_DLOG (daemon,
7228 _ ("MHD HTTPS option %d passed to MHD but " \
7229 "MHD_USE_TLS not set.\n"),
7230 opt);
7231#endif /* HAVE_MESSAGES */
7232 break;
7233#endif
7235#if GNUTLS_VERSION_NUMBER < 0x030603
7236#ifdef HAVE_MESSAGES
7237 MHD_DLOG (daemon,
7238 _ ("MHD_OPTION_HTTPS_CERT_CALLBACK2 requires building " \
7239 "MHD with GnuTLS >= 3.6.3.\n"));
7240#endif
7241 return MHD_NO;
7242#else
7243 pgcrf2 = va_arg (ap,
7244 gnutls_certificate_retrieve_function3 *);
7245 if (0 != (daemon->options & MHD_USE_TLS))
7246 daemon->cert_callback2 = pgcrf2;
7247#ifdef HAVE_MESSAGES
7248 else
7249 MHD_DLOG (daemon,
7250 _ ("MHD HTTPS option %d passed to MHD but " \
7251 "MHD_USE_TLS not set.\n"),
7252 opt);
7253#endif /* HAVE_MESSAGES */
7254 break;
7255#endif
7256#endif /* HTTPS_SUPPORT */
7257#ifdef DAUTH_SUPPORT
7260 daemon->digest_auth_rand_size = va_arg (ap,
7261 size_t);
7262 daemon->digest_auth_random = va_arg (ap,
7263 const char *);
7265 /* Set to some non-NULL value just to indicate that copy is required. */
7266 daemon->digest_auth_random_copy = daemon;
7267 else
7268 daemon->digest_auth_random_copy = NULL;
7269 break;
7271 daemon->nonce_nc_size = va_arg (ap,
7272 unsigned int);
7273 break;
7275 daemon->dauth_bind_type = va_arg (ap,
7276 unsigned int);
7277 if (0 != (daemon->dauth_bind_type & MHD_DAUTH_BIND_NONCE_URI_PARAMS))
7278 daemon->dauth_bind_type |= MHD_DAUTH_BIND_NONCE_URI;
7279 break;
7281 if (1)
7282 {
7283 unsigned int val;
7284 val = va_arg (ap,
7285 unsigned int);
7286 if (0 != val)
7287 daemon->dauth_def_nonce_timeout = val;
7288 }
7289 break;
7291 if (1)
7292 {
7293 uint32_t val;
7294 val = va_arg (ap,
7295 uint32_t);
7296 if (0 != val)
7297 daemon->dauth_def_max_nc = val;
7298 }
7299 break;
7300#else /* ! DAUTH_SUPPORT */
7307#ifdef HAVE_MESSAGES
7308 MHD_DLOG (daemon,
7309 _ ("Digest Auth is disabled for this build " \
7310 "of GNU libmicrohttpd.\n"));
7311#endif /* HAVE_MESSAGES */
7312 return MHD_NO;
7313#endif /* ! DAUTH_SUPPORT */
7315 params->listen_fd = va_arg (ap,
7316 MHD_socket);
7317 params->listen_fd_set = true;
7318 break;
7320#ifdef HAVE_MESSAGES
7321 daemon->custom_error_log = va_arg (ap,
7323 daemon->custom_error_log_cls = va_arg (ap,
7324 void *);
7325 if (1 != params->num_opts)
7326 MHD_DLOG (daemon,
7327 _ ("MHD_OPTION_EXTERNAL_LOGGER is not the first option "
7328 "specified for the daemon. Some messages may be "
7329 "printed by the standard MHD logger.\n"));
7330
7331#else
7332 (void) va_arg (ap,
7334 (void) va_arg (ap,
7335 void *);
7336#endif
7337 break;
7338#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
7340 daemon->thread_stack_size = va_arg (ap,
7341 size_t);
7342 break;
7343#endif
7345#ifdef TCP_FASTOPEN
7346 daemon->fastopen_queue_size = va_arg (ap,
7347 unsigned int);
7348 break;
7349#else /* ! TCP_FASTOPEN */
7350#ifdef HAVE_MESSAGES
7351 MHD_DLOG (daemon,
7352 _ ("TCP fastopen is not supported on this platform.\n"));
7353#endif /* HAVE_MESSAGES */
7354 return MHD_NO;
7355#endif /* ! TCP_FASTOPEN */
7357 daemon->listening_address_reuse = va_arg (ap,
7358 unsigned int) ? 1 : -1;
7359 break;
7361 daemon->listen_backlog_size = va_arg (ap,
7362 unsigned int);
7363 break;
7365 daemon->client_discipline = va_arg (ap, int); /* Temporal assignment */
7366 /* Map to correct value */
7367 if (-1 >= daemon->client_discipline)
7368 daemon->client_discipline = -3;
7369 else if (1 <= daemon->client_discipline)
7370 daemon->client_discipline = 1;
7371#ifdef HAVE_MESSAGES
7372 if ( (0 != (daemon->options & MHD_USE_PEDANTIC_CHECKS)) &&
7373 (1 != daemon->client_discipline) )
7374 {
7375 MHD_DLOG (daemon,
7376 _ ("Flag MHD_USE_PEDANTIC_CHECKS is ignored because "
7377 "another behaviour is specified by "
7378 "MHD_OPTION_STRICT_CLIENT.\n"));
7379 }
7380#endif /* HAVE_MESSAGES */
7381 break;
7383 daemon->client_discipline = va_arg (ap, int);
7384#ifdef HAVE_MESSAGES
7385 if ( (0 != (daemon->options & MHD_USE_PEDANTIC_CHECKS)) &&
7386 (1 != daemon->client_discipline) )
7387 {
7388 MHD_DLOG (daemon,
7389 _ ("Flag MHD_USE_PEDANTIC_CHECKS is ignored because "
7390 "another behaviour is specified by "
7391 "MHD_OPTION_CLIENT_DISCIPLINE_LVL.\n"));
7392 }
7393#endif /* HAVE_MESSAGES */
7394 break;
7396 daemon->allow_bzero_in_url = va_arg (ap, int);
7397 if ((0 > daemon->allow_bzero_in_url) ||
7398 (2 < daemon->allow_bzero_in_url))
7399 daemon->allow_bzero_in_url = 1;
7400 break;
7401 case MHD_OPTION_ARRAY:
7402 params->num_opts--; /* Do not count MHD_OPTION_ARRAY */
7403 oa = va_arg (ap, struct MHD_OptionItem *);
7404 i = 0;
7405 while (MHD_OPTION_END != (opt = oa[i].option))
7406 {
7407 switch (opt)
7408 {
7409 /* all options taking 'size_t' */
7413 if (MHD_NO == parse_options (daemon,
7414 params,
7415 opt,
7416 (size_t) oa[i].value,
7418 return MHD_NO;
7419 break;
7420 /* all options taking 'unsigned int' */
7432 if (MHD_NO == parse_options (daemon,
7433 params,
7434 opt,
7435 (unsigned int) oa[i].value,
7437 return MHD_NO;
7438 break;
7439 /* all options taking 'enum' */
7441#ifdef HTTPS_SUPPORT
7442 if (MHD_NO == parse_options (daemon,
7443 params,
7444 opt,
7445 (gnutls_credentials_type_t) oa[i].value,
7447#endif /* HTTPS_SUPPORT */
7448 return MHD_NO;
7449 break;
7450 /* all options taking 'MHD_socket' */
7452 if (MHD_NO == parse_options (daemon,
7453 params,
7454 opt,
7455 (MHD_socket) oa[i].value,
7457 return MHD_NO;
7458 break;
7459 /* all options taking 'int' */
7466 if (MHD_NO == parse_options (daemon,
7467 params,
7468 opt,
7469 (int) oa[i].value,
7471 return MHD_NO;
7472 break;
7473 /* all options taking 'uint32_t' */
7475 if (MHD_NO == parse_options (daemon,
7476 params,
7477 opt,
7478 (uint32_t) oa[i].value,
7480 return MHD_NO;
7481 break;
7482 /* all options taking one pointer */
7491 case MHD_OPTION_ARRAY:
7494 if (MHD_NO == parse_options (daemon,
7495 params,
7496 opt,
7497 oa[i].ptr_value,
7499 return MHD_NO;
7500 break;
7501 /* all options taking two pointers */
7508 if (MHD_NO == parse_options (daemon,
7509 params,
7510 opt,
7511 (void *) oa[i].value,
7512 oa[i].ptr_value,
7514 return MHD_NO;
7515 break;
7516 /* options taking size_t-number followed by pointer */
7519 if (MHD_NO == parse_options (daemon,
7520 params,
7521 opt,
7522 (size_t) oa[i].value,
7523 oa[i].ptr_value,
7525 return MHD_NO;
7526 break;
7527 /* options taking socklen_t-number followed by pointer */
7529 if (MHD_NO == parse_options (daemon,
7530 params,
7531 opt,
7532 (socklen_t) oa[i].value,
7533 oa[i].ptr_value,
7535 return MHD_NO;
7536 break;
7537 case MHD_OPTION_END: /* Not possible */
7538 default:
7539 return MHD_NO;
7540 }
7541 i++;
7542 }
7543 break;
7545 daemon->unescape_callback = va_arg (ap,
7547 daemon->unescape_callback_cls = va_arg (ap,
7548 void *);
7549 break;
7550#ifdef HTTPS_SUPPORT
7552#if GNUTLS_VERSION_MAJOR >= 3
7553 daemon->cred_callback = va_arg (ap,
7555 daemon->cred_callback_cls = va_arg (ap,
7556 void *);
7557 break;
7558#else
7559 MHD_DLOG (daemon,
7560 _ ("MHD HTTPS option %d passed to MHD compiled " \
7561 "without GNUtls >= 3.\n"),
7562 opt);
7563 return MHD_NO;
7564#endif
7565#endif /* HTTPS_SUPPORT */
7567 if (! MHD_D_IS_USING_THREADS_ (daemon))
7568 daemon->sigpipe_blocked = ( (va_arg (ap,
7569 int)) != 0);
7570 else
7571 {
7572 (void) va_arg (ap,
7573 int);
7574 }
7575 break;
7577#ifdef HTTPS_SUPPORT
7578 daemon->disable_alpn = (va_arg (ap,
7579 int) != 0);
7580#else /* ! HTTPS_SUPPORT */
7581 (void) va_arg (ap, int);
7582#endif /* ! HTTPS_SUPPORT */
7583#ifdef HAVE_MESSAGES
7584 if (0 == (daemon->options & MHD_USE_TLS))
7585 MHD_DLOG (daemon,
7586 _ ("MHD HTTPS option %d passed to MHD " \
7587 "but MHD_USE_TLS not set.\n"),
7588 (int) opt);
7589#endif /* HAVE_MESSAGES */
7590 break;
7592 params->fdset_size_set = true;
7593 params->fdset_size = va_arg (ap,
7594 int);
7595 break;
7596#ifndef HTTPS_SUPPORT
7608#ifdef HAVE_MESSAGES
7609 MHD_DLOG (daemon,
7610 _ ("MHD HTTPS option %d passed to MHD "
7611 "compiled without HTTPS support.\n"),
7612 opt);
7613#endif
7614 return MHD_NO;
7615#endif /* HTTPS_SUPPORT */
7616 case MHD_OPTION_END: /* Not possible */
7617 default:
7618#ifdef HAVE_MESSAGES
7619 MHD_DLOG (daemon,
7620 _ ("Invalid option %d! (Did you terminate "
7621 "the list with MHD_OPTION_END?).\n"),
7622 opt);
7623#endif
7624 return MHD_NO;
7625 }
7626 }
7627 return MHD_YES;
7628}
7629
7630
7631#ifdef EPOLL_SUPPORT
7632static int
7633setup_epoll_fd (struct MHD_Daemon *daemon)
7634{
7635 int fd;
7636
7637#ifndef HAVE_MESSAGES
7638 (void) daemon; /* Mute compiler warning. */
7639#endif /* ! HAVE_MESSAGES */
7640
7641#ifdef USE_EPOLL_CREATE1
7642 fd = epoll_create1 (EPOLL_CLOEXEC);
7643#else /* ! USE_EPOLL_CREATE1 */
7644 fd = epoll_create (MAX_EVENTS);
7645#endif /* ! USE_EPOLL_CREATE1 */
7646 if (MHD_INVALID_SOCKET == fd)
7647 {
7648#ifdef HAVE_MESSAGES
7649 MHD_DLOG (daemon,
7650 _ ("Call to epoll_create1 failed: %s\n"),
7652#endif
7653 return MHD_INVALID_SOCKET;
7654 }
7655#if ! defined(USE_EPOLL_CREATE1)
7657 {
7658#ifdef HAVE_MESSAGES
7659 MHD_DLOG (daemon,
7660 _ ("Failed to set noninheritable mode on epoll FD.\n"));
7661#endif
7662 }
7663#endif /* ! USE_EPOLL_CREATE1 */
7664 return fd;
7665}
7666
7667
7676static enum MHD_Result
7677setup_epoll_to_listen (struct MHD_Daemon *daemon)
7678{
7679 struct epoll_event event;
7680 MHD_socket ls;
7681
7684 mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \
7685 (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) || \
7686 MHD_ITC_IS_VALID_ (daemon->itc) );
7687 daemon->epoll_fd = setup_epoll_fd (daemon);
7688 if (! MHD_D_IS_USING_THREADS_ (daemon)
7689 && (0 != (daemon->options & MHD_USE_AUTO)))
7690 {
7691 /* Application requested "MHD_USE_AUTO", probably MHD_get_fdset() will be
7692 used.
7693 Make sure that epoll FD is suitable for fd_set.
7694 Actually, MHD_get_fdset() is allowed for MHD_USE_EPOLL direct,
7695 but most probably direct requirement for MHD_USE_EPOLL means that
7696 epoll FD will be used directly. This logic is fuzzy, but better
7697 than nothing with current MHD API. */
7698 if (! MHD_D_DOES_SCKT_FIT_FDSET_ (daemon->epoll_fd, daemon))
7699 {
7700#ifdef HAVE_MESSAGES
7701 MHD_DLOG (daemon,
7702 _ ("The epoll FD is too large to be used with fd_set.\n"));
7703#endif /* HAVE_MESSAGES */
7704 return MHD_NO;
7705 }
7706 }
7707 if (-1 == daemon->epoll_fd)
7708 return MHD_NO;
7709#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
7710 if (0 != (MHD_ALLOW_UPGRADE & daemon->options))
7711 {
7712 daemon->epoll_upgrade_fd = setup_epoll_fd (daemon);
7713 if (MHD_INVALID_SOCKET == daemon->epoll_upgrade_fd)
7714 return MHD_NO;
7715 }
7716#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
7717 if ( (MHD_INVALID_SOCKET != (ls = daemon->listen_fd)) &&
7718 (! daemon->was_quiesced) )
7719 {
7720 event.events = EPOLLIN | EPOLLRDHUP;
7721 event.data.ptr = daemon;
7722 if (0 != epoll_ctl (daemon->epoll_fd,
7723 EPOLL_CTL_ADD,
7724 ls,
7725 &event))
7726 {
7727#ifdef HAVE_MESSAGES
7728 MHD_DLOG (daemon,
7729 _ ("Call to epoll_ctl failed: %s\n"),
7731#endif
7732 return MHD_NO;
7733 }
7734 daemon->listen_socket_in_epoll = true;
7735 }
7736
7737 if (MHD_ITC_IS_VALID_ (daemon->itc))
7738 {
7739 event.events = EPOLLIN | EPOLLRDHUP;
7740 event.data.ptr = _MHD_DROP_CONST (epoll_itc_marker);
7741 if (0 != epoll_ctl (daemon->epoll_fd,
7742 EPOLL_CTL_ADD,
7743 MHD_itc_r_fd_ (daemon->itc),
7744 &event))
7745 {
7746#ifdef HAVE_MESSAGES
7747 MHD_DLOG (daemon,
7748 _ ("Call to epoll_ctl failed: %s\n"),
7750#endif
7751 return MHD_NO;
7752 }
7753 }
7754 return MHD_YES;
7755}
7756
7757
7758#endif
7759
7760
7772static bool
7774 const struct sockaddr **ppsockaddr,
7775 socklen_t *psockaddr_len,
7776 struct MHD_InterimParams_ *params)
7777{
7778 if (params->fdset_size_set)
7779 {
7780 if (0 >= params->fdset_size)
7781 {
7782#ifdef HAVE_MESSAGES
7783 MHD_DLOG (d,
7784 _ ("MHD_OPTION_APP_FD_SETSIZE value (%d) is not positive.\n"),
7785 params->fdset_size);
7786#endif /* HAVE_MESSAGES */
7787 return false;
7788 }
7790 {
7791#ifdef HAVE_MESSAGES
7792 MHD_DLOG (d,
7793 _ ("MHD_OPTION_APP_FD_SETSIZE is ignored for daemon started " \
7794 "with MHD_USE_INTERNAL_POLLING_THREAD.\n"));
7795#endif /* HAVE_MESSAGES */
7796 (void) 0;
7797 }
7798 else if (MHD_D_IS_USING_POLL_ (d))
7799 {
7800#ifdef HAVE_MESSAGES
7801 MHD_DLOG (d,
7802 _ ("MHD_OPTION_APP_FD_SETSIZE is ignored for daemon started " \
7803 "with MHD_USE_POLL.\n"));
7804#endif /* HAVE_MESSAGES */
7805 (void) 0;
7806 }
7807 else
7808 { /* The daemon without internal threads, external sockets polling */
7809#ifndef HAS_FD_SETSIZE_OVERRIDABLE
7810 if (((int) FD_SETSIZE) != params->fdset_size)
7811 {
7812#ifdef HAVE_MESSAGES
7813 MHD_DLOG (d,
7814 _ ("MHD_OPTION_APP_FD_SETSIZE value (%d) does not match " \
7815 "the platform FD_SETSIZE value (%d) and this platform " \
7816 "does not support overriding of FD_SETSIZE.\n"),
7817 params->fdset_size, (int) FD_SETSIZE);
7818#endif /* HAVE_MESSAGES */
7819 return false;
7820 }
7821#else /* HAS_FD_SETSIZE_OVERRIDABLE */
7822 d->fdset_size = params->fdset_size;
7823 d->fdset_size_set_by_app = true;
7824#endif /* HAS_FD_SETSIZE_OVERRIDABLE */
7825 }
7826 }
7827
7828 if (params->listen_fd_set)
7829 {
7830 if (MHD_INVALID_SOCKET == params->listen_fd)
7831 {
7832 (void) 0; /* Use MHD-created socket */
7833 }
7834#ifdef HAS_SIGNED_SOCKET
7835 else if (0 > params->listen_fd)
7836 {
7837#ifdef HAVE_MESSAGES
7838 MHD_DLOG (d,
7839 _ ("The value provided for MHD_OPTION_LISTEN_SOCKET " \
7840 "is invalid.\n"));
7841#endif /* HAVE_MESSAGES */
7842 return false;
7843 }
7844#endif /* HAS_SIGNED_SOCKET */
7845 else if (0 != (d->options & MHD_USE_NO_LISTEN_SOCKET))
7846 {
7847#ifdef HAVE_MESSAGES
7848 MHD_DLOG (d,
7849 _ ("MHD_OPTION_LISTEN_SOCKET specified for daemon "
7850 "with MHD_USE_NO_LISTEN_SOCKET flag set.\n"));
7851#endif /* HAVE_MESSAGES */
7852 (void) MHD_socket_close_ (params->listen_fd);
7853 return false;
7854 }
7855 else
7856 {
7857 d->listen_fd = params->listen_fd;
7859#ifdef MHD_USE_GETSOCKNAME
7860 d->port = 0; /* Force use of autodetection */
7861#endif /* MHD_USE_GETSOCKNAME */
7862 }
7863 }
7864
7865 mhd_assert (! params->server_addr_len_set || params->pserver_addr_set);
7866 if (params->pserver_addr_set)
7867 {
7868 if (NULL == params->pserver_addr)
7869 {
7870 /* The size must be zero if set */
7871 if (params->server_addr_len_set && (0 != params->server_addr_len))
7872 return false;
7873 /* Ignore parameter if it is NULL */
7874 }
7875 else if (MHD_INVALID_SOCKET != d->listen_fd)
7876 {
7877#ifdef HAVE_MESSAGES
7878 MHD_DLOG (d,
7879 _ ("MHD_OPTION_LISTEN_SOCKET cannot be used together with " \
7880 "MHD_OPTION_SOCK_ADDR_LEN or MHD_OPTION_SOCK_ADDR.\n"));
7881#endif /* HAVE_MESSAGES */
7882 return false;
7883 }
7884 else if (0 != (d->options & MHD_USE_NO_LISTEN_SOCKET))
7885 {
7886#ifdef HAVE_MESSAGES
7887 MHD_DLOG (d,
7888 _ ("MHD_OPTION_SOCK_ADDR_LEN or MHD_OPTION_SOCK_ADDR " \
7889 "specified for daemon with MHD_USE_NO_LISTEN_SOCKET " \
7890 "flag set.\n"));
7891#endif /* HAVE_MESSAGES */
7892 if (MHD_INVALID_SOCKET != d->listen_fd)
7893 {
7894 (void) MHD_socket_close_ (params->listen_fd);
7895 params->listen_fd = MHD_INVALID_SOCKET;
7896 }
7897 return false;
7898 }
7899 else
7900 {
7901 *ppsockaddr = params->pserver_addr;
7902 if (params->server_addr_len_set)
7903 {
7904 /* The size must be non-zero if set */
7905 if (0 == params->server_addr_len)
7906 return false;
7907 *psockaddr_len = params->server_addr_len;
7908 }
7909 else
7910 *psockaddr_len = 0;
7911 }
7912 }
7913 return true;
7914}
7915
7916
7938_MHD_EXTERN struct MHD_Daemon *
7939MHD_start_daemon_va (unsigned int flags,
7940 uint16_t port,
7942 void *apc_cls,
7944 void *dh_cls,
7945 va_list ap)
7946{
7947 const MHD_SCKT_OPT_BOOL_ on = 1;
7948 struct MHD_Daemon *daemon;
7949 const struct sockaddr *pservaddr = NULL;
7950 socklen_t addrlen;
7951#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
7952 unsigned int i;
7953#endif
7954 enum MHD_FLAG eflags; /* same type as in MHD_Daemon */
7955 enum MHD_FLAG *pflags;
7956 struct MHD_InterimParams_ *interim_params;
7957
7959 eflags = (enum MHD_FLAG) flags;
7960 pflags = &eflags;
7961
7962 if (0 != (*pflags & MHD_USE_THREAD_PER_CONNECTION))
7963 *pflags |= MHD_USE_INTERNAL_POLLING_THREAD; /* Force enable, log warning later if needed */
7964
7965#ifndef HAVE_INET6
7966 if (0 != (*pflags & MHD_USE_IPv6))
7967 return NULL;
7968#endif
7969#ifndef HAVE_POLL
7970 if (0 != (*pflags & MHD_USE_POLL))
7971 return NULL;
7972#endif
7973#ifndef EPOLL_SUPPORT
7974 if (0 != (*pflags & MHD_USE_EPOLL))
7975 return NULL;
7976#endif /* ! EPOLL_SUPPORT */
7977#ifndef HTTPS_SUPPORT
7978 if (0 != (*pflags & MHD_USE_TLS))
7979 return NULL;
7980#endif /* ! HTTPS_SUPPORT */
7981#ifndef TCP_FASTOPEN
7982 if (0 != (*pflags & MHD_USE_TCP_FASTOPEN))
7983 return NULL;
7984#endif
7985 if (0 != (*pflags & MHD_ALLOW_UPGRADE))
7986 {
7987#ifdef UPGRADE_SUPPORT
7988 *pflags |= MHD_ALLOW_SUSPEND_RESUME;
7989#else /* ! UPGRADE_SUPPORT */
7990 return NULL;
7991#endif /* ! UPGRADE_SUPPORT */
7992 }
7993#ifdef MHD_USE_THREADS
7996 & *pflags))
7997 return NULL; /* Cannot be thread-unsafe with multiple threads */
7998#else /* ! MHD_USE_THREADS */
7999 if (0 != (*pflags & MHD_USE_INTERNAL_POLLING_THREAD))
8000 return NULL;
8001#endif /* ! MHD_USE_THREADS */
8002
8003 if (NULL == dh)
8004 return NULL;
8005
8006 /* Check for invalid combinations of flags. */
8007 if ((0 != (*pflags & MHD_USE_POLL)) && (0 != (*pflags & MHD_USE_EPOLL)))
8008 return NULL;
8009 if ((0 != (*pflags & MHD_USE_EPOLL)) &&
8010 (0 != (*pflags & MHD_USE_THREAD_PER_CONNECTION)))
8011 return NULL;
8012 if ((0 != (*pflags & MHD_USE_POLL)) &&
8013 (0 == (*pflags & (MHD_USE_INTERNAL_POLLING_THREAD
8015 return NULL;
8016 if ((0 != (*pflags & MHD_USE_AUTO)) &&
8017 (0 != (*pflags & (MHD_USE_POLL | MHD_USE_EPOLL))))
8018 return NULL;
8019
8020 if (0 != (*pflags & MHD_USE_AUTO))
8021 {
8022#if defined(EPOLL_SUPPORT) && defined(HAVE_POLL)
8023 if (0 != (*pflags & MHD_USE_THREAD_PER_CONNECTION))
8024 *pflags |= MHD_USE_POLL;
8025 else
8026 *pflags |= MHD_USE_EPOLL; /* Including "external select" mode */
8027#elif defined(HAVE_POLL)
8028 if (0 != (*pflags & MHD_USE_INTERNAL_POLLING_THREAD))
8029 *pflags |= MHD_USE_POLL; /* Including thread-per-connection */
8030#elif defined(EPOLL_SUPPORT)
8031 if (0 == (*pflags & MHD_USE_THREAD_PER_CONNECTION))
8032 *pflags |= MHD_USE_EPOLL; /* Including "external select" mode */
8033#else
8034 /* No choice: use select() for any mode - do not modify flags */
8035#endif
8036 }
8037
8038 if (0 != (*pflags & MHD_USE_NO_THREAD_SAFETY))
8039 *pflags = (*pflags & ~((enum MHD_FLAG) MHD_USE_ITC)); /* useless in single-threaded environment */
8040 else if (0 != (*pflags & MHD_USE_INTERNAL_POLLING_THREAD))
8041 {
8042#ifdef HAVE_LISTEN_SHUTDOWN
8043 if (0 != (*pflags & MHD_USE_NO_LISTEN_SOCKET))
8044#endif
8045 *pflags |= MHD_USE_ITC; /* yes, must use ITC to signal thread */
8046 }
8047
8048 if (NULL == (daemon = MHD_calloc_ (1, sizeof (struct MHD_Daemon))))
8049 return NULL;
8050 interim_params = (struct MHD_InterimParams_ *) \
8051 MHD_calloc_ (1, sizeof (struct MHD_InterimParams_));
8052 if (NULL == interim_params)
8053 {
8054 int err_num = errno;
8055 free (daemon);
8056 errno = err_num;
8057 return NULL;
8058 }
8059#ifdef EPOLL_SUPPORT
8060 daemon->epoll_fd = -1;
8061#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
8062 daemon->epoll_upgrade_fd = -1;
8063#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
8064#endif
8065 /* try to open listen socket */
8066#ifdef HTTPS_SUPPORT
8067 daemon->priority_cache = NULL;
8068#endif /* HTTPS_SUPPORT */
8069 daemon->listen_fd = MHD_INVALID_SOCKET;
8070 daemon->listen_is_unix = _MHD_NO;
8071 daemon->listening_address_reuse = 0;
8072 daemon->options = *pflags;
8073 pflags = &daemon->options;
8074 daemon->client_discipline = (0 != (*pflags & MHD_USE_PEDANTIC_CHECKS)) ?
8075 1 : 0;
8076 daemon->port = port;
8077 daemon->apc = apc;
8078 daemon->apc_cls = apc_cls;
8079 daemon->default_handler = dh;
8080 daemon->default_handler_cls = dh_cls;
8081 daemon->connections = 0;
8086 daemon->connection_timeout_ms = 0; /* no timeout */
8087 MHD_itc_set_invalid_ (daemon->itc);
8088#ifdef MHD_USE_THREADS
8089 MHD_thread_handle_ID_set_invalid_ (&daemon->tid);
8090#endif /* MHD_USE_THREADS */
8091#ifdef SOMAXCONN
8092 daemon->listen_backlog_size = SOMAXCONN;
8093#else /* !SOMAXCONN */
8094 daemon->listen_backlog_size = 511; /* should be safe value */
8095#endif /* !SOMAXCONN */
8096#ifdef HAVE_MESSAGES
8097 daemon->custom_error_log = &MHD_default_logger_;
8098 daemon->custom_error_log_cls = stderr;
8099#endif
8100#ifndef MHD_WINSOCK_SOCKETS
8101 daemon->sigpipe_blocked = false;
8102#else /* MHD_WINSOCK_SOCKETS */
8103 /* There is no SIGPIPE on W32, nothing to block. */
8104 daemon->sigpipe_blocked = true;
8105#endif /* _WIN32 && ! __CYGWIN__ */
8106#if defined(_DEBUG) && defined(HAVE_ACCEPT4)
8107 daemon->avoid_accept4 = false;
8108#endif /* _DEBUG */
8109#ifdef HAS_FD_SETSIZE_OVERRIDABLE
8110 daemon->fdset_size = (int) FD_SETSIZE;
8111 daemon->fdset_size_set_by_app = false;
8112#endif /* HAS_FD_SETSIZE_OVERRIDABLE */
8113
8114#ifdef DAUTH_SUPPORT
8115 daemon->digest_auth_rand_size = 0;
8116 daemon->digest_auth_random = NULL;
8117 daemon->nonce_nc_size = 4; /* tiny */
8118 daemon->dauth_def_nonce_timeout = MHD_DAUTH_DEF_TIMEOUT_;
8119 daemon->dauth_def_max_nc = MHD_DAUTH_DEF_MAX_NC_;
8120#endif
8121#ifdef HTTPS_SUPPORT
8122 if (0 != (*pflags & MHD_USE_TLS))
8123 {
8124 daemon->cred_type = GNUTLS_CRD_CERTIFICATE;
8125 }
8126#endif /* HTTPS_SUPPORT */
8127
8128 interim_params->num_opts = 0;
8129 interim_params->fdset_size_set = false;
8130 interim_params->fdset_size = 0;
8131 interim_params->listen_fd_set = false;
8132 interim_params->listen_fd = MHD_INVALID_SOCKET;
8133 interim_params->pserver_addr_set = false;
8134 interim_params->pserver_addr = NULL;
8135 interim_params->server_addr_len_set = false;
8136 interim_params->server_addr_len = 0;
8137
8138 if (MHD_NO == parse_options_va (daemon,
8139 interim_params,
8140 ap))
8141 {
8142#ifdef HTTPS_SUPPORT
8143 tls_cleanup_failed_start (daemon);
8144#endif /* HTTPS_SUPPORT */
8145 free (interim_params);
8146 free (daemon);
8147 return NULL;
8148 }
8149 if (! process_interim_params (daemon,
8150 &pservaddr,
8151 &addrlen,
8152 interim_params))
8153 {
8154#ifdef HTTPS_SUPPORT
8155 tls_cleanup_failed_start (daemon);
8156#endif /* HTTPS_SUPPORT */
8157 free (interim_params);
8158 free (daemon);
8159 return NULL;
8160 }
8161 free (interim_params);
8162 interim_params = NULL;
8163#ifdef HTTPS_SUPPORT
8164 if ((0 != (*pflags & MHD_USE_TLS))
8165 && (NULL == daemon->priority_cache)
8166 && ! daemon_tls_priorities_init_default (daemon))
8167 {
8168#ifdef HAVE_MESSAGES
8169 MHD_DLOG (daemon,
8170 _ ("Failed to initialise GnuTLS priorities.\n"));
8171#endif /* HAVE_MESSAGES */
8172 tls_cleanup_failed_start (daemon);
8173 free (daemon);
8174 return NULL;
8175 }
8176#endif /* HTTPS_SUPPORT */
8177
8178#ifdef HAVE_MESSAGES
8179 if ( (0 != (flags & MHD_USE_THREAD_PER_CONNECTION)) &&
8180 (0 == (flags & MHD_USE_INTERNAL_POLLING_THREAD)) )
8181 {
8182 MHD_DLOG (daemon,
8183 _ ("Warning: MHD_USE_THREAD_PER_CONNECTION must be used " \
8184 "only with MHD_USE_INTERNAL_POLLING_THREAD. " \
8185 "Flag MHD_USE_INTERNAL_POLLING_THREAD was added. " \
8186 "Consider setting MHD_USE_INTERNAL_POLLING_THREAD " \
8187 "explicitly.\n"));
8188 }
8189#endif
8190
8192 && ((NULL != daemon->notify_completed)
8193 || (NULL != daemon->notify_connection)) )
8194 *pflags |= MHD_USE_ITC; /* requires ITC */
8195
8196#ifdef _DEBUG
8197#ifdef HAVE_MESSAGES
8198 MHD_DLOG (daemon,
8199 _ ("Using debug build of libmicrohttpd.\n") );
8200#endif /* HAVE_MESSAGES */
8201#endif /* _DEBUG */
8202
8203 if ( (0 != (*pflags & MHD_USE_ITC))
8204#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
8205 && (0 == daemon->worker_pool_size)
8206#endif
8207 )
8208 {
8209 if (! MHD_itc_init_ (daemon->itc))
8210 {
8211#ifdef HAVE_MESSAGES
8212 MHD_DLOG (daemon,
8213 _ ("Failed to create inter-thread communication channel: %s\n"),
8214 MHD_itc_last_strerror_ ());
8215#endif
8216#ifdef HTTPS_SUPPORT
8217 if (NULL != daemon->priority_cache)
8218 gnutls_priority_deinit (daemon->priority_cache);
8219#endif /* HTTPS_SUPPORT */
8220 free (daemon);
8221 return NULL;
8222 }
8223 if (MHD_D_IS_USING_SELECT_ (daemon) &&
8224 (! MHD_D_DOES_SCKT_FIT_FDSET_ (MHD_itc_r_fd_ (daemon->itc), daemon)) )
8225 {
8226#ifdef HAVE_MESSAGES
8227 MHD_DLOG (daemon,
8228 _ ("file descriptor for inter-thread communication " \
8229 "channel exceeds maximum value.\n"));
8230#endif
8231 MHD_itc_destroy_chk_ (daemon->itc);
8232#ifdef HTTPS_SUPPORT
8233 if (NULL != daemon->priority_cache)
8234 gnutls_priority_deinit (daemon->priority_cache);
8235#endif /* HTTPS_SUPPORT */
8236 free (daemon);
8237 return NULL;
8238 }
8239 }
8240
8241#ifdef DAUTH_SUPPORT
8242 if (NULL != daemon->digest_auth_random_copy)
8243 {
8244 mhd_assert (daemon == daemon->digest_auth_random_copy);
8245 daemon->digest_auth_random_copy = malloc (daemon->digest_auth_rand_size);
8246 if (NULL == daemon->digest_auth_random_copy)
8247 {
8248#ifdef HTTPS_SUPPORT
8249 if (0 != (*pflags & MHD_USE_TLS))
8250 gnutls_priority_deinit (daemon->priority_cache);
8251#endif /* HTTPS_SUPPORT */
8252 free (daemon);
8253 return NULL;
8254 }
8255 memcpy (daemon->digest_auth_random_copy,
8256 daemon->digest_auth_random,
8257 daemon->digest_auth_rand_size);
8258 daemon->digest_auth_random = daemon->digest_auth_random_copy;
8259 }
8260 if (daemon->nonce_nc_size > 0)
8261 {
8262 if ( ( (size_t) (daemon->nonce_nc_size * sizeof (struct MHD_NonceNc)))
8263 / sizeof(struct MHD_NonceNc) != daemon->nonce_nc_size)
8264 {
8265#ifdef HAVE_MESSAGES
8266 MHD_DLOG (daemon,
8267 _ ("Specified value for NC_SIZE too large.\n"));
8268#endif
8269#ifdef HTTPS_SUPPORT
8270 if (0 != (*pflags & MHD_USE_TLS))
8271 gnutls_priority_deinit (daemon->priority_cache);
8272#endif /* HTTPS_SUPPORT */
8273 free (daemon->digest_auth_random_copy);
8274 free (daemon);
8275 return NULL;
8276 }
8277 daemon->nnc = MHD_calloc_ (daemon->nonce_nc_size,
8278 sizeof (struct MHD_NonceNc));
8279 if (NULL == daemon->nnc)
8280 {
8281#ifdef HAVE_MESSAGES
8282 MHD_DLOG (daemon,
8283 _ ("Failed to allocate memory for nonce-nc map: %s\n"),
8284 MHD_strerror_ (errno));
8285#endif
8286#ifdef HTTPS_SUPPORT
8287 if (0 != (*pflags & MHD_USE_TLS))
8288 gnutls_priority_deinit (daemon->priority_cache);
8289#endif /* HTTPS_SUPPORT */
8290 free (daemon->digest_auth_random_copy);
8291 free (daemon);
8292 return NULL;
8293 }
8294 }
8295
8296#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
8297 if (! MHD_mutex_init_ (&daemon->nnc_lock))
8298 {
8299#ifdef HAVE_MESSAGES
8300 MHD_DLOG (daemon,
8301 _ ("MHD failed to initialize nonce-nc mutex.\n"));
8302#endif
8303#ifdef HTTPS_SUPPORT
8304 if (0 != (*pflags & MHD_USE_TLS))
8305 gnutls_priority_deinit (daemon->priority_cache);
8306#endif /* HTTPS_SUPPORT */
8307 free (daemon->digest_auth_random_copy);
8308 free (daemon->nnc);
8309 free (daemon);
8310 return NULL;
8311 }
8312#endif
8313#endif
8314
8315 /* Thread polling currently works only with internal select thread mode */
8316#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
8317 if ( (! MHD_D_IS_USING_THREADS_ (daemon)) &&
8318 (daemon->worker_pool_size > 0) )
8319 {
8320#ifdef HAVE_MESSAGES
8321 MHD_DLOG (daemon,
8322 _ ("MHD thread polling only works with " \
8323 "MHD_USE_INTERNAL_POLLING_THREAD.\n"));
8324#endif
8325 goto free_and_fail;
8326 }
8327#endif
8328
8329 if ( (MHD_INVALID_SOCKET == daemon->listen_fd) &&
8330 (0 == (*pflags & MHD_USE_NO_LISTEN_SOCKET)) )
8331 {
8332 /* try to open listen socket */
8333 struct sockaddr_in servaddr4;
8334#ifdef HAVE_INET6
8335 struct sockaddr_in6 servaddr6;
8336 const bool use_ipv6 = (0 != (*pflags & MHD_USE_IPv6));
8337#else /* ! HAVE_INET6 */
8338 const bool use_ipv6 = false;
8339#endif /* ! HAVE_INET6 */
8340 int domain;
8341
8342 if (NULL != pservaddr)
8343 {
8344#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
8345 const socklen_t sa_len = pservaddr->sa_len;
8346#endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */
8347#ifdef HAVE_INET6
8348 if (use_ipv6 && (AF_INET6 != pservaddr->sa_family))
8349 {
8350#ifdef HAVE_MESSAGES
8351 MHD_DLOG (daemon,
8352 _ ("MHD_USE_IPv6 is enabled, but 'struct sockaddr *' " \
8353 "specified for MHD_OPTION_SOCK_ADDR_LEN or " \
8354 "MHD_OPTION_SOCK_ADDR is not IPv6 address.\n"));
8355#endif /* HAVE_MESSAGES */
8356 goto free_and_fail;
8357 }
8358#endif /* HAVE_INET6 */
8359 switch (pservaddr->sa_family)
8360 {
8361 case AF_INET:
8362 if (1)
8363 {
8364 struct sockaddr_in sa4;
8365 uint16_t sa4_port;
8366 if ((0 != addrlen)
8367 && (((socklen_t) sizeof(sa4)) > addrlen))
8368 {
8369#ifdef HAVE_MESSAGES
8370 MHD_DLOG (daemon,
8371 _ ("The size specified for MHD_OPTION_SOCK_ADDR_LEN " \
8372 "option is wrong.\n"));
8373#endif /* HAVE_MESSAGES */
8374 goto free_and_fail;
8375 }
8376#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
8377 if (0 != sa_len)
8378 {
8379 if (((socklen_t) sizeof(sa4)) > sa_len)
8380 {
8381#ifdef HAVE_MESSAGES
8382 MHD_DLOG (daemon,
8383 _ ("The value of 'struct sockaddr.sa_len' provided " \
8384 "via MHD_OPTION_SOCK_ADDR_LEN option is not zero " \
8385 "and does not match 'sa_family' value of the " \
8386 "same structure.\n"));
8387#endif /* HAVE_MESSAGES */
8388 goto free_and_fail;
8389 }
8390 if ((0 == addrlen) || (sa_len < addrlen))
8391 addrlen = sa_len; /* Use smaller value for safety */
8392 }
8393#endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */
8394 if (0 == addrlen)
8395 addrlen = sizeof(sa4);
8396 memcpy (&sa4, pservaddr, sizeof(sa4)); /* Required due to stronger alignment */
8397 sa4_port = (uint16_t) ntohs (sa4.sin_port);
8398#ifndef MHD_USE_GETSOCKNAME
8399 if (0 != sa4_port)
8400#endif /* ! MHD_USE_GETSOCKNAME */
8401 daemon->port = sa4_port;
8402 domain = PF_INET;
8403 }
8404 break;
8405#ifdef HAVE_INET6
8406 case AF_INET6:
8407 if (1)
8408 {
8409 struct sockaddr_in6 sa6;
8410 uint16_t sa6_port;
8411 if ((0 != addrlen)
8412 && (((socklen_t) sizeof(sa6)) > addrlen))
8413 {
8414#ifdef HAVE_MESSAGES
8415 MHD_DLOG (daemon,
8416 _ ("The size specified for MHD_OPTION_SOCK_ADDR_LEN " \
8417 "option is wrong.\n"));
8418#endif /* HAVE_MESSAGES */
8419 goto free_and_fail;
8420 }
8421#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
8422 if (0 != sa_len)
8423 {
8424 if (((socklen_t) sizeof(sa6)) > sa_len)
8425 {
8426#ifdef HAVE_MESSAGES
8427 MHD_DLOG (daemon,
8428 _ ("The value of 'struct sockaddr.sa_len' provided " \
8429 "via MHD_OPTION_SOCK_ADDR_LEN option is not zero " \
8430 "and does not match 'sa_family' value of the " \
8431 "same structure.\n"));
8432#endif /* HAVE_MESSAGES */
8433 goto free_and_fail;
8434 }
8435 if ((0 == addrlen) || (sa_len < addrlen))
8436 addrlen = sa_len; /* Use smaller value for safety */
8437 }
8438#endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */
8439 if (0 == addrlen)
8440 addrlen = sizeof(sa6);
8441 memcpy (&sa6, pservaddr, sizeof(sa6)); /* Required due to stronger alignment */
8442 sa6_port = (uint16_t) ntohs (sa6.sin6_port);
8443#ifndef MHD_USE_GETSOCKNAME
8444 if (0 != sa6_port)
8445#endif /* ! MHD_USE_GETSOCKNAME */
8446 daemon->port = sa6_port;
8447 domain = PF_INET6;
8448 *pflags |= ((enum MHD_FLAG) MHD_USE_IPv6);
8449 }
8450 break;
8451#endif /* HAVE_INET6 */
8452#ifdef AF_UNIX
8453 case AF_UNIX:
8454#endif /* AF_UNIX */
8455 default:
8456#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
8457 if (0 == addrlen)
8458 addrlen = sa_len;
8459 else if ((0 != sa_len) && (sa_len < addrlen))
8460 addrlen = sa_len; /* Use smaller value for safety */
8461#endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */
8462 if (0 >= addrlen)
8463 {
8464#ifdef HAVE_MESSAGES
8465 MHD_DLOG (daemon,
8466 _ ("The 'sa_family' of the 'struct sockaddr' provided " \
8467 "via MHD_OPTION_SOCK_ADDR option is not supported.\n"));
8468#endif /* HAVE_MESSAGES */
8469 goto free_and_fail;
8470 }
8471#ifdef AF_UNIX
8472 if (AF_UNIX == pservaddr->sa_family)
8473 {
8474 daemon->port = 0; /* special value for UNIX domain sockets */
8475 daemon->listen_is_unix = _MHD_YES;
8476#ifdef PF_UNIX
8477 domain = PF_UNIX;
8478#else /* ! PF_UNIX */
8479 domain = AF_UNIX;
8480#endif /* ! PF_UNIX */
8481 }
8482 else /* combined with the next 'if' */
8483#endif /* AF_UNIX */
8484 if (1)
8485 {
8486 daemon->port = 0; /* ugh */
8487 daemon->listen_is_unix = _MHD_UNKNOWN;
8488 /* Assumed the same values for AF_* and PF_* */
8489 domain = pservaddr->sa_family;
8490 }
8491 break;
8492 }
8493 }
8494 else
8495 {
8496 if (! use_ipv6)
8497 {
8498 memset (&servaddr4,
8499 0,
8500 sizeof (struct sockaddr_in));
8501 servaddr4.sin_family = AF_INET;
8502 servaddr4.sin_port = htons (port);
8503 if (0 != INADDR_ANY)
8504 servaddr4.sin_addr.s_addr = htonl (INADDR_ANY);
8505#ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
8506 servaddr4.sin_len = sizeof (struct sockaddr_in);
8507#endif
8508 pservaddr = (struct sockaddr *) &servaddr4;
8509 addrlen = (socklen_t) sizeof(servaddr4);
8510 daemon->listen_is_unix = _MHD_NO;
8511 domain = PF_INET;
8512 }
8513#ifdef HAVE_INET6
8514 else
8515 {
8516#ifdef IN6ADDR_ANY_INIT
8517 static const struct in6_addr static_in6any = IN6ADDR_ANY_INIT;
8518#endif
8519 memset (&servaddr6,
8520 0,
8521 sizeof (struct sockaddr_in6));
8522 servaddr6.sin6_family = AF_INET6;
8523 servaddr6.sin6_port = htons (port);
8524#ifdef IN6ADDR_ANY_INIT
8525 servaddr6.sin6_addr = static_in6any;
8526#endif
8527#ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
8528 servaddr6.sin6_len = sizeof (struct sockaddr_in6);
8529#endif
8530 pservaddr = (struct sockaddr *) &servaddr6;
8531 addrlen = (socklen_t) sizeof (servaddr6);
8532 daemon->listen_is_unix = _MHD_NO;
8533 domain = PF_INET6;
8534 }
8535#endif /* HAVE_INET6 */
8536 }
8537
8538 daemon->listen_fd = MHD_socket_create_listen_ (domain);
8539 if (MHD_INVALID_SOCKET == daemon->listen_fd)
8540 {
8541#ifdef HAVE_MESSAGES
8542 MHD_DLOG (daemon,
8543 _ ("Failed to create socket for listening: %s\n"),
8545#endif
8546 goto free_and_fail;
8547 }
8548 if (MHD_D_IS_USING_SELECT_ (daemon) &&
8550 daemon)) )
8551 {
8552#ifdef HAVE_MESSAGES
8553 MHD_DLOG (daemon,
8554 _ ("Listen socket descriptor (%d) is not " \
8555 "less than daemon FD_SETSIZE value (%d).\n"),
8556 (int) daemon->listen_fd,
8557 (int) MHD_D_GET_FD_SETSIZE_ (daemon));
8558#endif
8559 goto free_and_fail;
8560 }
8561
8562 /* Apply the socket options according to listening_address_reuse. */
8563 if (0 == daemon->listening_address_reuse)
8564 {
8565#ifndef MHD_WINSOCK_SOCKETS
8566 /* No user requirement, use "traditional" default SO_REUSEADDR
8567 * on non-W32 platforms, and do not fail if it doesn't work.
8568 * Don't use it on W32, because on W32 it will allow multiple
8569 * bind to the same address:port, like SO_REUSEPORT on others. */
8570 if (0 > setsockopt (daemon->listen_fd,
8571 SOL_SOCKET,
8572 SO_REUSEADDR,
8573 (const void *) &on, sizeof (on)))
8574 {
8575#ifdef HAVE_MESSAGES
8576 MHD_DLOG (daemon,
8577 _ ("setsockopt failed: %s\n"),
8579#endif
8580 }
8581#endif /* ! MHD_WINSOCK_SOCKETS */
8582 }
8583 else if (daemon->listening_address_reuse > 0)
8584 {
8585 /* User requested to allow reusing listening address:port. */
8586#ifndef MHD_WINSOCK_SOCKETS
8587 /* Use SO_REUSEADDR on non-W32 platforms, and do not fail if
8588 * it doesn't work. */
8589 if (0 > setsockopt (daemon->listen_fd,
8590 SOL_SOCKET,
8591 SO_REUSEADDR,
8592 (const void *) &on, sizeof (on)))
8593 {
8594#ifdef HAVE_MESSAGES
8595 MHD_DLOG (daemon,
8596 _ ("setsockopt failed: %s\n"),
8598#endif
8599 }
8600#endif /* ! MHD_WINSOCK_SOCKETS */
8601 /* Use SO_REUSEADDR on Windows and SO_REUSEPORT on most platforms.
8602 * Fail if SO_REUSEPORT is not defined or setsockopt fails.
8603 */
8604 /* SO_REUSEADDR on W32 has the same semantics
8605 as SO_REUSEPORT on BSD/Linux */
8606#if defined(MHD_WINSOCK_SOCKETS) || defined(SO_REUSEPORT)
8607 if (0 > setsockopt (daemon->listen_fd,
8608 SOL_SOCKET,
8609#ifndef MHD_WINSOCK_SOCKETS
8610 SO_REUSEPORT,
8611#else /* MHD_WINSOCK_SOCKETS */
8612 SO_REUSEADDR,
8613#endif /* MHD_WINSOCK_SOCKETS */
8614 (const void *) &on,
8615 sizeof (on)))
8616 {
8617#ifdef HAVE_MESSAGES
8618 MHD_DLOG (daemon,
8619 _ ("setsockopt failed: %s\n"),
8621#endif
8622 goto free_and_fail;
8623 }
8624#else /* !MHD_WINSOCK_SOCKETS && !SO_REUSEPORT */
8625 /* we're supposed to allow address:port re-use, but
8626 on this platform we cannot; fail hard */
8627#ifdef HAVE_MESSAGES
8628 MHD_DLOG (daemon,
8629 _ ("Cannot allow listening address reuse: " \
8630 "SO_REUSEPORT not defined.\n"));
8631#endif
8632 goto free_and_fail;
8633#endif /* !MHD_WINSOCK_SOCKETS && !SO_REUSEPORT */
8634 }
8635 else /* if (daemon->listening_address_reuse < 0) */
8636 {
8637 /* User requested to disallow reusing listening address:port.
8638 * Do nothing except for Windows where SO_EXCLUSIVEADDRUSE
8639 * is used and Solaris with SO_EXCLBIND.
8640 * Fail if MHD was compiled for W32 without SO_EXCLUSIVEADDRUSE
8641 * or setsockopt fails.
8642 */
8643#if (defined(MHD_WINSOCK_SOCKETS) && defined(SO_EXCLUSIVEADDRUSE)) || \
8644 (defined(__sun) && defined(SO_EXCLBIND))
8645 if (0 > setsockopt (daemon->listen_fd,
8646 SOL_SOCKET,
8647#ifdef SO_EXCLUSIVEADDRUSE
8648 SO_EXCLUSIVEADDRUSE,
8649#else /* SO_EXCLBIND */
8650 SO_EXCLBIND,
8651#endif /* SO_EXCLBIND */
8652 (const void *) &on,
8653 sizeof (on)))
8654 {
8655#ifdef HAVE_MESSAGES
8656 MHD_DLOG (daemon,
8657 _ ("setsockopt failed: %s\n"),
8659#endif
8660 goto free_and_fail;
8661 }
8662#elif defined(MHD_WINSOCK_SOCKETS) /* SO_EXCLUSIVEADDRUSE not defined on W32? */
8663#ifdef HAVE_MESSAGES
8664 MHD_DLOG (daemon,
8665 _ ("Cannot disallow listening address reuse: " \
8666 "SO_EXCLUSIVEADDRUSE not defined.\n"));
8667#endif
8668 goto free_and_fail;
8669#endif /* MHD_WINSOCK_SOCKETS */
8670 }
8671
8672 /* check for user supplied sockaddr */
8673 if (0 != (*pflags & MHD_USE_IPv6))
8674 {
8675#ifdef IPPROTO_IPV6
8676#ifdef IPV6_V6ONLY
8677 /* Note: "IPV6_V6ONLY" is declared by Windows Vista ff., see "IPPROTO_IPV6 Socket Options"
8678 (http://msdn.microsoft.com/en-us/library/ms738574%28v=VS.85%29.aspx);
8679 and may also be missing on older POSIX systems; good luck if you have any of those,
8680 your IPv6 socket may then also bind against IPv4 anyway... */
8681 const MHD_SCKT_OPT_BOOL_ v6_only =
8682 (MHD_USE_DUAL_STACK != (*pflags & MHD_USE_DUAL_STACK));
8683 if (0 > setsockopt (daemon->listen_fd,
8684 IPPROTO_IPV6, IPV6_V6ONLY,
8685 (const void *) &v6_only,
8686 sizeof (v6_only)))
8687 {
8688#ifdef HAVE_MESSAGES
8689 MHD_DLOG (daemon,
8690 _ ("setsockopt failed: %s\n"),
8692#endif
8693 }
8694#endif
8695#endif
8696 }
8697 if (0 != bind (daemon->listen_fd,
8698 pservaddr,
8699 addrlen))
8700 {
8701#ifdef HAVE_MESSAGES
8702 MHD_DLOG (daemon,
8703 _ ("Failed to bind to port %u: %s\n"),
8704 (unsigned int) port,
8706#endif
8707 goto free_and_fail;
8708 }
8709#ifdef TCP_FASTOPEN
8710 if (0 != (*pflags & MHD_USE_TCP_FASTOPEN))
8711 {
8712 if (0 == daemon->fastopen_queue_size)
8713 daemon->fastopen_queue_size = MHD_TCP_FASTOPEN_QUEUE_SIZE_DEFAULT;
8714 if (0 != setsockopt (daemon->listen_fd,
8715 IPPROTO_TCP,
8716 TCP_FASTOPEN,
8717 (const void *) &daemon->fastopen_queue_size,
8718 sizeof (daemon->fastopen_queue_size)))
8719 {
8720#ifdef HAVE_MESSAGES
8721 MHD_DLOG (daemon,
8722 _ ("setsockopt failed: %s\n"),
8724#endif
8725 }
8726 }
8727#endif
8728 if (0 != listen (daemon->listen_fd,
8729 (int) daemon->listen_backlog_size))
8730 {
8731#ifdef HAVE_MESSAGES
8732 MHD_DLOG (daemon,
8733 _ ("Failed to listen for connections: %s\n"),
8735#endif
8736 goto free_and_fail;
8737 }
8738 }
8739 else
8740 {
8741 if (MHD_D_IS_USING_SELECT_ (daemon) &&
8743 daemon)) )
8744 {
8745#ifdef HAVE_MESSAGES
8746 MHD_DLOG (daemon,
8747 _ ("Listen socket descriptor (%d) is not " \
8748 "less than daemon FD_SETSIZE value (%d).\n"),
8749 (int) daemon->listen_fd,
8750 (int) MHD_D_GET_FD_SETSIZE_ (daemon));
8751#endif
8752 goto free_and_fail;
8753 }
8754 else
8755 {
8756#if defined(SOL_SOCKET) && (defined(SO_DOMAIN) || defined(SO_PROTOCOL_INFOW))
8757 int af;
8758 int opt_name;
8759 void *poptval;
8760 socklen_t optval_size;
8761#ifdef SO_DOMAIN
8762 opt_name = SO_DOMAIN;
8763 poptval = &af;
8764 optval_size = (socklen_t) sizeof (af);
8765#else /* SO_PROTOCOL_INFOW */
8766 WSAPROTOCOL_INFOW prot_info;
8767 opt_name = SO_PROTOCOL_INFOW;
8768 poptval = &prot_info;
8769 optval_size = (socklen_t) sizeof (prot_info);
8770#endif /* SO_PROTOCOL_INFOW */
8771
8772 if (0 == getsockopt (daemon->listen_fd,
8773 SOL_SOCKET,
8774 opt_name,
8775 poptval,
8776 &optval_size))
8777 {
8778#ifndef SO_DOMAIN
8779 af = prot_info.iAddressFamily;
8780#endif /* SO_DOMAIN */
8781 switch (af)
8782 {
8783 case AF_INET:
8784 daemon->listen_is_unix = _MHD_NO;
8785 break;
8786#ifdef HAVE_INET6
8787 case AF_INET6:
8788 *pflags |= MHD_USE_IPv6;
8789 daemon->listen_is_unix = _MHD_NO;
8790 break;
8791#endif /* HAVE_INET6 */
8792#ifdef AF_UNIX
8793 case AF_UNIX:
8794 daemon->port = 0; /* special value for UNIX domain sockets */
8795 daemon->listen_is_unix = _MHD_YES;
8796 break;
8797#endif /* AF_UNIX */
8798 default:
8799 daemon->port = 0; /* ugh */
8800 daemon->listen_is_unix = _MHD_UNKNOWN;
8801 break;
8802 }
8803 }
8804 else
8805#endif /* SOL_SOCKET && (SO_DOMAIN || SO_PROTOCOL_INFOW)) */
8806 daemon->listen_is_unix = _MHD_UNKNOWN;
8807 }
8808
8809#ifdef MHD_USE_GETSOCKNAME
8810 daemon->port = 0; /* Force use of autodetection */
8811#endif /* MHD_USE_GETSOCKNAME */
8812 }
8813
8814#ifdef MHD_USE_GETSOCKNAME
8815 if ( (0 == daemon->port) &&
8816 (0 == (*pflags & MHD_USE_NO_LISTEN_SOCKET)) &&
8817 (_MHD_YES != daemon->listen_is_unix) )
8818 { /* Get port number. */
8819 struct sockaddr_storage bindaddr;
8820
8821 memset (&bindaddr,
8822 0,
8823 sizeof (struct sockaddr_storage));
8824 addrlen = sizeof (struct sockaddr_storage);
8825#ifdef HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN
8826 bindaddr.ss_len = (socklen_t) addrlen;
8827#endif
8828 if (0 != getsockname (daemon->listen_fd,
8829 (struct sockaddr *) &bindaddr,
8830 &addrlen))
8831 {
8832#ifdef HAVE_MESSAGES
8833 MHD_DLOG (daemon,
8834 _ ("Failed to get listen port number: %s\n"),
8835 MHD_socket_last_strerr_ ());
8836#endif /* HAVE_MESSAGES */
8837 }
8838#ifdef MHD_POSIX_SOCKETS
8839 else if (sizeof (bindaddr) < addrlen)
8840 {
8841 /* should be impossible with `struct sockaddr_storage` */
8842#ifdef HAVE_MESSAGES
8843 MHD_DLOG (daemon,
8844 _ ("Failed to get listen port number " \
8845 "(`struct sockaddr_storage` too small!?).\n"));
8846#endif /* HAVE_MESSAGES */
8847 }
8848#ifndef __linux__
8849 else if (0 == addrlen)
8850 {
8851 /* Many non-Linux-based platforms return zero addrlen
8852 * for AF_UNIX sockets */
8853 daemon->port = 0; /* special value for UNIX domain sockets */
8854 if (_MHD_UNKNOWN == daemon->listen_is_unix)
8855 daemon->listen_is_unix = _MHD_YES;
8856 }
8857#endif /* __linux__ */
8858#endif /* MHD_POSIX_SOCKETS */
8859 else
8860 {
8861 switch (bindaddr.ss_family)
8862 {
8863 case AF_INET:
8864 {
8865 struct sockaddr_in *s4 = (struct sockaddr_in *) &bindaddr;
8866
8867 daemon->port = ntohs (s4->sin_port);
8868 daemon->listen_is_unix = _MHD_NO;
8869 break;
8870 }
8871#ifdef HAVE_INET6
8872 case AF_INET6:
8873 {
8874 struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) &bindaddr;
8875
8876 daemon->port = ntohs (s6->sin6_port);
8877 daemon->listen_is_unix = _MHD_NO;
8878 mhd_assert (0 != (*pflags & MHD_USE_IPv6));
8879 break;
8880 }
8881#endif /* HAVE_INET6 */
8882#ifdef AF_UNIX
8883 case AF_UNIX:
8884 daemon->port = 0; /* special value for UNIX domain sockets */
8885 daemon->listen_is_unix = _MHD_YES;
8886 break;
8887#endif
8888 default:
8889#ifdef HAVE_MESSAGES
8890 MHD_DLOG (daemon,
8891 _ ("Listen socket has unknown address family!\n"));
8892#endif
8893 daemon->port = 0; /* ugh */
8894 daemon->listen_is_unix = _MHD_UNKNOWN;
8895 break;
8896 }
8897 }
8898 }
8899#endif /* MHD_USE_GETSOCKNAME */
8900
8901 if (MHD_INVALID_SOCKET != daemon->listen_fd)
8902 {
8903 mhd_assert (0 == (*pflags & MHD_USE_NO_LISTEN_SOCKET));
8904 if (! MHD_socket_nonblocking_ (daemon->listen_fd))
8905 {
8906#ifdef HAVE_MESSAGES
8907 MHD_DLOG (daemon,
8908 _ ("Failed to set nonblocking mode on listening socket: %s\n"),
8910#endif
8911 if (MHD_D_IS_USING_EPOLL_ (daemon)
8912#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
8913 || (daemon->worker_pool_size > 0)
8914#endif
8915 )
8916 {
8917 /* Accept must be non-blocking. Multiple children may wake up
8918 * to handle a new connection, but only one will win the race.
8919 * The others must immediately return. */
8920 goto free_and_fail;
8921 }
8922 daemon->listen_nonblk = false;
8923 }
8924 else
8925 daemon->listen_nonblk = true;
8926 }
8927 else
8928 {
8929 mhd_assert (0 != (*pflags & MHD_USE_NO_LISTEN_SOCKET));
8930 daemon->listen_nonblk = false; /* Actually listen socket does not exist */
8931 }
8932
8933#ifdef EPOLL_SUPPORT
8934 if (MHD_D_IS_USING_EPOLL_ (daemon)
8935#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
8936 && (0 == daemon->worker_pool_size)
8937#endif
8938 )
8939 {
8941 {
8942#ifdef HAVE_MESSAGES
8943 MHD_DLOG (daemon,
8944 _ ("Combining MHD_USE_THREAD_PER_CONNECTION and " \
8945 "MHD_USE_EPOLL is not supported.\n"));
8946#endif
8947 goto free_and_fail;
8948 }
8949 if (MHD_NO == setup_epoll_to_listen (daemon))
8950 goto free_and_fail;
8951 }
8952#endif /* EPOLL_SUPPORT */
8953
8954#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
8955 if (! MHD_mutex_init_ (&daemon->per_ip_connection_mutex))
8956 {
8957#ifdef HAVE_MESSAGES
8958 MHD_DLOG (daemon,
8959 _ ("MHD failed to initialize IP connection limit mutex.\n"));
8960#endif
8961 goto free_and_fail;
8962 }
8963#endif
8964
8965#ifdef HTTPS_SUPPORT
8966 /* initialize HTTPS daemon certificate aspects & send / recv functions */
8967 if ( (0 != (*pflags & MHD_USE_TLS)) &&
8968 (0 != MHD_TLS_init (daemon)) )
8969 {
8970#ifdef HAVE_MESSAGES
8971 MHD_DLOG (daemon,
8972 _ ("Failed to initialize TLS support.\n"));
8973#endif
8974#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
8975 MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex);
8976#endif
8977 goto free_and_fail;
8978 }
8979#endif /* HTTPS_SUPPORT */
8980#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
8981 /* Start threads if requested by parameters */
8982 if (MHD_D_IS_USING_THREADS_ (daemon))
8983 {
8984 /* Internal thread (or threads) is used.
8985 * Make sure that MHD will be able to communicate with threads. */
8986 /* If using a thread pool ITC will be initialised later
8987 * for each individual worker thread. */
8988#ifdef HAVE_LISTEN_SHUTDOWN
8989 mhd_assert ((1 < daemon->worker_pool_size) || \
8990 (MHD_ITC_IS_VALID_ (daemon->itc)) || \
8991 (MHD_INVALID_SOCKET != daemon->listen_fd));
8992#else /* ! HAVE_LISTEN_SHUTDOWN */
8993 mhd_assert ((1 < daemon->worker_pool_size) || \
8994 (MHD_ITC_IS_VALID_ (daemon->itc)));
8995#endif /* ! HAVE_LISTEN_SHUTDOWN */
8996 if (0 == daemon->worker_pool_size)
8997 {
8998 if (! MHD_mutex_init_ (&daemon->cleanup_connection_mutex))
8999 {
9000#ifdef HAVE_MESSAGES
9001 MHD_DLOG (daemon,
9002 _ ("Failed to initialise internal lists mutex.\n"));
9003#endif
9004 MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex);
9005 goto free_and_fail;
9006 }
9007 if (! MHD_mutex_init_ (&daemon->new_connections_mutex))
9008 {
9009#ifdef HAVE_MESSAGES
9010 MHD_DLOG (daemon,
9011 _ ("Failed to initialise mutex.\n"));
9012#endif
9013 MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex);
9014 MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex);
9015 goto free_and_fail;
9016 }
9017 if (! MHD_mutex_init_ (&daemon->epoll_listen_mutex))
9018 {
9019#ifdef HAVE_MESSAGES
9020 MHD_DLOG (daemon,
9021 _ ("Failed to initialise mutex.\n"));
9022#endif
9023 MHD_mutex_destroy_chk_ (&daemon->new_connections_mutex);
9024 MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex);
9025 MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex);
9026 goto free_and_fail;
9027 }
9028 if (! MHD_create_named_thread_ (&daemon->tid,
9030 "MHD-listen" : "MHD-single",
9031 daemon->thread_stack_size,
9032 &MHD_polling_thread,
9033 daemon) )
9034 {
9035#ifdef HAVE_MESSAGES
9036#ifdef EAGAIN
9037 if (EAGAIN == errno)
9038 MHD_DLOG (daemon,
9039 _ ("Failed to create a new thread because it would have " \
9040 "exceeded the system limit on the number of threads or " \
9041 "no system resources available.\n"));
9042 else
9043#endif /* EAGAIN */
9044 MHD_DLOG (daemon,
9045 _ ("Failed to create listen thread: %s\n"),
9046 MHD_strerror_ (errno));
9047#endif /* HAVE_MESSAGES */
9048 MHD_mutex_destroy_chk_ (&daemon->epoll_listen_mutex);
9049 MHD_mutex_destroy_chk_ (&daemon->new_connections_mutex);
9050 MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex);
9051 MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex);
9052 goto free_and_fail;
9053 }
9054 }
9055 else /* 0 < daemon->worker_pool_size */
9056 {
9057 /* Coarse-grained count of connections per thread (note error
9058 * due to integer division). Also keep track of how many
9059 * connections are leftover after an equal split. */
9060 unsigned int conns_per_thread = daemon->connection_limit
9061 / daemon->worker_pool_size;
9062 unsigned int leftover_conns = daemon->connection_limit
9063 % daemon->worker_pool_size;
9064
9065 mhd_assert (2 <= daemon->worker_pool_size);
9066 i = 0; /* we need this in case fcntl or malloc fails */
9067
9068 /* Allocate memory for pooled objects */
9069 daemon->worker_pool = malloc (sizeof (struct MHD_Daemon)
9070 * daemon->worker_pool_size);
9071 if (NULL == daemon->worker_pool)
9072 goto thread_failed;
9073
9074 /* Start the workers in the pool */
9075 for (i = 0; i < daemon->worker_pool_size; ++i)
9076 {
9077 /* Create copy of the Daemon object for each worker */
9078 struct MHD_Daemon *d = &daemon->worker_pool[i];
9079
9080 memcpy (d, daemon, sizeof (struct MHD_Daemon));
9081 /* Adjust polling params for worker daemons; note that memcpy()
9082 has already copied MHD_USE_INTERNAL_POLLING_THREAD thread mode into
9083 the worker threads. */
9084 d->master = daemon;
9085 d->worker_pool_size = 0;
9086 d->worker_pool = NULL;
9087 if (! MHD_mutex_init_ (&d->cleanup_connection_mutex))
9088 {
9089#ifdef HAVE_MESSAGES
9090 MHD_DLOG (daemon,
9091 _ ("Failed to initialise internal lists mutex.\n"));
9092#endif
9093 goto thread_failed;
9094 }
9095 if (! MHD_mutex_init_ (&d->new_connections_mutex))
9096 {
9097#ifdef HAVE_MESSAGES
9098 MHD_DLOG (daemon,
9099 _ ("Failed to initialise mutex.\n"));
9100#endif
9101 MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex);
9102 goto thread_failed;
9103 }
9104 if (! MHD_mutex_init_ (&d->epoll_listen_mutex))
9105 {
9106#ifdef HAVE_MESSAGES
9107 MHD_DLOG (daemon,
9108 _ ("Failed to initialise mutex.\n"));
9109#endif
9110 MHD_mutex_destroy_chk_ (&d->new_connections_mutex);
9111 MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex);
9112 MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex);
9113 goto free_and_fail;
9114 }
9115 if (0 != (*pflags & MHD_USE_ITC))
9116 {
9117 if (! MHD_itc_init_ (d->itc))
9118 {
9119#ifdef HAVE_MESSAGES
9120 MHD_DLOG (daemon,
9121 _ ("Failed to create worker inter-thread " \
9122 "communication channel: %s\n"),
9123 MHD_itc_last_strerror_ () );
9124#endif
9125 MHD_mutex_destroy_chk_ (&d->epoll_listen_mutex);
9126 MHD_mutex_destroy_chk_ (&d->new_connections_mutex);
9127 MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex);
9128 goto thread_failed;
9129 }
9130 if (MHD_D_IS_USING_SELECT_ (d) &&
9131 (! MHD_D_DOES_SCKT_FIT_FDSET_ (MHD_itc_r_fd_ (d->itc), daemon)) )
9132 {
9133#ifdef HAVE_MESSAGES
9134 MHD_DLOG (daemon,
9135 _ ("File descriptor for worker inter-thread " \
9136 "communication channel exceeds maximum value.\n"));
9137#endif
9139 MHD_mutex_destroy_chk_ (&d->epoll_listen_mutex);
9140 MHD_mutex_destroy_chk_ (&d->new_connections_mutex);
9141 MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex);
9142 goto thread_failed;
9143 }
9144 }
9145 else
9146 MHD_itc_set_invalid_ (d->itc);
9147
9148#ifdef HAVE_LISTEN_SHUTDOWN
9149 mhd_assert ((MHD_ITC_IS_VALID_ (d->itc)) || \
9151#else /* ! HAVE_LISTEN_SHUTDOWN */
9152 mhd_assert (MHD_ITC_IS_VALID_ (d->itc));
9153#endif /* ! HAVE_LISTEN_SHUTDOWN */
9154
9155 /* Divide available connections evenly amongst the threads.
9156 * Thread indexes in [0, leftover_conns) each get one of the
9157 * leftover connections. */
9158 d->connection_limit = conns_per_thread;
9159 if (i < leftover_conns)
9160 ++d->connection_limit;
9161#ifdef EPOLL_SUPPORT
9162 if (MHD_D_IS_USING_EPOLL_ (d) &&
9163 (MHD_NO == setup_epoll_to_listen (d)) )
9164 {
9165 if (MHD_ITC_IS_VALID_ (d->itc))
9167 MHD_mutex_destroy_chk_ (&d->epoll_listen_mutex);
9168 MHD_mutex_destroy_chk_ (&d->new_connections_mutex);
9169 MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex);
9170 goto thread_failed;
9171 }
9172#endif
9173 /* Some members must be used only in master daemon */
9174#if defined(MHD_USE_THREADS)
9175 memset (&d->per_ip_connection_mutex, 0x7F,
9176 sizeof(d->per_ip_connection_mutex));
9177#endif /* MHD_USE_THREADS */
9178#ifdef DAUTH_SUPPORT
9179 d->nnc = NULL;
9180 d->nonce_nc_size = 0;
9181 d->digest_auth_random_copy = NULL;
9182#if defined(MHD_USE_THREADS)
9183 memset (&d->nnc_lock, 0x7F, sizeof(d->nnc_lock));
9184#endif /* MHD_USE_THREADS */
9185#endif /* DAUTH_SUPPORT */
9186
9187 /* Spawn the worker thread */
9188 if (! MHD_create_named_thread_ (&d->tid,
9189 "MHD-worker",
9190 daemon->thread_stack_size,
9191 &MHD_polling_thread,
9192 d))
9193 {
9194#ifdef HAVE_MESSAGES
9195#ifdef EAGAIN
9196 if (EAGAIN == errno)
9197 MHD_DLOG (daemon,
9198 _ ("Failed to create a new pool thread because it would " \
9199 "have exceeded the system limit on the number of " \
9200 "threads or no system resources available.\n"));
9201 else
9202#endif /* EAGAIN */
9203 MHD_DLOG (daemon,
9204 _ ("Failed to create pool thread: %s\n"),
9205 MHD_strerror_ (errno));
9206#endif
9207 /* Free memory for this worker; cleanup below handles
9208 * all previously-created workers. */
9209 if (MHD_ITC_IS_VALID_ (d->itc))
9211 MHD_mutex_destroy_chk_ (&d->epoll_listen_mutex);
9212 MHD_mutex_destroy_chk_ (&d->new_connections_mutex);
9213 MHD_mutex_destroy_chk_ (&d->cleanup_connection_mutex);
9214 goto thread_failed;
9215 }
9216 }
9217 }
9218 }
9219 else
9220 { /* Daemon without internal threads */
9221 if (! MHD_mutex_init_ (&daemon->cleanup_connection_mutex))
9222 {
9223#ifdef HAVE_MESSAGES
9224 MHD_DLOG (daemon,
9225 _ ("Failed to initialise internal lists mutex.\n"));
9226#endif
9227 MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex);
9228 goto free_and_fail;
9229 }
9230 if (! MHD_mutex_init_ (&daemon->new_connections_mutex))
9231 {
9232#ifdef HAVE_MESSAGES
9233 MHD_DLOG (daemon,
9234 _ ("Failed to initialise mutex.\n"));
9235#endif
9236 MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex);
9237 MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex);
9238 goto free_and_fail;
9239 }
9240 if (! MHD_mutex_init_ (&daemon->epoll_listen_mutex))
9241 {
9242#ifdef HAVE_MESSAGES
9243 MHD_DLOG (daemon,
9244 _ ("Failed to initialise mutex.\n"));
9245#endif
9246 MHD_mutex_destroy_chk_ (&daemon->new_connections_mutex);
9247 MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex);
9248 MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex);
9249 goto free_and_fail;
9250 }
9251 }
9252#endif
9253#ifdef HTTPS_SUPPORT
9254 /* API promises to never use the password after initialization,
9255 so we additionally NULL it here to not deref a dangling pointer. */
9256 daemon->https_key_password = NULL;
9257#endif /* HTTPS_SUPPORT */
9258
9259 return daemon;
9260
9261#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
9262thread_failed:
9263 /* If no worker threads created, then shut down normally. Calling
9264 MHD_stop_daemon (as we do below) doesn't work here since it
9265 assumes a 0-sized thread pool means we had been in the default
9266 MHD_USE_INTERNAL_POLLING_THREAD mode. */
9267 if (0 == i)
9268 {
9269 MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex);
9270 if (NULL != daemon->worker_pool)
9271 free (daemon->worker_pool);
9272 goto free_and_fail;
9273 }
9274
9275 /* Shutdown worker threads we've already created. Pretend
9276 as though we had fully initialized our daemon, but
9277 with a smaller number of threads than had been
9278 requested. */
9279 daemon->worker_pool_size = i;
9280 MHD_stop_daemon (daemon);
9281 return NULL;
9282#endif
9283
9284free_and_fail:
9285 /* clean up basic memory state in 'daemon' and return NULL to
9286 indicate failure */
9287#ifdef EPOLL_SUPPORT
9288#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
9289 if (daemon->upgrade_fd_in_epoll)
9290 {
9291 if (0 != epoll_ctl (daemon->epoll_fd,
9292 EPOLL_CTL_DEL,
9293 daemon->epoll_upgrade_fd,
9294 NULL))
9295 MHD_PANIC (_ ("Failed to remove FD from epoll set.\n"));
9296 daemon->upgrade_fd_in_epoll = false;
9297 }
9298#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
9299 if (-1 != daemon->epoll_fd)
9300 close (daemon->epoll_fd);
9301#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
9302 if (-1 != daemon->epoll_upgrade_fd)
9303 close (daemon->epoll_upgrade_fd);
9304#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
9305#endif /* EPOLL_SUPPORT */
9306#ifdef DAUTH_SUPPORT
9307 free (daemon->digest_auth_random_copy);
9308 free (daemon->nnc);
9309#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
9310 MHD_mutex_destroy_chk_ (&daemon->nnc_lock);
9311#endif
9312#endif
9313#ifdef HTTPS_SUPPORT
9314 tls_cleanup_failed_start (daemon);
9315#endif /* HTTPS_SUPPORT */
9316 if (MHD_ITC_IS_VALID_ (daemon->itc))
9317 MHD_itc_destroy_chk_ (daemon->itc);
9318 if (MHD_INVALID_SOCKET != daemon->listen_fd)
9319 (void) MHD_socket_close_ (daemon->listen_fd);
9320 free (daemon);
9321 return NULL;
9322}
9323
9324
9333static void
9335{
9336 struct MHD_Connection *pos;
9337 const bool used_thr_p_c = MHD_D_IS_USING_THREAD_PER_CONN_ (daemon);
9338#ifdef UPGRADE_SUPPORT
9339 const bool upg_allowed = (0 != (daemon->options & MHD_ALLOW_UPGRADE));
9340#endif /* UPGRADE_SUPPORT */
9341#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
9342 struct MHD_UpgradeResponseHandle *urh;
9343 struct MHD_UpgradeResponseHandle *urhn;
9344 const bool used_tls = (0 != (daemon->options & MHD_USE_TLS));
9345#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
9346
9347#ifdef MHD_USE_THREADS
9348 mhd_assert ( (! MHD_D_IS_USING_THREADS_ (daemon)) || \
9351 mhd_assert (NULL == daemon->worker_pool);
9352#endif /* MHD_USE_THREADS */
9353 mhd_assert (daemon->shutdown);
9354
9355#ifdef MHD_USE_THREADS
9356/* Remove new connections that MHD_add_connection() queued and that were
9357 * never processed. This is not limited to daemons with an internal
9358 * polling thread: internal_add_connection() queues whenever the daemon
9359 * is thread-safe, which is every daemon that was not started with
9360 * MHD_USE_NO_THREAD_SAFETY, and new_connections_list_process_()
9361 * asserts the same condition. An application driving an external
9362 * event loop can therefore call MHD_add_connection() and then
9363 * MHD_stop_daemon() before the next MHD_run(), and this list is what
9364 * holds the connection at that point. */
9365 MHD_mutex_lock_chk_ (&daemon->new_connections_mutex);
9366 while (NULL != (pos = daemon->new_connections_tail))
9367 {
9370 daemon->new_connections_tail,
9371 pos);
9372 new_connection_close_ (daemon, pos);
9373 }
9374 MHD_mutex_unlock_chk_ (&daemon->new_connections_mutex);
9375#endif /* MHD_USE_THREADS */
9376
9377#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
9378 /* give upgraded HTTPS connections a chance to finish */
9379 /* 'daemon->urh_head' is not used in thread-per-connection mode. */
9380 for (urh = daemon->urh_tail; NULL != urh; urh = urhn)
9381 {
9382 mhd_assert (! used_thr_p_c);
9383 urhn = urh->prev;
9384 /* call generic forwarding function for passing data
9385 with chance to detect that application is done. */
9386 process_urh (urh);
9387 MHD_connection_finish_forward_ (urh->connection);
9388 urh->clean_ready = true;
9389 /* Resuming will move connection to cleanup list. */
9390 MHD_resume_connection (urh->connection);
9391 }
9392#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
9393
9394 /* Give suspended connections a chance to resume to avoid
9395 running into the check for there not being any suspended
9396 connections left in case of a tight race with a recently
9397 resumed connection. */
9398 if (0 != (MHD_TEST_ALLOW_SUSPEND_RESUME & daemon->options))
9399 {
9400 daemon->resuming = true; /* Force check for pending resume. */
9402 }
9403 /* first, make sure all threads are aware of shutdown; need to
9404 traverse DLLs in peace... */
9405#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
9406 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
9407#endif
9408#ifdef UPGRADE_SUPPORT
9409 if (upg_allowed)
9410 {
9411 struct MHD_Connection *susp;
9412
9414 while (NULL != susp)
9415 {
9416 if (NULL == susp->urh) /* "Upgraded" connection? */
9417 MHD_PANIC (_ ("MHD_stop_daemon() called while we have " \
9418 "suspended connections.\n"));
9419#ifdef HTTPS_SUPPORT
9420 else if (used_tls &&
9421 used_thr_p_c &&
9422 (! susp->urh->clean_ready) )
9423 shutdown (susp->urh->app.socket,
9424 SHUT_RDWR); /* Wake thread by shutdown of app socket. */
9425#endif /* HTTPS_SUPPORT */
9426 else
9427 {
9428#ifdef HAVE_MESSAGES
9429 if (! susp->urh->was_closed)
9430 MHD_DLOG (daemon,
9431 _ ("Initiated daemon shutdown while \"upgraded\" " \
9432 "connection was not closed.\n"));
9433#endif
9434 susp->urh->was_closed = true;
9435 /* If thread-per-connection is used, connection's thread
9436 * may still processing "upgrade" (exiting). */
9437 if (! used_thr_p_c)
9439 /* Do not use MHD_resume_connection() as mutex is
9440 * already locked. */
9441 susp->resuming = true;
9442 daemon->resuming = true;
9443 }
9444 susp = susp->prev;
9445 }
9446 }
9447 else /* This 'else' is combined with next 'if' */
9448#endif /* UPGRADE_SUPPORT */
9450 MHD_PANIC (_ ("MHD_stop_daemon() called while we have " \
9451 "suspended connections.\n"));
9452#if defined(UPGRADE_SUPPORT) && defined(HTTPS_SUPPORT)
9453#ifdef MHD_USE_THREADS
9454 if (upg_allowed && used_tls && used_thr_p_c)
9455 {
9456 /* "Upgraded" threads may be running in parallel. Connection will not be
9457 * moved to the "cleanup list" until connection's thread finishes.
9458 * We must ensure that all "upgraded" connections are finished otherwise
9459 * connection may stay in "suspended" list and will not be cleaned. */
9460 for (pos = daemon->suspended_connections_tail; NULL != pos; pos = pos->prev)
9461 {
9462 /* Any connection found here is "upgraded" connection, normal suspended
9463 * connections are already removed from this list. */
9464 mhd_assert (NULL != pos->urh);
9465 if (! pos->thread_joined)
9466 {
9467 /* While "cleanup" list is not manipulated by "upgraded"
9468 * connection, "cleanup" mutex is required for call of
9469 * MHD_resume_connection() during finishing of "upgraded"
9470 * thread. */
9471 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
9472 if (! MHD_thread_handle_ID_join_thread_ (pos->tid))
9473 MHD_PANIC (_ ("Failed to join a thread.\n"));
9474 pos->thread_joined = true;
9475 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
9476 }
9477 }
9478 }
9479#endif /* MHD_USE_THREADS */
9480#endif
9481 for (pos = daemon->connections_tail; NULL != pos; pos = pos->prev)
9482 {
9483 shutdown (pos->socket_fd,
9484 SHUT_RDWR);
9485#ifdef MHD_WINSOCK_SOCKETS
9487 (MHD_ITC_IS_VALID_ (daemon->itc)) &&
9488 (! MHD_itc_activate_ (daemon->itc, "e")) )
9489 MHD_PANIC (_ ("Failed to signal shutdown via inter-thread " \
9490 "communication channel.\n"));
9491#endif
9492 }
9493
9494#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
9495 /* now, collect per-connection threads */
9496 if (used_thr_p_c)
9497 {
9498 pos = daemon->connections_tail;
9499 while (NULL != pos)
9500 {
9501 if (! pos->thread_joined)
9502 {
9503 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
9504 if (! MHD_thread_handle_ID_join_thread_ (pos->tid))
9505 MHD_PANIC (_ ("Failed to join a thread.\n"));
9506 MHD_mutex_lock_chk_ (&daemon->cleanup_connection_mutex);
9507 pos->thread_joined = true;
9508 /* The thread may have concurrently modified the DLL,
9509 need to restart from the beginning */
9510 pos = daemon->connections_tail;
9511 continue;
9512 }
9513 pos = pos->prev;
9514 }
9515 }
9516 MHD_mutex_unlock_chk_ (&daemon->cleanup_connection_mutex);
9517#endif
9518
9519#ifdef UPGRADE_SUPPORT
9520 /* Finished threads with "upgraded" connections need to be moved
9521 * to cleanup list by resume_suspended_connections(). */
9522 /* "Upgraded" connections that were not closed explicitly by
9523 * application should be moved to cleanup list too. */
9524 if (upg_allowed)
9525 {
9526 daemon->resuming = true; /* Force check for pending resume. */
9528 }
9529#endif /* UPGRADE_SUPPORT */
9530
9532 /* now that we're alone, move everyone to cleanup */
9533 while (NULL != (pos = daemon->connections_tail))
9534 {
9535#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
9537 (! pos->thread_joined) )
9538 MHD_PANIC (_ ("Failed to join a thread.\n"));
9539#endif
9540 close_connection (pos);
9541 }
9543}
9544
9545
9552_MHD_EXTERN void
9554{
9555 MHD_socket fd;
9556#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
9557 unsigned int i;
9558#endif
9559
9560 if (NULL == daemon)
9561 return;
9562 if ( (daemon->shutdown) && (NULL == daemon->master) )
9563 MHD_PANIC (_ ("MHD_stop_daemon() was called twice."));
9564
9566 (NULL != daemon->worker_pool) || \
9569 (NULL == daemon->worker_pool)) || \
9571
9572 /* Slave daemons must be stopped by master daemon. */
9573 mhd_assert ( (NULL == daemon->master) || (daemon->shutdown) );
9574
9575 daemon->shutdown = true;
9576 if (daemon->was_quiesced)
9577 fd = MHD_INVALID_SOCKET; /* Do not use FD if daemon was quiesced */
9578 else
9579 fd = daemon->listen_fd;
9580
9581#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
9582 if (NULL != daemon->worker_pool)
9583 { /* Master daemon with worker pool. */
9584 mhd_assert (1 < daemon->worker_pool_size);
9586
9587 /* Let workers shutdown in parallel. */
9588 for (i = 0; i < daemon->worker_pool_size; ++i)
9589 {
9590 daemon->worker_pool[i].shutdown = true;
9591 if (MHD_ITC_IS_VALID_ (daemon->worker_pool[i].itc))
9592 {
9593 if (! MHD_itc_activate_ (daemon->worker_pool[i].itc,
9594 "e"))
9595 MHD_PANIC (_ ("Failed to signal shutdown via inter-thread " \
9596 "communication channel.\n"));
9597 }
9598 else
9600 }
9601#ifdef HAVE_LISTEN_SHUTDOWN
9602 if (MHD_INVALID_SOCKET != fd)
9603 {
9604 (void) shutdown (fd,
9605 SHUT_RDWR);
9606 }
9607#endif /* HAVE_LISTEN_SHUTDOWN */
9608 for (i = 0; i < daemon->worker_pool_size; ++i)
9609 {
9610 MHD_stop_daemon (&daemon->worker_pool[i]);
9611 }
9612 free (daemon->worker_pool);
9614#ifdef EPOLL_SUPPORT
9615 mhd_assert (-1 == daemon->epoll_fd);
9616#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
9617 mhd_assert (-1 == daemon->epoll_upgrade_fd);
9618#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
9619#endif /* EPOLL_SUPPORT */
9620 }
9621 else
9622#endif
9623 { /* Worker daemon or single daemon. */
9624#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
9626 { /* Worker daemon or single daemon with internal thread(s). */
9627 mhd_assert (0 == daemon->worker_pool_size);
9628 /* Separate thread(s) is used for polling sockets. */
9629 if (MHD_ITC_IS_VALID_ (daemon->itc))
9630 {
9631 if (! MHD_itc_activate_ (daemon->itc,
9632 "e"))
9633 MHD_PANIC (_ ("Failed to signal shutdown via inter-thread " \
9634 "communication channel.\n"));
9635 }
9636 else
9637 {
9638#ifdef HAVE_LISTEN_SHUTDOWN
9639 if (MHD_INVALID_SOCKET != fd)
9640 {
9641 if (NULL == daemon->master)
9642 (void) shutdown (fd,
9643 SHUT_RDWR);
9644 }
9645 else
9646#endif /* HAVE_LISTEN_SHUTDOWN */
9647 mhd_assert (false); /* Should never happen */
9648 }
9649
9651 {
9652 MHD_PANIC (_ ("Failed to join a thread.\n"));
9653 }
9654 /* close_all_connections() was called in daemon thread. */
9655 }
9656 else
9657#endif
9658 {
9659 /* No internal threads are used for polling sockets. */
9661 }
9666#if defined(UPGRADE_SUPPORT) && defined(HTTPS_SUPPORT)
9667 mhd_assert (NULL == daemon->urh_head);
9668#endif /* UPGRADE_SUPPORT && HTTPS_SUPPORT */
9669
9670 if (MHD_ITC_IS_VALID_ (daemon->itc))
9672
9673#ifdef EPOLL_SUPPORT
9675 (-1 != daemon->epoll_fd) )
9676 MHD_socket_close_chk_ (daemon->epoll_fd);
9677#if defined(HTTPS_SUPPORT) && defined(UPGRADE_SUPPORT)
9679 (-1 != daemon->epoll_upgrade_fd) )
9680 MHD_socket_close_chk_ (daemon->epoll_upgrade_fd);
9681#endif /* HTTPS_SUPPORT && UPGRADE_SUPPORT */
9682#endif /* EPOLL_SUPPORT */
9683
9684#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
9685 MHD_mutex_destroy_chk_ (&daemon->cleanup_connection_mutex);
9686 MHD_mutex_destroy_chk_ (&daemon->epoll_listen_mutex);
9687 MHD_mutex_destroy_chk_ (&daemon->new_connections_mutex);
9688#endif
9689 }
9690
9691 if (NULL == daemon->master)
9692 { /* Cleanup that should be done only one time in master/single daemon.
9693 * Do not perform this cleanup in worker daemons. */
9694
9695 if (MHD_INVALID_SOCKET != fd)
9697
9698 /* TLS clean up */
9699#ifdef HTTPS_SUPPORT
9700 if (daemon->have_dhparams)
9701 {
9702 gnutls_dh_params_deinit (daemon->https_mem_dhparams);
9703 daemon->have_dhparams = false;
9704 }
9705 if (0 != (daemon->options & MHD_USE_TLS))
9706 {
9707 gnutls_priority_deinit (daemon->priority_cache);
9708 if (daemon->x509_cred)
9709 gnutls_certificate_free_credentials (daemon->x509_cred);
9710 if (daemon->psk_cred)
9711 gnutls_psk_free_server_credentials (daemon->psk_cred);
9712 }
9713#endif /* HTTPS_SUPPORT */
9714
9715#ifdef DAUTH_SUPPORT
9716 free (daemon->digest_auth_random_copy);
9717 free (daemon->nnc);
9718#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
9719 MHD_mutex_destroy_chk_ (&daemon->nnc_lock);
9720#endif
9721#endif
9722#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
9723 MHD_mutex_destroy_chk_ (&daemon->per_ip_connection_mutex);
9724#endif
9725 free (daemon);
9726 }
9727}
9728
9729
9742_MHD_EXTERN const union MHD_DaemonInfo *
9744 enum MHD_DaemonInfoType info_type,
9745 ...)
9746{
9747 if (NULL == daemon)
9748 return NULL;
9749
9750 mhd_assert ((0 == (daemon->options & MHD_USE_SELECT_INTERNALLY)) || \
9751 (NULL != daemon->worker_pool) || \
9753 mhd_assert (((0 != (daemon->options & MHD_USE_SELECT_INTERNALLY)) &&
9754 (NULL == daemon->worker_pool)) || \
9755 (! MHD_thread_handle_ID_is_valid_handle_ (daemon->tid)));
9756
9757 switch (info_type)
9758 {
9760 return NULL; /* no longer supported */
9762 return NULL; /* no longer supported */
9765 return &daemon->daemon_info_dummy_listen_fd;
9767#ifdef EPOLL_SUPPORT
9768 daemon->daemon_info_dummy_epoll_fd.epoll_fd = daemon->epoll_fd;
9769 return &daemon->daemon_info_dummy_epoll_fd;
9770#else /* ! EPOLL_SUPPORT */
9771 return NULL;
9772#endif /* ! EPOLL_SUPPORT */
9774 if (! MHD_D_IS_THREAD_SAFE_ (daemon))
9775 MHD_cleanup_connections (daemon);
9776#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
9777 else if (daemon->worker_pool)
9778 {
9779 unsigned int i;
9780 /* Collect the connection information stored in the workers. */
9781 daemon->connections = 0;
9782 for (i = 0; i < daemon->worker_pool_size; i++)
9783 {
9784 /* FIXME: next line is thread-safe only if read is atomic. */
9785 daemon->connections += daemon->worker_pool[i].connections;
9786 }
9787 }
9788#endif
9790 = daemon->connections;
9791 return &daemon->daemon_info_dummy_num_connections;
9793 daemon->daemon_info_dummy_flags.flags = daemon->options;
9794 return &daemon->daemon_info_dummy_flags;
9796 daemon->daemon_info_dummy_port.port = daemon->port;
9797 return &daemon->daemon_info_dummy_port;
9798 default:
9799 return NULL;
9800 }
9801}
9802
9803
9810_MHD_EXTERN const char *
9812{
9813#ifdef PACKAGE_VERSION
9814 return PACKAGE_VERSION;
9815#else /* !PACKAGE_VERSION */
9816 static char ver[12] = "\0\0\0\0\0\0\0\0\0\0\0";
9817 if (0 == ver[0])
9818 {
9819 int res = MHD_snprintf_ (ver,
9820 sizeof(ver),
9821 "%x.%x.%x",
9822 (int) (((uint32_t) MHD_VERSION >> 24) & 0xFF),
9823 (int) (((uint32_t) MHD_VERSION >> 16) & 0xFF),
9824 (int) (((uint32_t) MHD_VERSION >> 8) & 0xFF));
9825 if ((0 >= res) || (sizeof(ver) <= res))
9826 return "0.0.0"; /* Can't return real version */
9827 }
9828 return ver;
9829#endif /* !PACKAGE_VERSION */
9830}
9831
9832
9841_MHD_EXTERN uint32_t
9843{
9844 return (uint32_t) MHD_VERSION;
9845}
9846
9847
9861{
9862 switch (feature)
9863 {
9865#ifdef HAVE_MESSAGES
9866 return MHD_YES;
9867#else
9868 return MHD_NO;
9869#endif
9870 case MHD_FEATURE_TLS:
9871#ifdef HTTPS_SUPPORT
9872 return MHD_YES;
9873#else /* ! HTTPS_SUPPORT */
9874 return MHD_NO;
9875#endif /* ! HTTPS_SUPPORT */
9877#if defined(HTTPS_SUPPORT) && GNUTLS_VERSION_MAJOR >= 3
9878 return MHD_YES;
9879#else /* !HTTPS_SUPPORT || GNUTLS_VERSION_MAJOR < 3 */
9880 return MHD_NO;
9881#endif /* !HTTPS_SUPPORT || GNUTLS_VERSION_MAJOR < 3 */
9883#if defined(HTTPS_SUPPORT) && GNUTLS_VERSION_NUMBER >= 0x030603
9884 return MHD_YES;
9885#else /* !HTTPS_SUPPORT || GNUTLS_VERSION_NUMBER < 0x030603 */
9886 return MHD_NO;
9887#endif /* !HTTPS_SUPPORT || GNUTLS_VERSION_NUMBER < 0x030603 */
9888 case MHD_FEATURE_IPv6:
9889#ifdef HAVE_INET6
9890 return MHD_YES;
9891#else
9892 return MHD_NO;
9893#endif
9895#if defined(IPPROTO_IPV6) && defined(IPV6_V6ONLY)
9896 return MHD_YES;
9897#else
9898 return MHD_NO;
9899#endif
9900 case MHD_FEATURE_POLL:
9901#ifdef HAVE_POLL
9902 return MHD_YES;
9903#else
9904 return MHD_NO;
9905#endif
9906 case MHD_FEATURE_EPOLL:
9907#ifdef EPOLL_SUPPORT
9908 return MHD_YES;
9909#else
9910 return MHD_NO;
9911#endif
9913#ifdef HAVE_LISTEN_SHUTDOWN
9914 return MHD_YES;
9915#else
9916 return MHD_NO;
9917#endif
9919#ifdef _MHD_ITC_SOCKETPAIR
9920 return MHD_YES;
9921#else
9922 return MHD_NO;
9923#endif
9925#ifdef TCP_FASTOPEN
9926 return MHD_YES;
9927#else
9928 return MHD_NO;
9929#endif
9931#ifdef BAUTH_SUPPORT
9932 return MHD_YES;
9933#else
9934 return MHD_NO;
9935#endif
9937#ifdef DAUTH_SUPPORT
9938 return MHD_YES;
9939#else
9940 return MHD_NO;
9941#endif
9943#ifdef HAVE_POSTPROCESSOR
9944 return MHD_YES;
9945#else
9946 return MHD_NO;
9947#endif
9949#if defined(HTTPS_SUPPORT) && GNUTLS_VERSION_NUMBER >= 0x030111
9950 return MHD_YES;
9951#else /* !HTTPS_SUPPORT || GNUTLS_VERSION_NUMBER < 0x030111 */
9952 return MHD_NO;
9953#endif /* !HTTPS_SUPPORT || GNUTLS_VERSION_NUMBER < 0x030111 */
9955#if defined(HAVE_PREAD64) || defined(_WIN32)
9956 return MHD_YES;
9957#elif defined(HAVE_PREAD)
9958 return (sizeof(uint64_t) > sizeof(off_t)) ? MHD_NO : MHD_YES;
9959#elif defined(HAVE_LSEEK64)
9960 return MHD_YES;
9961#else
9962 return (sizeof(uint64_t) > sizeof(off_t)) ? MHD_NO : MHD_YES;
9963#endif
9965#if defined(MHD_USE_THREAD_NAME_)
9966 return MHD_YES;
9967#else
9968 return MHD_NO;
9969#endif
9971#if defined(UPGRADE_SUPPORT)
9972 return MHD_YES;
9973#else
9974 return MHD_NO;
9975#endif
9977#if defined(HAVE_PREAD64) || defined(HAVE_PREAD) || defined(_WIN32)
9978 return MHD_YES;
9979#else
9980 return MHD_NO;
9981#endif
9983#ifdef MHD_USE_GETSOCKNAME
9984 return MHD_YES;
9985#else
9986 return MHD_NO;
9987#endif
9989#if defined(MHD_SEND_SPIPE_SUPPRESS_POSSIBLE) || \
9990 ! defined(MHD_SEND_SPIPE_SUPPRESS_NEEDED)
9991 return MHD_YES;
9992#else
9993 return MHD_NO;
9994#endif
9996#ifdef _MHD_HAVE_SENDFILE
9997 return MHD_YES;
9998#else
9999 return MHD_NO;
10000#endif
10002#if defined(MHD_USE_POSIX_THREADS) || defined(MHD_USE_W32_THREADS)
10003 return MHD_YES;
10004#else
10005 return MHD_NO;
10006#endif
10008#if defined(COOKIE_SUPPORT)
10009 return MHD_YES;
10010#else
10011 return MHD_NO;
10012#endif
10014#ifdef DAUTH_SUPPORT
10015 return MHD_YES;
10016#else
10017 return MHD_NO;
10018#endif
10020#if defined(DAUTH_SUPPORT) && defined(MHD_MD5_SUPPORT)
10021 return MHD_YES;
10022#else
10023 return MHD_NO;
10024#endif
10026#if defined(DAUTH_SUPPORT) && defined(MHD_SHA256_SUPPORT)
10027 return MHD_YES;
10028#else
10029 return MHD_NO;
10030#endif
10032#if defined(DAUTH_SUPPORT) && defined(MHD_SHA512_256_SUPPORT)
10033 return MHD_YES;
10034#else
10035 return MHD_NO;
10036#endif
10038#ifdef DAUTH_SUPPORT
10039 return MHD_NO;
10040#else
10041 return MHD_NO;
10042#endif
10044#ifdef DAUTH_SUPPORT
10045 return MHD_NO;
10046#else
10047 return MHD_NO;
10048#endif
10050#ifdef DAUTH_SUPPORT
10051 return MHD_YES;
10052#else
10053 return MHD_NO;
10054#endif
10056#if defined(MHD_MD5_TLSLIB) || defined(MHD_SHA256_TLSLIB)
10057 return MHD_YES;
10058#else
10059 return MHD_NO;
10060#endif
10062#ifdef _DEBUG
10063 return MHD_YES;
10064#else
10065 return MHD_NO;
10066#endif
10068#ifdef HAS_FD_SETSIZE_OVERRIDABLE
10069 return MHD_YES;
10070#else /* ! HAS_FD_SETSIZE_OVERRIDABLE */
10071 return MHD_NO;
10072#endif /* ! HAS_FD_SETSIZE_OVERRIDABLE */
10073
10074 default:
10075 break;
10076 }
10077 return MHD_NO;
10078}
10079
10080
10081#ifdef MHD_HTTPS_REQUIRE_GCRYPT
10082#if defined(HTTPS_SUPPORT) && GCRYPT_VERSION_NUMBER < 0x010600
10083#if defined(MHD_USE_POSIX_THREADS)
10084GCRY_THREAD_OPTION_PTHREAD_IMPL;
10085#elif defined(MHD_W32_MUTEX_)
10086
10087static int
10088gcry_w32_mutex_init (void **ppmtx)
10089{
10090 *ppmtx = malloc (sizeof (MHD_mutex_));
10091
10092 if (NULL == *ppmtx)
10093 return ENOMEM;
10094 if (! MHD_mutex_init_ ((MHD_mutex_ *) *ppmtx))
10095 {
10096 free (*ppmtx);
10097 *ppmtx = NULL;
10098 return EPERM;
10099 }
10100
10101 return 0;
10102}
10103
10104
10105static int
10106gcry_w32_mutex_destroy (void **ppmtx)
10107{
10108 int res = (MHD_mutex_destroy_ ((MHD_mutex_ *) *ppmtx)) ? 0 : EINVAL;
10109 free (*ppmtx);
10110 return res;
10111}
10112
10113
10114static int
10115gcry_w32_mutex_lock (void **ppmtx)
10116{
10117 return MHD_mutex_lock_ ((MHD_mutex_ *) *ppmtx) ? 0 : EINVAL;
10118}
10119
10120
10121static int
10122gcry_w32_mutex_unlock (void **ppmtx)
10123{
10124 return MHD_mutex_unlock_ ((MHD_mutex_ *) *ppmtx) ? 0 : EINVAL;
10125}
10126
10127
10128static struct gcry_thread_cbs gcry_threads_w32 = {
10129 (GCRY_THREAD_OPTION_USER | (GCRY_THREAD_OPTION_VERSION << 8)),
10130 NULL, gcry_w32_mutex_init, gcry_w32_mutex_destroy,
10131 gcry_w32_mutex_lock, gcry_w32_mutex_unlock,
10133};
10134
10135#endif /* defined(MHD_W32_MUTEX_) */
10136#endif /* HTTPS_SUPPORT && GCRYPT_VERSION_NUMBER < 0x010600 */
10137#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
10138
10142void
10144{
10145#if defined(MHD_WINSOCK_SOCKETS)
10146 WSADATA wsd;
10147#endif /* MHD_WINSOCK_SOCKETS */
10148
10150
10151#if defined(MHD_WINSOCK_SOCKETS)
10152 if (0 != WSAStartup (MAKEWORD (2, 2), &wsd))
10153 MHD_PANIC (_ ("Failed to initialize winsock.\n"));
10154 if ((2 != LOBYTE (wsd.wVersion)) && (2 != HIBYTE (wsd.wVersion)))
10155 MHD_PANIC (_ ("Winsock version 2.2 is not available.\n"));
10156#endif /* MHD_WINSOCK_SOCKETS */
10157#ifdef HTTPS_SUPPORT
10158#ifdef MHD_HTTPS_REQUIRE_GCRYPT
10159#if GCRYPT_VERSION_NUMBER < 0x010600
10160#if GNUTLS_VERSION_NUMBER <= 0x020b00
10161#if defined(MHD_USE_POSIX_THREADS)
10162 if (0 != gcry_control (GCRYCTL_SET_THREAD_CBS,
10163 &gcry_threads_pthread))
10164 MHD_PANIC (_ ("Failed to initialise multithreading in libgcrypt.\n"));
10165#elif defined(MHD_W32_MUTEX_)
10166 if (0 != gcry_control (GCRYCTL_SET_THREAD_CBS,
10167 &gcry_threads_w32))
10168 MHD_PANIC (_ ("Failed to initialise multithreading in libgcrypt.\n"));
10169#endif /* defined(MHD_W32_MUTEX_) */
10170#endif /* GNUTLS_VERSION_NUMBER <= 0x020b00 */
10171 gcry_check_version (NULL);
10172#else
10173 if (NULL == gcry_check_version ("1.6.0"))
10174 MHD_PANIC (_ ("libgcrypt is too old. MHD was compiled for " \
10175 "libgcrypt 1.6.0 or newer.\n"));
10176#endif
10177#endif /* MHD_HTTPS_REQUIRE_GCRYPT */
10178 gnutls_global_init ();
10179#endif /* HTTPS_SUPPORT */
10183 /* Check whether sizes were correctly detected by configure */
10184#ifdef _DEBUG
10185 if (1)
10186 {
10187 struct timeval tv;
10188 mhd_assert (sizeof(tv.tv_sec) == SIZEOF_STRUCT_TIMEVAL_TV_SEC);
10189 }
10190#endif /* _DEBUG */
10191 mhd_assert (sizeof(uint64_t) == SIZEOF_UINT64_T);
10192}
10193
10194
10195void
10197{
10198#ifdef HTTPS_SUPPORT
10199 gnutls_global_deinit ();
10200#endif /* HTTPS_SUPPORT */
10201#if defined(MHD_WINSOCK_SOCKETS)
10202 WSACleanup ();
10203#endif /* MHD_WINSOCK_SOCKETS */
10205}
10206
10207
10208#ifdef _AUTOINIT_FUNCS_ARE_SUPPORTED
10210#endif /* _AUTOINIT_FUNCS_ARE_SUPPORTED */
10211
10212/* end of daemon.c */
#define _SET_INIT_AND_DEINIT_FUNCS(FI, FD)
void MHD_connection_set_initial_state_(struct MHD_Connection *c)
void MHD_connection_handle_write(struct MHD_Connection *connection)
void MHD_set_http_callbacks_(struct MHD_Connection *connection)
enum MHD_Result MHD_connection_handle_idle(struct MHD_Connection *connection)
void MHD_connection_handle_read(struct MHD_Connection *connection, bool socket_error)
void MHD_update_last_activity_(struct MHD_Connection *connection)
void MHD_connection_close_(struct MHD_Connection *connection, enum MHD_RequestTerminationCode termination_code)
void MHD_connection_mark_closed_(struct MHD_Connection *connection)
Methods for managing connections.
#define MHD_connection_finish_forward_(conn)
Definition connection.h:174
void MHD_set_https_callbacks(struct MHD_Connection *connection)
Methods for managing connections.
static void MHD_ip_limit_del(struct MHD_Daemon *daemon, const struct sockaddr_storage *addr, socklen_t addrlen)
Definition daemon.c:437
static void close_all_connections(struct MHD_Daemon *daemon)
Definition daemon.c:9334
static enum MHD_Result MHD_ip_addr_to_key(const struct sockaddr_storage *addr, socklen_t addrlen, struct MHD_IPCount *key)
Definition daemon.c:316
void internal_suspend_connection_(struct MHD_Connection *connection)
Definition daemon.c:3401
void MHD_fini(void)
Definition daemon.c:10196
static enum MHD_Result MHD_ip_limit_add(struct MHD_Daemon *daemon, const struct sockaddr_storage *addr, socklen_t addrlen)
Definition daemon.c:369
static enum MHD_Result call_handlers(struct MHD_Connection *con, bool read_ready, bool write_ready, bool force_close)
Definition daemon.c:1332
static void MHD_ip_count_unlock(struct MHD_Daemon *daemon)
Definition daemon.c:276
static struct MHD_Connection * new_connection_prepare_(struct MHD_Daemon *daemon, MHD_socket client_socket, const struct sockaddr_storage *addr, socklen_t addrlen, bool external_add, bool non_blck, bool sk_spipe_supprs, enum MHD_tristate sk_is_nonip)
Definition daemon.c:2687
volatile int global_init_count
Definition daemon.c:144
void MHD_check_global_init_(void)
Definition daemon.c:161
static void close_connection(struct MHD_Connection *pos)
Definition daemon.c:6190
_MHD_EXTERN void MHD_resume_connection(struct MHD_Connection *connection)
Definition daemon.c:3542
static enum MHD_Result MHD_select(struct MHD_Daemon *daemon, int32_t millisec)
Definition daemon.c:5024
static enum MHD_Result parse_options(struct MHD_Daemon *daemon, struct MHD_InterimParams_ *params,...)
Definition daemon.c:6575
static int MHD_ip_addr_compare(const void *a1, const void *a2)
Definition daemon.c:297
static void new_connections_list_process_(struct MHD_Daemon *daemon)
Definition daemon.c:3349
void MHD_init(void)
Definition daemon.c:10143
static void MHD_cleanup_connections(struct MHD_Daemon *daemon)
Definition daemon.c:4254
void(* VfprintfFunctionPointerType)(void *cls, const char *format, va_list va)
Definition daemon.c:6545
static enum MHD_Result MHD_accept_connection(struct MHD_Daemon *daemon)
Definition daemon.c:4015
static enum MHD_Result parse_options_va(struct MHD_Daemon *daemon, struct MHD_InterimParams_ *params, va_list ap)
Definition daemon.c:6867
#define MHD_MAX_CONNECTIONS_DEFAULT
Definition daemon.c:80
static size_t unescape_wrapper(void *cls, struct MHD_Connection *connection, char *val)
Definition daemon.c:6310
static enum MHD_Result new_connection_process_(struct MHD_Daemon *daemon, struct MHD_Connection *connection)
Definition daemon.c:3039
static enum MHD_Result internal_add_connection(struct MHD_Daemon *daemon, MHD_socket client_socket, const struct sockaddr_storage *addr, socklen_t addrlen, bool external_add, bool non_blck, bool sk_spipe_supprs, enum MHD_tristate sk_is_nonip)
Definition daemon.c:3262
static void MHD_ip_count_lock(struct MHD_Daemon *daemon)
Definition daemon.c:259
static enum MHD_Result resume_suspended_connections(struct MHD_Daemon *daemon)
Definition daemon.c:3644
#define MHD_POOL_SIZE_DEFAULT
Definition daemon.c:88
static bool process_interim_params(struct MHD_Daemon *d, const struct sockaddr **ppsockaddr, socklen_t *psockaddr_len, struct MHD_InterimParams_ *params)
Definition daemon.c:7773
_MHD_EXTERN void MHD_suspend_connection(struct MHD_Connection *connection)
Definition daemon.c:3499
_MHD_EXTERN int MHD_get_timeout_i(struct MHD_Daemon *daemon)
_MHD_EXTERN int64_t MHD_get_timeout64s(struct MHD_Daemon *daemon)
#define MHD_run_from_select(d, r, w, e)
_MHD_EXTERN void MHD_stop_daemon(struct MHD_Daemon *daemon)
Definition daemon.c:9553
_MHD_EXTERN struct MHD_Daemon * MHD_start_daemon_va(unsigned int flags, uint16_t port, MHD_AcceptPolicyCallback apc, void *apc_cls, MHD_AccessHandlerCallback dh, void *dh_cls, va_list ap)
Definition daemon.c:7939
_MHD_EXTERN enum MHD_Result MHD_run(struct MHD_Daemon *daemon)
Definition daemon.c:6076
static enum MHD_Result internal_run_from_select(struct MHD_Daemon *daemon, const fd_set *read_fd_set, const fd_set *write_fd_set, const fd_set *except_fd_set, int fd_setsize)
Definition daemon.c:4708
_MHD_EXTERN enum MHD_Result MHD_get_fdset2(struct MHD_Daemon *daemon, fd_set *read_fd_set, fd_set *write_fd_set, fd_set *except_fd_set, MHD_socket *max_fd, unsigned int fd_setsize)
Definition daemon.c:1227
static enum MHD_Result internal_get_fdset2(struct MHD_Daemon *daemon, fd_set *read_fd_set, fd_set *write_fd_set, fd_set *except_fd_set, MHD_socket *max_fd, int fd_setsize)
Definition daemon.c:1026
#define MHD_get_fdset(daemon, read_fd_set, write_fd_set, except_fd_set, max_fd)
_MHD_EXTERN enum MHD_Result MHD_get_timeout(struct MHD_Daemon *daemon, MHD_UNSIGNED_LONG_LONG *timeout)
Definition daemon.c:4385
_MHD_EXTERN enum MHD_Result MHD_get_timeout64(struct MHD_Daemon *daemon, uint64_t *timeout)
Definition daemon.c:4439
_MHD_EXTERN enum MHD_Result MHD_run_from_select2(struct MHD_Daemon *daemon, const fd_set *read_fd_set, const fd_set *write_fd_set, const fd_set *except_fd_set, unsigned int fd_setsize)
Definition daemon.c:4879
_MHD_EXTERN struct MHD_Daemon * MHD_start_daemon(unsigned int flags, uint16_t port, MHD_AcceptPolicyCallback apc, void *apc_cls, MHD_AccessHandlerCallback dh, void *dh_cls,...)
Definition daemon.c:6355
_MHD_EXTERN enum MHD_Result MHD_run_wait(struct MHD_Daemon *daemon, int32_t millisec)
Definition daemon.c:6126
_MHD_EXTERN void MHD_set_panic_func(MHD_PanicCallback cb, void *cls)
Definition mhd_panic.c:94
void(* MHD_RequestCompletedCallback)(void *cls, struct MHD_Connection *connection, void **req_cls, enum MHD_RequestTerminationCode toe)
void(* MHD_NotifyConnectionCallback)(void *cls, struct MHD_Connection *connection, void **socket_context, enum MHD_ConnectionNotificationCode toe)
@ MHD_CONNECTION_NOTIFY_STARTED
@ MHD_CONNECTION_NOTIFY_CLOSED
@ MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN
@ MHD_REQUEST_TERMINATED_COMPLETED_OK
@ MHD_REQUEST_TERMINATED_WITH_ERROR
_MHD_EXTERN void MHD_destroy_response(struct MHD_Response *response)
Definition response.c:2294
_MHD_EXTERN enum MHD_Result MHD_add_connection(struct MHD_Daemon *daemon, MHD_socket client_socket, const struct sockaddr *addr, socklen_t addrlen)
Definition daemon.c:3813
_MHD_EXTERN enum MHD_Result MHD_is_feature_supported(enum MHD_FEATURE feature)
Definition daemon.c:9860
_MHD_EXTERN MHD_socket MHD_quiesce_daemon(struct MHD_Daemon *daemon)
Definition daemon.c:6400
_MHD_EXTERN const union MHD_DaemonInfo * MHD_get_daemon_info(struct MHD_Daemon *daemon, enum MHD_DaemonInfoType info_type,...)
Definition daemon.c:9743
_MHD_EXTERN uint32_t MHD_get_version_bin(void)
Definition daemon.c:9842
_MHD_EXTERN const char * MHD_get_version(void)
Definition daemon.c:9811
_MHD_EXTERN void MHD_free(void *ptr)
Definition daemon.c:213
MHD internal shared structures.
@ MHD_CONNECTION_HEADERS_SENDING
Definition internal.h:694
@ MHD_CONNECTION_INIT
Definition internal.h:618
@ MHD_CONNECTION_CLOSED
Definition internal.h:741
@ MHD_CONNECTION_NORMAL_BODY_READY
Definition internal.h:710
@ MHD_CONNECTION_CHUNKED_BODY_READY
Definition internal.h:720
#define MHD_D_IS_USING_POLL_(d)
Definition internal.h:2606
#define XDLL_insert(head, tail, element)
Definition internal.h:2765
MHD_EpollState
Definition internal.h:169
@ MHD_EPOLL_STATE_SUSPENDED
Definition internal.h:202
@ MHD_EPOLL_STATE_IN_EREADY_EDLL
Definition internal.h:192
@ MHD_EPOLL_STATE_READ_READY
Definition internal.h:181
@ MHD_EPOLL_STATE_IN_EPOLL_SET
Definition internal.h:197
@ MHD_EPOLL_STATE_WRITE_READY
Definition internal.h:187
@ MHD_EPOLL_STATE_ERROR
Definition internal.h:207
@ MHD_TLS_CONN_NO_TLS
Definition internal.h:760
@ MHD_TLS_CONN_INIT
Definition internal.h:761
@ MHD_TLS_CONN_CONNECTED
Definition internal.h:763
#define DLL_insert(head, tail, element)
Definition internal.h:2718
#define MHD_D_DOES_SCKT_FIT_FDSET_(sckt, d)
Definition internal.h:2661
@ MHD_EVENT_LOOP_INFO_PROCESS_READ
Definition internal.h:235
@ MHD_EVENT_LOOP_INFO_PROCESS
Definition internal.h:229
@ MHD_EVENT_LOOP_INFO_READ
Definition internal.h:219
@ MHD_EVENT_LOOP_INFO_WRITE
Definition internal.h:224
@ MHD_EVENT_LOOP_INFO_CLEANUP
Definition internal.h:241
#define MHD_D_IS_USING_SELECT_(d)
Definition internal.h:2602
#define EDLL_insert(head, tail, element)
Definition internal.h:2812
void *(* LogCallback)(void *cls, const char *uri, struct MHD_Connection *con)
Definition internal.h:1871
_MHD_static_inline struct MHD_Daemon * MHD_get_master(struct MHD_Daemon *const daemon)
Definition internal.h:2960
#define _MHD_DROP_CONST(ptr)
Definition internal.h:77
#define MHD_D_GET_FD_SETSIZE_(d)
Definition internal.h:2655
#define MHD_BUF_INC_SIZE
Definition internal.h:142
#define EDLL_remove(head, tail, element)
Definition internal.h:2832
#define PRIu64
Definition internal.h:53
#define XDLL_remove(head, tail, element)
Definition internal.h:2787
#define MHD_D_IS_USING_THREAD_PER_CONN_(d)
Definition internal.h:2638
#define DLL_remove(head, tail, element)
Definition internal.h:2740
#define MHD_D_IS_USING_THREADS_(d)
Definition internal.h:2634
#define MHD_TEST_ALLOW_SUSPEND_RESUME
Definition internal.h:249
size_t(* UnescapeCallback)(void *cls, struct MHD_Connection *conn, char *uri)
Definition internal.h:1885
#define MHD_D_IS_USING_EPOLL_(d)
Definition internal.h:2610
#define MHD_D_IS_THREAD_SAFE_(d)
Definition internal.h:2643
MHD_tristate
Definition internal.h:156
@ _MHD_UNKNOWN
Definition internal.h:157
@ _MHD_YES
Definition internal.h:161
@ _MHD_OFF
Definition internal.h:158
@ _MHD_NO
Definition internal.h:159
void MHD_init_mem_pools_(void)
Definition memorypool.c:229
void MHD_pool_destroy(struct MemoryPool *pool)
Definition memorypool.c:361
struct MemoryPool * MHD_pool_create(size_t max)
Definition memorypool.c:290
memory pool; mostly used for efficient (de)allocation for each connection and bounding memory use for...
types alignment macros
#define mhd_assert(ignore)
Definition mhd_assert.h:45
void * MHD_calloc_(size_t nelem, size_t elsize)
Definition mhd_compat.c:98
Header for platform missing functions.
#define MHD_strerror_(errnum)
Definition mhd_compat.h:46
Header for platform-independent inter-thread communication.
#define MHD_PANIC(msg)
Definition mhd_itc.h:45
#define MHD_ITC_IS_INVALID_(itc)
Definition mhd_itc.h:385
#define MHD_itc_destroy_chk_(itc)
Definition mhd_itc.h:371
limits values definitions
#define SSIZE_MAX
Definition mhd_limits.h:121
#define UINT64_MAX
Definition mhd_limits.h:93
#define SIZE_MAX
Definition mhd_limits.h:111
#define INT_MAX
Definition mhd_limits.h:45
#define ULLONG_MAX
Definition mhd_limits.h:69
#define TIMEVAL_TV_SEC_MAX
Definition mhd_limits.h:150
#define UINT_MAX
Definition mhd_limits.h:53
#define INT64_MAX
Definition mhd_limits.h:101
Header for platform-independent locks abstraction.
#define MHD_mutex_unlock_chk_(ignore)
Definition mhd_locks.h:198
#define MHD_mutex_destroy_(ignore)
Definition mhd_locks.h:193
#define MHD_mutex_unlock_(ignore)
Definition mhd_locks.h:197
#define MHD_mutex_lock_(ignore)
Definition mhd_locks.h:195
#define MHD_mutex_init_(ignore)
Definition mhd_locks.h:192
#define MHD_mutex_lock_chk_(ignore)
Definition mhd_locks.h:196
#define MHD_mutex_destroy_chk_(ignore)
Definition mhd_locks.h:194
#define NULL
uint64_t MHD_monotonic_msec_counter(void)
void MHD_monotonic_sec_counter_finish(void)
void MHD_monotonic_sec_counter_init(void)
internal monotonic clock functions implementations
#define MHD_DAUTH_DEF_TIMEOUT_
#define _(String)
Definition mhd_options.h:42
#define _MHD_EXTERN
Definition mhd_options.h:53
#define MHD_DAUTH_DEF_MAX_NC_
void MHD_send_init_static_vars_(void)
Definition mhd_send.c:157
Declarations of send() wrappers.
int MHD_socket_noninheritable_(MHD_socket sock)
int MHD_socket_nonblocking_(MHD_socket sock)
int MHD_add_to_fd_set_(MHD_socket fd, fd_set *set, MHD_socket *max_fd, int fd_setsize)
MHD_socket MHD_socket_create_listen_(int pf)
#define MHD_SCKT_ERR_IS_DISCNN_BEFORE_ACCEPT_(err)
#define MHD_SCKT_FD_FITS_FDSET_SETSIZE_(fd, pset, setsize)
#define MHD_SCKT_ERR_IS_(err, code)
int MHD_SCKT_OPT_BOOL_
#define SOCK_NONBLOCK_OR_ZERO
#define MHD_socket_close_(fd)
#define MHD_SCKT_ERR_IS_EAGAIN_(err)
#define MHD_SCKT_ERR_IS_LOW_RESOURCES_(err)
#define MHD_SCKT_EINTR_
#define _MHD_SYS_DEFAULT_FD_SETSIZE
#define MHD_socket_strerr_(err)
#define MHD_socket_last_strerr_()
#define MHD_socket_get_error_()
#define SOCK_NOSIGPIPE_OR_ZERO
#define MHD_SCKT_EINVAL_
#define MHD_socket_close_chk_(fd)
#define MHD_SCKT_ERR_IS_EINTR_(err)
#define MHD_socket_fset_error_(err)
#define MHD_SCKT_SEND_MAX_SIZE_
#define MHD_recv_(s, b, l)
#define MHD_send_(s, b, l)
#define MHD_SCKT_LAST_ERR_IS_(code)
#define MHD_SYS_select_(n, r, w, e, t)
#define SOCK_CLOEXEC_OR_ZERO
size_t MHD_str_pct_decode_in_place_lenient_(char *str, bool *broken_encoding)
Definition mhd_str.c:1994
size_t MHD_str_pct_decode_in_place_strict_(char *str)
Definition mhd_str.c:1938
Header for string manipulating helpers.
#define _MHD_S_STR_W_LEN(str)
#define MHD_STATICSTR_LEN_(macro)
Header for platform-independent threads abstraction.
#define MHD_thread_handle_ID_set_current_thread_ID_(hndl_id_ptr)
#define MHD_thread_handle_ID_is_current_thread_(hndl_id)
#define MHD_thread_handle_ID_is_valid_handle_(hndl_id)
#define MHD_thread_handle_ID_join_thread_(hndl_id)
#define MHD_thread_handle_ID_set_invalid_(hndl_id_ptr)
#define MHD_thread_handle_ID_is_valid_ID_(hndl_id)
#define MHD_create_named_thread_(t, n, s, r, a)
int MHD_socket
Definition microhttpd.h:206
MHD_FEATURE
@ MHD_FEATURE_POSTPROCESSOR
@ MHD_FEATURE_SHUTDOWN_LISTEN_SOCKET
@ MHD_FEATURE_DIGEST_AUTH_USERHASH
@ MHD_FEATURE_THREADS
@ MHD_FEATURE_DIGEST_AUTH_AUTH_INT
@ MHD_FEATURE_DIGEST_AUTH_SHA256
@ MHD_FEATURE_SENDFILE
@ MHD_FEATURE_AUTODETECT_BIND_PORT
@ MHD_FEATURE_LARGE_FILE
@ MHD_FEATURE_DIGEST_AUTH_SHA512_256
@ MHD_FEATURE_EXTERN_HASH
@ MHD_FEATURE_HTTPS_CERT_CALLBACK
@ MHD_FEATURE_BASIC_AUTH
@ MHD_FEATURE_DIGEST_AUTH
@ MHD_FEATURE_IPv6
@ MHD_FEATURE_POLL
@ MHD_FEATURE_THREAD_NAMES
@ MHD_FEATURE_DEBUG_BUILD
@ MHD_FEATURE_FLEXIBLE_FD_SETSIZE
@ MHD_FEATURE_EPOLL
@ MHD_FEATURE_TLS
@ MHD_FEATURE_HTTPS_KEY_PASSWORD
@ MHD_FEATURE_AUTOSUPPRESS_SIGPIPE
@ MHD_FEATURE_RESPONSES_SHARED_FD
@ MHD_FEATURE_MESSAGES
@ MHD_FEATURE_IPv6_ONLY
@ MHD_FEATURE_DIGEST_AUTH_ALGO_SESSION
@ MHD_FEATURE_COOKIE_PARSING
@ MHD_FEATURE_DIGEST_AUTH_MD5
@ MHD_FEATURE_UPGRADE
@ MHD_FEATURE_SOCKETPAIR
@ MHD_FEATURE_TCP_FASTOPEN
@ MHD_FEATURE_DIGEST_AUTH_RFC2069
@ MHD_FEATURE_HTTPS_CERT_CALLBACK2
MHD_OPTION
MHD options.
@ MHD_OPTION_HTTPS_PRIORITIES_APPEND
@ MHD_OPTION_CONNECTION_MEMORY_INCREMENT
@ MHD_OPTION_HTTPS_CRED_TYPE
@ MHD_OPTION_URI_LOG_CALLBACK
@ MHD_OPTION_HTTPS_CERT_CALLBACK2
@ MHD_OPTION_DIGEST_AUTH_DEFAULT_NONCE_TIMEOUT
@ MHD_OPTION_CLIENT_DISCIPLINE_LVL
@ MHD_OPTION_SOCK_ADDR_LEN
@ MHD_OPTION_APP_FD_SETSIZE
@ MHD_OPTION_SIGPIPE_HANDLED_BY_APP
@ MHD_OPTION_UNESCAPE_CALLBACK
@ MHD_OPTION_EXTERNAL_LOGGER
@ MHD_OPTION_TLS_NO_ALPN
@ MHD_OPTION_LISTEN_BACKLOG_SIZE
@ MHD_OPTION_HTTPS_PRIORITIES
@ MHD_OPTION_HTTPS_MEM_DHPARAMS
@ MHD_OPTION_NOTIFY_CONNECTION
@ MHD_OPTION_LISTENING_ADDRESS_REUSE
@ MHD_OPTION_THREAD_POOL_SIZE
@ MHD_OPTION_CONNECTION_LIMIT
@ MHD_OPTION_PER_IP_CONNECTION_LIMIT
@ MHD_OPTION_DIGEST_AUTH_DEFAULT_MAX_NC
@ MHD_OPTION_TCP_FASTOPEN_QUEUE_SIZE
@ MHD_OPTION_HTTPS_MEM_CERT
@ MHD_OPTION_SERVER_INSANITY
@ MHD_OPTION_LISTEN_SOCKET
@ MHD_OPTION_HTTPS_MEM_KEY
@ MHD_OPTION_DIGEST_AUTH_RANDOM
@ MHD_OPTION_HTTPS_KEY_PASSWORD
@ MHD_OPTION_NONCE_NC_SIZE
@ MHD_OPTION_ALLOW_BIN_ZERO_IN_URI_PATH
@ MHD_OPTION_CONNECTION_MEMORY_LIMIT
@ MHD_OPTION_THREAD_STACK_SIZE
@ MHD_OPTION_DIGEST_AUTH_RANDOM_COPY
@ MHD_OPTION_ARRAY
@ MHD_OPTION_STRICT_FOR_CLIENT
@ MHD_OPTION_DIGEST_AUTH_NONCE_BIND_TYPE
@ MHD_OPTION_SOCK_ADDR
@ MHD_OPTION_CONNECTION_TIMEOUT
@ MHD_OPTION_GNUTLS_PSK_CRED_HANDLER
@ MHD_OPTION_END
@ MHD_OPTION_HTTPS_MEM_TRUST
@ MHD_OPTION_HTTPS_CERT_CALLBACK
@ MHD_OPTION_NOTIFY_COMPLETED
MHD_DisableSanityCheck
MHD_Result
Definition microhttpd.h:163
@ MHD_YES
Definition microhttpd.h:172
@ MHD_NO
Definition microhttpd.h:167
enum MHD_Result(* MHD_AcceptPolicyCallback)(void *cls, const struct sockaddr *addr, socklen_t addrlen)
#define MHD_UNSIGNED_LONG_LONG
Definition microhttpd.h:311
enum MHD_Result(* MHD_AccessHandlerCallback)(void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **req_cls)
int fd
#define MHD_POSIX_SOCKETS
Definition microhttpd.h:205
void * data
#define MHD_INVALID_SOCKET
Definition microhttpd.h:207
int(* MHD_PskServerCredentialsCallback)(void *cls, const struct MHD_Connection *connection, const char *username, void **psk, size_t *psk_size)
#define MHD_VERSION
Definition microhttpd.h:104
MHD_DaemonInfoType
@ MHD_DAEMON_INFO_MAC_KEY_SIZE
@ MHD_DAEMON_INFO_BIND_PORT
@ MHD_DAEMON_INFO_EPOLL_FD
@ MHD_DAEMON_INFO_FLAGS
@ MHD_DAEMON_INFO_KEY_SIZE
@ MHD_DAEMON_INFO_CURRENT_CONNECTIONS
@ MHD_DAEMON_INFO_LISTEN_FD
MHD_FLAG
Flags for the struct MHD_Daemon.
@ MHD_USE_EPOLL
@ MHD_ALLOW_SUSPEND_RESUME
@ MHD_USE_TCP_FASTOPEN
@ MHD_USE_THREAD_PER_CONNECTION
@ MHD_USE_AUTO
@ MHD_USE_POST_HANDSHAKE_AUTH_SUPPORT
@ MHD_USE_TURBO
@ MHD_USE_IPv6
@ MHD_USE_DUAL_STACK
@ MHD_USE_POLL
@ MHD_USE_SELECT_INTERNALLY
@ MHD_USE_TLS
@ MHD_USE_INSECURE_TLS_EARLY_DATA
@ MHD_ALLOW_UPGRADE
@ MHD_USE_NO_LISTEN_SOCKET
@ MHD_USE_PEDANTIC_CHECKS
@ MHD_USE_INTERNAL_POLLING_THREAD
@ MHD_USE_ITC
@ MHD_USE_NO_THREAD_SAFETY
@ MHD_DAUTH_BIND_NONCE_URI
@ MHD_DAUTH_BIND_NONCE_URI_PARAMS
platform-specific includes for libmicrohttpd
time_t _MHD_TIMEVAL_TV_SEC_TYPE
Definition platform.h:126
Methods for managing response objects.
MHD_socket socket_fd
Definition internal.h:1489
enum MHD_tristate sk_nodelay
Definition internal.h:1515
struct MHD_Connection * prev
Definition internal.h:1347
socklen_t addr_len
Definition internal.h:1469
enum MHD_ConnectionEventLoopInfo event_loop_info
Definition internal.h:1576
enum MHD_tristate is_nonip
Definition internal.h:1495
struct MHD_itc_ resume_itc
Definition internal.h:1657
volatile bool resuming
Definition internal.h:1627
void * socket_context
Definition internal.h:1395
uint64_t last_activity
Definition internal.h:1475
struct MHD_Request rq
Definition internal.h:1371
struct MHD_Connection * nextX
Definition internal.h:1356
struct MHD_Connection * next
Definition internal.h:1342
size_t read_buffer_offset
Definition internal.h:1442
struct MHD_Reply rp
Definition internal.h:1376
struct MemoryPool * pool
Definition internal.h:1386
enum MHD_CONNECTION_STATE state
Definition internal.h:1571
struct MHD_Connection * prevX
Definition internal.h:1361
struct MHD_Daemon * daemon
Definition internal.h:1366
bool sk_spipe_suppress
Definition internal.h:1505
uint64_t connection_timeout_ms
Definition internal.h:1482
struct sockaddr_storage * addr
Definition internal.h:1421
size_t read_buffer_size
Definition internal.h:1436
enum MHD_tristate sk_corked
Definition internal.h:1510
size_t pool_size
Definition internal.h:2172
MHD_NotifyConnectionCallback notify_connection
Definition internal.h:2079
MHD_AccessHandlerCallback default_handler
Definition internal.h:1903
LogCallback uri_log_callback
Definition internal.h:2093
bool data_already_pending
Definition internal.h:2294
union MHD_DaemonInfo daemon_info_dummy_port
Definition internal.h:2542
struct MHD_Connection * normal_timeout_tail
Definition internal.h:2036
bool at_limit
Definition internal.h:2272
struct MHD_Connection * new_connections_tail
Definition internal.h:1926
int client_discipline
Definition internal.h:2318
uint16_t port
Definition internal.h:2116
bool listen_nonblk
Definition internal.h:2147
unsigned int connection_limit
Definition internal.h:2299
void * unescape_callback_cls
Definition internal.h:2108
enum MHD_DisableSanityCheck insanity_level
Definition internal.h:2233
struct MHD_Connection * connections_tail
Definition internal.h:1936
struct MHD_Connection * suspended_connections_tail
Definition internal.h:1946
union MHD_DaemonInfo daemon_info_dummy_listen_fd
Definition internal.h:2520
struct MHD_Connection * manual_timeout_head
Definition internal.h:2044
unsigned int listen_backlog_size
Definition internal.h:2514
struct MHD_Connection * normal_timeout_head
Definition internal.h:2029
union MHD_DaemonInfo daemon_info_dummy_flags
Definition internal.h:2537
MHD_RequestCompletedCallback notify_completed
Definition internal.h:2068
struct MHD_Connection * cleanup_head
Definition internal.h:1951
unsigned int connections
Definition internal.h:2167
struct MHD_itc_ itc
Definition internal.h:2251
int listening_address_reuse
Definition internal.h:2244
uint64_t connection_timeout_ms
Definition internal.h:2306
void * apc_cls
Definition internal.h:2062
unsigned int per_ip_connection_limit
Definition internal.h:2312
struct MHD_Connection * manual_timeout_tail
Definition internal.h:2051
volatile bool shutdown
Definition internal.h:2256
union MHD_DaemonInfo daemon_info_dummy_num_connections
Definition internal.h:2532
enum MHD_FLAG options
Definition internal.h:1916
void * notify_connection_cls
Definition internal.h:2084
struct MHD_Connection * cleanup_tail
Definition internal.h:1956
bool sigpipe_blocked
Definition internal.h:2346
UnescapeCallback unescape_callback
Definition internal.h:2103
void * notify_completed_cls
Definition internal.h:2073
volatile bool was_quiesced
Definition internal.h:2263
struct MHD_Connection * suspended_connections_head
Definition internal.h:1941
struct MHD_Connection * new_connections_head
Definition internal.h:1921
int allow_bzero_in_url
Definition internal.h:2325
enum MHD_tristate listen_is_unix
Definition internal.h:1961
volatile bool resuming
Definition internal.h:2277
void * default_handler_cls
Definition internal.h:1908
struct MHD_Connection * connections_head
Definition internal.h:1931
MHD_AcceptPolicyCallback apc
Definition internal.h:2057
volatile bool have_new
Definition internal.h:2283
size_t pool_increment
Definition internal.h:2177
MHD_socket listen_fd
Definition internal.h:2142
void * per_ip_connection_count
Definition internal.h:2159
void * uri_log_callback_cls
Definition internal.h:2098
struct MHD_Daemon * master
Definition internal.h:2134
enum MHD_OPTION option
struct MHD_Response * response
Definition internal.h:1282
void * client_context
Definition internal.h:1198
bool client_aware
Definition internal.h:1205
const char *const str
const size_t len
void * tfind(const void *vkey, void *const *vrootp, int(*compar)(const void *, const void *))
Definition tsearch.c:67
void * tdelete(const void *vkey, void **vrootp, int(*compar)(const void *, const void *))
Definition tsearch.c:92
void * tsearch(const void *vkey, void **vrootp, int(*compar)(const void *, const void *))
Definition tsearch.c:32
enum MHD_FLAG flags
unsigned int num_connections
MHD_socket listen_fd