libmicrohttpd

HTTP/1.x server C library (MHD 1.x, stable)
Log | Files | Refs | Submodules | README | LICENSE

test_quiesce.c (24062B)


      1 /*
      2      This file is part of libmicrohttpd
      3      Copyright (C) 2013, 2015 Christian Grothoff
      4      Copyright (C) 2014-2022 Evgeny Grin (Karlson2k)
      5 
      6      libmicrohttpd is free software; you can redistribute it and/or modify
      7      it under the terms of the GNU General Public License as published
      8      by the Free Software Foundation; either version 2, or (at your
      9      option) any later version.
     10 
     11      libmicrohttpd is distributed in the hope that it will be useful, but
     12      WITHOUT ANY WARRANTY; without even the implied warranty of
     13      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     14      General Public License for more details.
     15 
     16      You should have received a copy of the GNU General Public License
     17      along with libmicrohttpd; see the file COPYING.  If not, write to the
     18      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
     19      Boston, MA 02110-1301, USA.
     20 */
     21 /**
     22  * @file test_quiesce.c
     23  * @brief  Testcase for libmicrohttpd quiescing
     24  * @author Christian Grothoff
     25  * @author Karlson2k (Evgeny Grin)
     26  */
     27 
     28 #include "MHD_config.h"
     29 #include "platform.h"
     30 #include <curl/curl.h>
     31 #include <microhttpd.h>
     32 #include <stdlib.h>
     33 #include <string.h>
     34 #include <time.h>
     35 #include <sys/types.h>
     36 #include <pthread.h>
     37 #include <errno.h>
     38 #include "mhd_sockets.h" /* only macros used */
     39 #include "mhd_has_in_name.h"
     40 #include "mhd_has_param.h"
     41 
     42 /* Turn any MHD_PANIC() or failing mhd_assert() reached from this
     43    test into a marked, classifiable test error (TESTING.md, P5). */
     44 #include "mhd_panic_tripwire.h"
     45 
     46 
     47 #ifndef WINDOWS
     48 #include <unistd.h>
     49 #include <sys/socket.h>
     50 #endif
     51 
     52 #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2
     53 #undef MHD_CPU_COUNT
     54 #endif
     55 #if ! defined(MHD_CPU_COUNT)
     56 #define MHD_CPU_COUNT 2
     57 #endif
     58 
     59 
     60 #ifndef _MHD_INSTRMACRO
     61 /* Quoted macro parameter */
     62 #define _MHD_INSTRMACRO(a) #a
     63 #endif /* ! _MHD_INSTRMACRO */
     64 #ifndef _MHD_STRMACRO
     65 /* Quoted expanded macro parameter */
     66 #define _MHD_STRMACRO(a) _MHD_INSTRMACRO (a)
     67 #endif /* ! _MHD_STRMACRO */
     68 
     69 #if defined(HAVE___FUNC__)
     70 #define externalErrorExit(ignore) \
     71     _externalErrorExit_func(NULL, __func__, __LINE__)
     72 #define externalErrorExitDesc(errDesc) \
     73     _externalErrorExit_func(errDesc, __func__, __LINE__)
     74 #define libcurlErrorExit(ignore) \
     75     _libcurlErrorExit_func(NULL, __func__, __LINE__)
     76 #define libcurlErrorExitDesc(errDesc) \
     77     _libcurlErrorExit_func(errDesc, __func__, __LINE__)
     78 #define mhdErrorExit(ignore) \
     79     _mhdErrorExit_func(NULL, __func__, __LINE__)
     80 #define mhdErrorExitDesc(errDesc) \
     81     _mhdErrorExit_func(errDesc, __func__, __LINE__)
     82 #define checkCURLE_OK(libcurlcall) \
     83     _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), \
     84                         __func__, __LINE__)
     85 #elif defined(HAVE___FUNCTION__)
     86 #define externalErrorExit(ignore) \
     87     _externalErrorExit_func(NULL, __FUNCTION__, __LINE__)
     88 #define externalErrorExitDesc(errDesc) \
     89     _externalErrorExit_func(errDesc, __FUNCTION__, __LINE__)
     90 #define libcurlErrorExit(ignore) \
     91     _libcurlErrorExit_func(NULL, __FUNCTION__, __LINE__)
     92 #define libcurlErrorExitDesc(errDesc) \
     93     _libcurlErrorExit_func(errDesc, __FUNCTION__, __LINE__)
     94 #define mhdErrorExit(ignore) \
     95     _mhdErrorExit_func(NULL, __FUNCTION__, __LINE__)
     96 #define mhdErrorExitDesc(errDesc) \
     97     _mhdErrorExit_func(errDesc, __FUNCTION__, __LINE__)
     98 #define checkCURLE_OK(libcurlcall) \
     99     _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), \
    100                         __FUNCTION__, __LINE__)
    101 #else
    102 #define externalErrorExit(ignore) _externalErrorExit_func(NULL, NULL, __LINE__)
    103 #define externalErrorExitDesc(errDesc) \
    104   _externalErrorExit_func(errDesc, NULL, __LINE__)
    105 #define libcurlErrorExit(ignore) _libcurlErrorExit_func(NULL, NULL, __LINE__)
    106 #define libcurlErrorExitDesc(errDesc) \
    107   _libcurlErrorExit_func(errDesc, NULL, __LINE__)
    108 #define mhdErrorExit(ignore) _mhdErrorExit_func(NULL, NULL, __LINE__)
    109 #define mhdErrorExitDesc(errDesc) _mhdErrorExit_func(errDesc, NULL, __LINE__)
    110 #define checkCURLE_OK(libcurlcall) \
    111   _checkCURLE_OK_func((libcurlcall), _MHD_STRMACRO(libcurlcall), NULL, __LINE__)
    112 #endif
    113 
    114 
    115 _MHD_NORETURN static void
    116 _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
    117 {
    118   fflush (stdout);
    119   if ((NULL != errDesc) && (0 != errDesc[0]))
    120     fprintf (stderr, "%s", errDesc);
    121   else
    122     fprintf (stderr, "System or external library call failed");
    123   if ((NULL != funcName) && (0 != funcName[0]))
    124     fprintf (stderr, " in %s", funcName);
    125   if (0 < lineNum)
    126     fprintf (stderr, " at line %d", lineNum);
    127 
    128   fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
    129            strerror (errno));
    130 #ifdef MHD_WINSOCK_SOCKETS
    131   fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
    132 #endif /* MHD_WINSOCK_SOCKETS */
    133   fflush (stderr);
    134   exit (99);
    135 }
    136 
    137 
    138 static char libcurl_errbuf[CURL_ERROR_SIZE] = "";
    139 
    140 _MHD_NORETURN static void
    141 _libcurlErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
    142 {
    143   fflush (stdout);
    144   if ((NULL != errDesc) && (0 != errDesc[0]))
    145     fprintf (stderr, "%s", errDesc);
    146   else
    147     fprintf (stderr, "CURL library call failed");
    148   if ((NULL != funcName) && (0 != funcName[0]))
    149     fprintf (stderr, " in %s", funcName);
    150   if (0 < lineNum)
    151     fprintf (stderr, " at line %d", lineNum);
    152 
    153   fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
    154            strerror (errno));
    155 #ifdef MHD_WINSOCK_SOCKETS
    156   fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
    157 #endif /* MHD_WINSOCK_SOCKETS */
    158   if (0 != libcurl_errbuf[0])
    159     fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf);
    160 
    161   fflush (stderr);
    162   exit (99);
    163 }
    164 
    165 
    166 _MHD_NORETURN static void
    167 _mhdErrorExit_func (const char *errDesc, const char *funcName, int lineNum)
    168 {
    169   fflush (stdout);
    170   if ((NULL != errDesc) && (0 != errDesc[0]))
    171     fprintf (stderr, "%s", errDesc);
    172   else
    173     fprintf (stderr, "MHD unexpected error");
    174   if ((NULL != funcName) && (0 != funcName[0]))
    175     fprintf (stderr, " in %s", funcName);
    176   if (0 < lineNum)
    177     fprintf (stderr, " at line %d", lineNum);
    178 
    179   fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
    180            strerror (errno));
    181 #ifdef MHD_WINSOCK_SOCKETS
    182   fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ());
    183 #endif /* MHD_WINSOCK_SOCKETS */
    184 
    185   fflush (stderr);
    186   exit (8);
    187 }
    188 
    189 
    190 static void
    191 _checkCURLE_OK_func (CURLcode code, const char *curlFunc,
    192                      const char *funcName, int lineNum)
    193 {
    194   if (CURLE_OK == code)
    195     return;
    196 
    197   fflush (stdout);
    198   if ((NULL != curlFunc) && (0 != curlFunc[0]))
    199     fprintf (stderr, "'%s' resulted in '%s'", curlFunc,
    200              curl_easy_strerror (code));
    201   else
    202     fprintf (stderr, "libcurl function call resulted in '%s'",
    203              curl_easy_strerror (code));
    204   if ((NULL != funcName) && (0 != funcName[0]))
    205     fprintf (stderr, " in %s", funcName);
    206   if (0 < lineNum)
    207     fprintf (stderr, " at line %d", lineNum);
    208 
    209   fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno,
    210            strerror (errno));
    211   if (0 != libcurl_errbuf[0])
    212     fprintf (stderr, "Last libcurl error description: %s\n", libcurl_errbuf);
    213 
    214   fflush (stderr);
    215   exit (9);
    216 }
    217 
    218 
    219 /* Could be increased to facilitate debugging */
    220 #define TIMEOUTS_VAL 4
    221 
    222 #define MHD_URI_BASE_PATH "/hello_world"
    223 
    224 /* Global parameters */
    225 static int verbose;                 /**< Be verbose */
    226 static int oneone;                  /**< If false use HTTP/1.0 for requests*/
    227 static uint16_t global_port;        /**< MHD daemons listen port number */
    228 
    229 struct CBC
    230 {
    231   char *buf;
    232   size_t pos;
    233   size_t size;
    234 };
    235 
    236 static size_t
    237 copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
    238 {
    239   struct CBC *cbc = ctx;
    240 
    241   if (cbc->pos + size * nmemb > cbc->size)
    242     return 0;                   /* overflow */
    243   memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb);
    244   cbc->pos += size * nmemb;
    245   return size * nmemb;
    246 }
    247 
    248 
    249 static enum MHD_Result
    250 ahc_echo (void *cls,
    251           struct MHD_Connection *connection,
    252           const char *url,
    253           const char *method,
    254           const char *version,
    255           const char *upload_data, size_t *upload_data_size,
    256           void **req_cls)
    257 {
    258   static int ptr;
    259   struct MHD_Response *response;
    260   (void) cls;
    261   (void) version; (void) upload_data; (void) upload_data_size;       /* Unused. Silent compiler warning. */
    262 
    263   if (0 != strcmp (MHD_HTTP_METHOD_GET, method))
    264   {
    265     fprintf (stderr, "Unexpected HTTP method '%s'. ", method);
    266     externalErrorExit ();
    267   }
    268   if (&ptr != *req_cls)
    269   {
    270     *req_cls = &ptr;
    271     return MHD_YES;
    272   }
    273   *req_cls = NULL;
    274   response = MHD_create_response_from_buffer_copy (strlen (url),
    275                                                    (const void *) url);
    276   if (NULL == response)
    277     mhdErrorExitDesc ("MHD_create_response failed");
    278   /* Make sure that connection will not be reused */
    279   if (MHD_NO == MHD_add_response_header (response, MHD_HTTP_HEADER_CONNECTION,
    280                                          "close"))
    281     mhdErrorExitDesc ("MHD_add_response_header() failed");
    282   if (MHD_NO == MHD_queue_response (connection, MHD_HTTP_OK, response))
    283     mhdErrorExitDesc ("MHD_queue_response() failed");
    284   MHD_destroy_response (response);
    285   return MHD_YES;
    286 }
    287 
    288 
    289 static void
    290 request_completed (void *cls, struct MHD_Connection *connection,
    291                    void **req_cls, enum MHD_RequestTerminationCode code)
    292 {
    293   int *done = (int *) cls;
    294   (void) connection; (void) req_cls; (void) code;    /* Unused. Silent compiler warning. */
    295   if (MHD_REQUEST_TERMINATED_COMPLETED_OK != code)
    296   {
    297     fprintf (stderr, "Unexpected termination code: %d. ", (int) code);
    298     mhdErrorExit ();
    299   }
    300   *done = 1;
    301   if (verbose)
    302     printf ("Notify callback has been called with OK code.\n");
    303 }
    304 
    305 
    306 static void *
    307 ServeOneRequest (void *param)
    308 {
    309   struct MHD_Daemon *d;
    310   fd_set rs;
    311   fd_set ws;
    312   fd_set es;
    313   MHD_socket fd, max;
    314   time_t start;
    315   struct timeval tv;
    316   volatile int done = 0;
    317 
    318   if (NULL == param)
    319     externalErrorExit ();
    320 
    321   fd = *((MHD_socket *) param);
    322 
    323   d = MHD_start_daemon (MHD_USE_ERROR_LOG,
    324                         0, NULL, NULL, &ahc_echo, NULL,
    325                         MHD_OPTION_LISTEN_SOCKET, fd,
    326                         MHD_OPTION_NOTIFY_COMPLETED, &request_completed, &done,
    327                         MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE,
    328                         MHD_OPTION_END);
    329   if (d == NULL)
    330     mhdErrorExit ();
    331 
    332   if (verbose)
    333     printf ("Started MHD daemon in ServeOneRequest().\n");
    334 
    335   start = time (NULL);
    336   while ((time (NULL) - start < TIMEOUTS_VAL * 2) && done == 0)
    337   {
    338     max = 0;
    339     FD_ZERO (&rs);
    340     FD_ZERO (&ws);
    341     FD_ZERO (&es);
    342     if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max))
    343       mhdErrorExit ("MHD_get_fdset() failed");
    344     tv.tv_sec = 0;
    345     tv.tv_usec = 100000;
    346     if (-1 == MHD_SYS_select_ (max + 1, &rs, &ws, &es, &tv))
    347     {
    348 #ifdef MHD_POSIX_SOCKETS
    349       if (EINTR != errno)
    350         externalErrorExitDesc ("Unexpected select() error");
    351 #else
    352       if ((WSAEINVAL != WSAGetLastError ()) ||
    353           (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
    354         externalErrorExitDesc ("Unexpected select() error");
    355       Sleep ((DWORD) (tv.tv_sec * 1000 + tv.tv_usec / 1000));
    356 #endif
    357     }
    358     MHD_run (d);
    359   }
    360   if (! done)
    361     mhdErrorExit ("ServeOneRequest() failed and finished by timeout");
    362   fd = MHD_quiesce_daemon (d);
    363   if (MHD_INVALID_SOCKET == fd)
    364     mhdErrorExit ("MHD_quiesce_daemon() failed in ServeOneRequest()");
    365 
    366   MHD_stop_daemon (d);
    367   return NULL;
    368 }
    369 
    370 
    371 static CURL *
    372 setupCURL (void *cbc)
    373 {
    374   CURL *c;
    375 
    376   c = curl_easy_init ();
    377   if (NULL == c)
    378     libcurlErrorExitDesc ("curl_easy_init() failed");
    379 
    380   if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) ||
    381       (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROXY, "")) ||
    382       (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL,
    383                                      "http://127.0.0.1" MHD_URI_BASE_PATH)) ||
    384       (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) global_port)) ||
    385       (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION,
    386                                      &copyBuffer)) ||
    387       (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc)) ||
    388       (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT,
    389                                      (long) (TIMEOUTS_VAL / 2))) ||
    390       (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT,
    391                                      (long) TIMEOUTS_VAL)) ||
    392       (CURLE_OK != curl_easy_setopt (c, CURLOPT_ERRORBUFFER,
    393                                      libcurl_errbuf)) ||
    394       (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) ||
    395       (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION,
    396                                      (oneone) ?
    397                                      CURL_HTTP_VERSION_1_1 :
    398                                      CURL_HTTP_VERSION_1_0)))
    399     libcurlErrorExitDesc ("curl_easy_setopt() failed");
    400   return c;
    401 }
    402 
    403 
    404 static unsigned int
    405 testGet (unsigned int type, int pool_count, uint32_t poll_flag)
    406 {
    407   struct MHD_Daemon *d;
    408   CURL *c;
    409   char buf[2048];
    410   struct CBC cbc;
    411   MHD_socket fd;
    412   pthread_t thrd;
    413   char *thrdRet;
    414 
    415   if (verbose)
    416     printf ("testGet(%u, %d, %u) test started.\n",
    417             type, pool_count, (unsigned int) poll_flag);
    418 
    419   cbc.buf = buf;
    420   cbc.size = sizeof(buf);
    421   cbc.pos = 0;
    422   if (pool_count > 0)
    423   {
    424     d = MHD_start_daemon (type | MHD_USE_ERROR_LOG | MHD_USE_ITC
    425                           | (enum MHD_FLAG) poll_flag,
    426                           global_port, NULL, NULL, &ahc_echo, NULL,
    427                           MHD_OPTION_THREAD_POOL_SIZE,
    428                           (unsigned int) pool_count,
    429                           MHD_OPTION_END);
    430 
    431   }
    432   else
    433   {
    434     d = MHD_start_daemon (type | MHD_USE_ERROR_LOG | MHD_USE_ITC
    435                           | (enum MHD_FLAG) poll_flag,
    436                           global_port, NULL, NULL, &ahc_echo, NULL,
    437                           MHD_OPTION_END);
    438   }
    439   if (d == NULL)
    440     mhdErrorExitDesc ("MHD_start_daemon() failed");
    441   if (0 == global_port)
    442   {
    443     const union MHD_DaemonInfo *dinfo;
    444     dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
    445     if ((NULL == dinfo) || (0 == dinfo->port) )
    446       mhdErrorExit ();
    447     global_port = dinfo->port;
    448   }
    449 
    450   c = setupCURL (&cbc);
    451 
    452   checkCURLE_OK (curl_easy_perform (c));
    453 
    454   if (cbc.pos != strlen (MHD_URI_BASE_PATH))
    455   {
    456     fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ",
    457              (unsigned) cbc.pos, (int) cbc.pos, cbc.buf,
    458              (unsigned) strlen (MHD_URI_BASE_PATH));
    459     mhdErrorExitDesc ("Wrong returned data length");
    460   }
    461   if (0 != strncmp (MHD_URI_BASE_PATH, cbc.buf, strlen (MHD_URI_BASE_PATH)))
    462   {
    463     fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos, cbc.buf);
    464     mhdErrorExitDesc ("Wrong returned data");
    465   }
    466   if (verbose)
    467     printf ("Received valid response data.\n");
    468 
    469   fd = MHD_quiesce_daemon (d);
    470   if (MHD_INVALID_SOCKET == fd)
    471     mhdErrorExitDesc ("MHD_quiesce_daemon failed");
    472 
    473   if (0 != pthread_create (&thrd, NULL, &ServeOneRequest,
    474                            (void *) &fd))
    475     externalErrorExitDesc ("pthread_create() failed");
    476 
    477   /* No need for the thread sync as socket is already listening,
    478    * so libcurl may start connecting before MHD is started in another thread */
    479   cbc.pos = 0;
    480   checkCURLE_OK (curl_easy_perform (c));
    481 
    482   if (cbc.pos != strlen (MHD_URI_BASE_PATH))
    483   {
    484     fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ",
    485              (unsigned) cbc.pos, (int) cbc.pos, cbc.buf,
    486              (unsigned) strlen (MHD_URI_BASE_PATH));
    487     mhdErrorExitDesc ("Wrong returned data length");
    488   }
    489   if (0 != strncmp (MHD_URI_BASE_PATH, cbc.buf, strlen (MHD_URI_BASE_PATH)))
    490   {
    491     fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos, cbc.buf);
    492     mhdErrorExitDesc ("Wrong returned data");
    493   }
    494 
    495   if (0 != pthread_join (thrd, (void **) &thrdRet))
    496     externalErrorExitDesc ("pthread_join() failed");
    497   if (NULL != thrdRet)
    498     externalErrorExitDesc ("ServeOneRequest() returned non-NULL result");
    499 
    500   if (verbose)
    501   {
    502     printf ("ServeOneRequest() thread was joined.\n");
    503     fflush (stdout);
    504   }
    505 
    506   /* at this point, the forked server quiesced and quit,
    507    * so new requests should fail
    508    */
    509   cbc.pos = 0;
    510   if (CURLE_OK == curl_easy_perform (c))
    511   {
    512     fprintf (stderr, "curl_easy_perform() succeed while it should fail. ");
    513     fprintf (stderr, "Got %u bytes ('%.*s'), "
    514              "valid data would be %u bytes (%s). ",
    515              (unsigned) cbc.pos, (int) cbc.pos, cbc.buf,
    516              (unsigned) strlen (MHD_URI_BASE_PATH), MHD_URI_BASE_PATH);
    517     mhdErrorExitDesc ("Unexpected succeed request");
    518   }
    519   if (verbose)
    520     printf ("curl_easy_perform() failed as expected.\n");
    521   curl_easy_cleanup (c);
    522   MHD_stop_daemon (d);
    523   MHD_socket_close_chk_ (fd);
    524 
    525   if (verbose)
    526   {
    527     printf ("testGet(%u, %d, %u) test succeed.\n",
    528             type, pool_count, (unsigned int) poll_flag);
    529     fflush (stdout);
    530   }
    531 
    532   return 0;
    533 }
    534 
    535 
    536 static unsigned int
    537 testExternalGet (void)
    538 {
    539   struct MHD_Daemon *d;
    540   CURL *c;
    541   char buf[2048];
    542   struct CBC cbc;
    543   CURLM *multi;
    544   CURLMcode mret;
    545   fd_set rs;
    546   fd_set ws;
    547   fd_set es;
    548   int running;
    549   struct CURLMsg *msg;
    550   time_t start;
    551   struct timeval tv;
    552   int i;
    553   MHD_socket fd = MHD_INVALID_SOCKET;
    554 
    555   if (verbose)
    556     printf ("testExternalGet test started.\n");
    557 
    558   fd = MHD_INVALID_SOCKET;
    559   multi = NULL;
    560   cbc.buf = buf;
    561   cbc.size = sizeof(buf);
    562   cbc.pos = 0;
    563   d = MHD_start_daemon (MHD_USE_ERROR_LOG,
    564                         global_port,
    565                         NULL, NULL,
    566                         &ahc_echo, NULL,
    567                         MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE,
    568                         MHD_OPTION_END);
    569   if (d == NULL)
    570     mhdErrorExitDesc ("Failed to start MHD daemon");
    571   if (0 == global_port)
    572   {
    573     const union MHD_DaemonInfo *dinfo;
    574     dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT);
    575     if ((NULL == dinfo) || (0 == dinfo->port) )
    576       mhdErrorExit ();
    577     global_port = dinfo->port;
    578   }
    579 
    580   for (i = 0; i < 2; i++)
    581   {
    582     c = setupCURL (&cbc);
    583 
    584     multi = curl_multi_init ();
    585     if (multi == NULL)
    586       libcurlErrorExit ();
    587 
    588     mret = curl_multi_add_handle (multi, c);
    589     if (mret != CURLM_OK)
    590       libcurlErrorExit ();
    591 
    592     start = time (NULL);
    593     while ( (time (NULL) - start < TIMEOUTS_VAL * 2) &&
    594             (NULL != multi) )
    595     {
    596       MHD_socket maxsock;
    597       int maxposixs;
    598       maxsock = MHD_INVALID_SOCKET;
    599       maxposixs = -1;
    600       FD_ZERO (&rs);
    601       FD_ZERO (&ws);
    602       FD_ZERO (&es);
    603       curl_multi_perform (multi, &running);
    604       mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxposixs);
    605       if (mret != CURLM_OK)
    606         libcurlErrorExit ();
    607       if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxsock))
    608         mhdErrorExit ();
    609 #ifndef MHD_WINSOCK_SOCKETS
    610       if (maxsock > maxposixs)
    611         maxposixs = maxsock;
    612 #endif /* MHD_POSIX_SOCKETS */
    613       tv.tv_sec = 0;
    614       tv.tv_usec = 100000;
    615       if (-1 == select (maxposixs + 1, &rs, &ws, &es, &tv))
    616       {
    617 #ifdef MHD_POSIX_SOCKETS
    618         if (EINTR != errno)
    619           externalErrorExitDesc ("Unexpected select() error");
    620 #else
    621         if ((WSAEINVAL != WSAGetLastError ()) ||
    622             (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) )
    623           externalErrorExitDesc ("Unexpected select() error");
    624         Sleep ((DWORD) (tv.tv_sec * 1000 + tv.tv_usec / 1000));
    625 #endif
    626       }
    627       curl_multi_perform (multi, &running);
    628       if (0 == running)
    629       {
    630         int pending;
    631         int curl_fine = 0;
    632         while (NULL != (msg = curl_multi_info_read (multi, &pending)))
    633         {
    634           if (msg->msg == CURLMSG_DONE)
    635           {
    636             if (msg->data.result == CURLE_OK)
    637             {
    638               curl_fine = 1;
    639               if (verbose)
    640                 printf ("libcurl reported success.\n");
    641             }
    642             else if (i == 0)
    643             {
    644               fprintf (stderr,
    645                        "curl_multi_perform() failed with '%s'. ",
    646                        curl_easy_strerror (msg->data.result));
    647               mhdErrorExit ();
    648             }
    649           }
    650         }
    651         if (i == 0)
    652         {
    653           if (! curl_fine)
    654           {
    655             fprintf (stderr, "libcurl haven't returned OK code\n");
    656             mhdErrorExit ();
    657           }
    658           /* MHD is running, result should be correct */
    659           if (cbc.pos != strlen (MHD_URI_BASE_PATH))
    660           {
    661             fprintf (stderr, "Got %u bytes ('%.*s'), expected %u bytes. ",
    662                      (unsigned) cbc.pos, (int) cbc.pos, cbc.buf,
    663                      (unsigned) strlen (MHD_URI_BASE_PATH));
    664             mhdErrorExitDesc ("Wrong returned data length");
    665           }
    666           if (0 != strncmp (MHD_URI_BASE_PATH, cbc.buf,
    667                             strlen (MHD_URI_BASE_PATH)))
    668           {
    669             fprintf (stderr, "Got invalid response '%.*s'. ", (int) cbc.pos,
    670                      cbc.buf);
    671             mhdErrorExitDesc ("Wrong returned data");
    672           }
    673           if (verbose)
    674           {
    675             printf ("First request was successful.\n");
    676             fflush (stdout);
    677           }
    678         }
    679         else if (i == 1)
    680         {
    681           if  (curl_fine)
    682           {
    683             fprintf (stderr, "libcurl returned OK code, while it shouldn't\n");
    684             mhdErrorExit ();
    685           }
    686           if (verbose)
    687             printf ("Second request failed as expected.\n");
    688         }
    689         curl_multi_remove_handle (multi, c);
    690         curl_multi_cleanup (multi);
    691         curl_easy_cleanup (c);
    692         c = NULL;
    693         multi = NULL;
    694         break;
    695       }
    696       MHD_run (d);
    697     }
    698 
    699     if (NULL != multi)
    700       mhdErrorExitDesc ("Test failed and finished by timeout");
    701 
    702     if (0 == i)
    703     {
    704       /* quiesce the daemon on the 1st iteration, so the 2nd should fail */
    705       fd = MHD_quiesce_daemon (d);
    706       if (MHD_INVALID_SOCKET == fd)
    707         mhdErrorExitDesc ("MHD_quiesce_daemon() failed");
    708     }
    709   }
    710   MHD_stop_daemon (d);
    711   if (MHD_INVALID_SOCKET == fd)
    712   {
    713     fprintf (stderr, "Failed to MHD_quiesce_daemon() at some point. ");
    714     externalErrorExit ();
    715   }
    716   MHD_socket_close_chk_ (fd);
    717 
    718   if (verbose)
    719   {
    720     printf ("testExternalGet succeed.\n");
    721     fflush (stdout);
    722   }
    723 
    724   return 0;
    725 }
    726 
    727 
    728 int
    729 main (int argc, char *const *argv)
    730 {
    731   unsigned int errorCount = 0;
    732   oneone = ! has_in_name (argv[0], "10");
    733   verbose = ! (has_param (argc, argv, "-q") ||
    734                has_param (argc, argv, "--quiet") ||
    735                has_param (argc, argv, "-s") ||
    736                has_param (argc, argv, "--silent"));
    737 
    738   if (0 != curl_global_init (CURL_GLOBAL_WIN32))
    739     return 2;
    740 
    741   if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
    742     global_port = 0;
    743   else
    744     global_port = 1480 + (oneone ? 1 : 0);
    745 
    746   errorCount += testExternalGet ();
    747   if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS))
    748   {
    749     errorCount += testGet (MHD_USE_INTERNAL_POLLING_THREAD, 0, 0);
    750     errorCount += testGet (MHD_USE_THREAD_PER_CONNECTION
    751                            | MHD_USE_INTERNAL_POLLING_THREAD, 0, 0);
    752     errorCount += testGet (MHD_USE_INTERNAL_POLLING_THREAD, MHD_CPU_COUNT, 0);
    753     if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL))
    754     {
    755       errorCount += testGet (MHD_USE_INTERNAL_POLLING_THREAD, 0, MHD_USE_POLL);
    756       errorCount += testGet (MHD_USE_THREAD_PER_CONNECTION
    757                              | MHD_USE_INTERNAL_POLLING_THREAD, 0,
    758                              MHD_USE_POLL);
    759       errorCount += testGet (MHD_USE_INTERNAL_POLLING_THREAD, MHD_CPU_COUNT,
    760                              MHD_USE_POLL);
    761     }
    762     if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL))
    763     {
    764       errorCount += testGet (MHD_USE_INTERNAL_POLLING_THREAD, 0, MHD_USE_EPOLL);
    765       errorCount += testGet (MHD_USE_INTERNAL_POLLING_THREAD, MHD_CPU_COUNT,
    766                              MHD_USE_EPOLL);
    767     }
    768   }
    769   if (0 != errorCount)
    770     fprintf (stderr,
    771              "Error (code: %u)\n",
    772              errorCount);
    773   curl_global_cleanup ();
    774   return (0 == errorCount) ? 0 : 1;       /* 0 == pass */
    775 }