libmicrohttpd

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

test_get.c (53643B)


      1 /*
      2      This file is part of libmicrohttpd
      3      Copyright (C) 2007, 2008 Christian Grothoff
      4      Copyright (C) 2016-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 /**
     23  * @file testzzuf/test_get.c
     24  * @brief  Several testcases for libmicrohttpd with input fuzzing
     25  * @author Christian Grothoff
     26  * @author Karlson2k (Evgeny Grin)
     27  */
     28 
     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 <errno.h>
     36 
     37 #ifndef WINDOWS
     38 #include <unistd.h>
     39 #endif
     40 
     41 #include "mhd_debug_funcs.h"
     42 #include "mhd_zzuf_common.h"
     43 #include "test_helpers.h"
     44 
     45 #ifndef MHD_STATICSTR_LEN_
     46 /**
     47  * Determine length of static string / macro strings at compile time.
     48  */
     49 #define MHD_STATICSTR_LEN_(macro) (sizeof(macro) / sizeof(char) - 1)
     50 #endif /* ! MHD_STATICSTR_LEN_ */
     51 
     52 #ifndef CURL_VERSION_BITS
     53 #define CURL_VERSION_BITS(x,y,z) ((x) << 16 | (y) << 8 | (z))
     54 #endif /* ! CURL_VERSION_BITS */
     55 #ifndef CURL_AT_LEAST_VERSION
     56 #define CURL_AT_LEAST_VERSION(x,y,z) \
     57   (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS (x, y, z))
     58 #endif /* ! CURL_AT_LEAST_VERSION */
     59 
     60 /**
     61  * A larger loop count will run more random tests --
     62  * which would be good, except that it may take too
     63  * long for most user's patience.  So this small
     64  * value is the default.
     65  * Can be redefined by CPPFLAGS=-DLOOP_COUNT=123
     66  */
     67 #ifndef LOOP_COUNT
     68 #ifndef _MHD_VHEAVY_TESTS
     69 #define LOOP_COUNT 10
     70 #else  /* ! _MHD_HEAVY_TESTS */
     71 #define LOOP_COUNT 200
     72 #endif /* ! _MHD_HEAVY_TESTS */
     73 #endif /* LOOP_COUNT */
     74 
     75 #ifdef _DEBUG
     76 /* Uncomment the next line (or use CPPFLAGS) to see all request and response bodies in log */
     77 /* #define TEST_PRINT_BODY */
     78 /* Uncomment the next line (or use CPPFLAGS) to see all request bodies as they are sent by libcurl */
     79 /* #define TEST_PRINT_BODY_RQ 1 */
     80 /* Uncomment the next line (or use CPPFLAGS) to see all request bodies as they are received by libcurl */
     81 /* #define TEST_PRINT_BODY_RP 1 */
     82 #endif /* _DEBUG */
     83 
     84 #define MHD_TIMEOUT 2
     85 
     86 #define CURL_TIMEOUT 5
     87 
     88 /* Global test parameters */
     89 static int oneone;
     90 static int dry_run;
     91 static int use_get;
     92 static int use_get_chunked;
     93 static int use_put;
     94 static int use_put_large;
     95 static int use_put_chunked;
     96 static int use_post;
     97 static int use_post_form;
     98 static int use_long_header;
     99 static int use_long_uri;
    100 static int use_close;
    101 static int run_with_socat;
    102 /**
    103  * Non-zero if this program sweeps the matrix of "hostile" daemon options
    104  * (small connection memory pools, small connection limits, short timeouts
    105  * and the various client discipline levels) instead of using the single
    106  * "plain" set of daemon options.
    107  * Derived from the "_hostile" marker in the program name.
    108  */
    109 static int use_hostile_opts;
    110 
    111 /**
    112  * The daemon option profile that is currently in use.
    113  */
    114 static const struct zzuf_opt_profile *cur_profile;
    115 
    116 /**
    117  * The connection timeout that the current daemon has been started with.
    118  */
    119 static unsigned int expected_conn_timeout = MHD_TIMEOUT;
    120 
    121 #define TEST_BASE_URI "http:/" "/127.0.0.1/test_uri"
    122 #define TEST_BASE_URI_SOCAT "http:/" "/127.0.0.121/test_uri"
    123 
    124 #define SOCAT_PORT 10121
    125 
    126 #define TEST_BASE_PORT 4010
    127 
    128 #define EMPTY_PAGE "Empty page."
    129 #define EMPTY_PAGE_ALT "Alternative empty page."
    130 #define METHOD_NOT_SUPPORTED "HTTP method is not supported."
    131 #define POST_DATA_BROKEN "The POST request is ill-formed."
    132 
    133 #define POST_KEY1 "test"
    134 #define POST_VALUE1 "test_post"
    135 #define POST_KEY2 "library"
    136 #define POST_VALUE2 "GNU libmicrohttpd"
    137 #define POST_URLENC_DATA \
    138   POST_KEY1 "=" POST_VALUE1 "&" POST_KEY2 "=" "GNU%20libmicrohttpd"
    139 
    140 #define PUT_NORMAL_SIZE 11
    141 /* Does not need to be very large as MHD buffer will be made smaller anyway */
    142 #define PUT_LARGE_SIZE (4 * 1024)
    143 /* The length of "very long" URI and header strings. MHD uses smaller buffer. */
    144 #define TEST_STRING_VLONG_LEN 8 * 1024
    145 
    146 
    147 #if ! CURL_AT_LEAST_VERSION (7,56,0)
    148 #define TEST_USE_STATIC_POST_DATA 1
    149 static struct curl_httppost *post_first;
    150 static struct curl_httppost *post_last;
    151 #endif /* ! CURL_AT_LEAST_VERSION(7,56,0) */
    152 
    153 static struct curl_slist *libcurl_long_header;
    154 
    155 /**
    156  * Initialise long header for libcurl
    157  *
    158  * @return non-zero if succeed,
    159  *         zero if failed
    160  */
    161 static int
    162 long_header_init (void)
    163 {
    164   char *buf;
    165 
    166   buf = malloc (TEST_STRING_VLONG_LEN + 1);
    167   if (NULL == buf)
    168   {
    169     fprintf (stderr, "malloc() failed "
    170              "at line %d.\n", (int) __LINE__);
    171     return 0;
    172   }
    173   buf[TEST_STRING_VLONG_LEN] = 0;
    174   buf[0] = 'A';
    175   memset (buf + 1, 'a', TEST_STRING_VLONG_LEN / 2 - 2);
    176   buf[TEST_STRING_VLONG_LEN / 2 - 1] = ':';
    177   buf[TEST_STRING_VLONG_LEN / 2] = ' ';
    178   memset (buf + TEST_STRING_VLONG_LEN / 2 + 1, 'c',
    179           TEST_STRING_VLONG_LEN / 2 - 1);
    180   libcurl_long_header = curl_slist_append (NULL, buf);
    181   free (buf);
    182   if (NULL != libcurl_long_header)
    183     return ! 0; /* Success exit point */
    184 
    185   fprintf (stderr, "curl_slist_append() failed "
    186            "at line %d.\n", (int) __LINE__);
    187   return 0; /* Failure exit point */
    188 }
    189 
    190 
    191 /**
    192  * Globally initialise test environment
    193  * @return non-zero if succeed,
    194  *         zero if failed
    195  */
    196 static int
    197 test_global_init (void)
    198 {
    199   libcurl_long_header = NULL;
    200   if (CURLE_OK != curl_global_init (CURL_GLOBAL_WIN32))
    201   {
    202     fprintf (stderr, "curl_global_init() failed "
    203              "at line %d.\n", (int) __LINE__);
    204     return 0;
    205   }
    206 
    207   if (long_header_init ())
    208   {
    209 #ifndef TEST_USE_STATIC_POST_DATA
    210     return 1; /* Success exit point */
    211 #else  /* ! TEST_USE_STATIC_POST_DATA */
    212     post_first = NULL;
    213     post_last = NULL;
    214     if ((CURL_FORMADD_OK !=
    215          curl_formadd (&post_first, &post_last,
    216                        CURLFORM_PTRNAME, POST_KEY1,
    217                        CURLFORM_NAMELENGTH,
    218                        (long) MHD_STATICSTR_LEN_ (POST_KEY1),
    219                        CURLFORM_PTRCONTENTS, POST_VALUE1,
    220 #if CURL_AT_LEAST_VERSION (7,46,0)
    221                        CURLFORM_CONTENTLEN,
    222                        (curl_off_t) MHD_STATICSTR_LEN_ (POST_VALUE1),
    223 #else  /* ! CURL_AT_LEAST_VERSION(7,46,0) */
    224                        CURLFORM_CONTENTSLENGTH,
    225                        (long) MHD_STATICSTR_LEN_ (POST_VALUE1),
    226 #endif /* ! CURL_AT_LEAST_VERSION(7,46,0) */
    227                        CURLFORM_END)) ||
    228         (CURL_FORMADD_OK !=
    229          curl_formadd (&post_first, &post_last,
    230                        CURLFORM_PTRNAME, POST_KEY2,
    231                        CURLFORM_NAMELENGTH,
    232                        (long) MHD_STATICSTR_LEN_ (POST_KEY2),
    233                        CURLFORM_PTRCONTENTS, POST_VALUE2,
    234 #if CURL_AT_LEAST_VERSION (7,46,0)
    235                        CURLFORM_CONTENTLEN,
    236                        (curl_off_t) MHD_STATICSTR_LEN_ (POST_VALUE2),
    237 #else  /* ! CURL_AT_LEAST_VERSION(7,46,0) */
    238                        CURLFORM_CONTENTSLENGTH,
    239                        (long) MHD_STATICSTR_LEN_ (POST_VALUE2),
    240 #endif /* ! CURL_AT_LEAST_VERSION(7,46,0) */
    241                        CURLFORM_END)))
    242       fprintf (stderr, "curl_formadd() failed "
    243                "at line %d.\n", (int) __LINE__);
    244     else
    245       return 1; /* Success exit point */
    246 
    247     if (NULL != post_first)
    248       curl_formfree (post_first);
    249     curl_slist_free_all (libcurl_long_header);
    250 #endif /* ! CURL_AT_LEAST_VERSION(7,56,0) */
    251   }
    252   curl_global_cleanup ();
    253   return 0; /* Failure exit point */
    254 }
    255 
    256 
    257 /**
    258  * Globally de-initialise test environment
    259  */
    260 static void
    261 test_global_deinit (void)
    262 {
    263 #ifdef TEST_USE_STATIC_POST_DATA
    264   curl_formfree (post_first);
    265 #endif /* TEST_USE_STATIC_POST_DATA */
    266   curl_global_cleanup ();
    267   if (NULL != libcurl_long_header)
    268     curl_slist_free_all (libcurl_long_header);
    269 }
    270 
    271 
    272 /**
    273  * libcurl callback parameters for uploads, downloads and debug callbacks
    274  */
    275 struct CBC
    276 {
    277   /* Upload members */
    278   size_t up_pos;
    279   size_t up_size;
    280   /* Download members */
    281   char *dn_buf;
    282   size_t dn_pos;
    283   size_t dn_buf_size;
    284   /* Debug callback members */
    285   unsigned int excess_found;
    286 };
    287 
    288 static void
    289 initCBC (struct CBC *libcurlcbc, char *dn_buf, size_t dn_buf_size)
    290 {
    291   libcurlcbc->up_pos = 0;
    292   if (use_put_large)
    293     libcurlcbc->up_size = PUT_LARGE_SIZE;
    294   else if (use_put)
    295     libcurlcbc->up_size = PUT_NORMAL_SIZE;
    296   else
    297     libcurlcbc->up_size = 0;
    298   libcurlcbc->dn_buf = dn_buf;
    299   libcurlcbc->dn_pos = 0;
    300   libcurlcbc->dn_buf_size = dn_buf_size;
    301   libcurlcbc->excess_found = 0;
    302 }
    303 
    304 
    305 static void
    306 resetCBC (struct CBC *libcurlcbc)
    307 {
    308   libcurlcbc->up_pos = 0;
    309   libcurlcbc->dn_pos = 0;
    310 }
    311 
    312 
    313 static size_t
    314 putBuffer (void *stream, size_t item_size, size_t nitems, void *ctx)
    315 {
    316   size_t to_fill;
    317   size_t i;
    318   struct CBC *cbc = ctx;
    319 
    320   to_fill = cbc->up_size - cbc->up_pos;
    321   /* Skip overflow check as the return value is valid anyway */
    322   if (use_put_chunked)
    323   {
    324     /* Send data as several chunks */
    325     if (to_fill > cbc->up_size / 3)
    326       to_fill = cbc->up_size / 3;
    327   }
    328   if (to_fill > item_size * nitems)
    329     to_fill = item_size * nitems;
    330 
    331   /* Avoid libcurl magic numbers */
    332 #ifdef CURL_READFUNC_PAUSE
    333   if (CURL_READFUNC_ABORT == to_fill)
    334     to_fill -= 2;
    335 #endif /* CURL_READFUNC_PAUSE */
    336 #ifdef CURL_READFUNC_ABORT
    337   if (CURL_READFUNC_ABORT == to_fill)
    338     --to_fill;
    339 #endif /* CURL_READFUNC_ABORT */
    340   for (i = 0; i < to_fill; ++i)
    341     ((char *) stream)[i] = 'a' + (char) ((cbc->up_pos + i)
    342                                          % (unsigned char) ('z' - 'a' + 1));
    343 
    344   cbc->up_pos += to_fill;
    345   return to_fill;
    346 }
    347 
    348 
    349 static size_t
    350 copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx)
    351 {
    352   struct CBC *cbc = ctx;
    353 
    354   if (cbc->dn_pos + size * nmemb > cbc->dn_buf_size)
    355     return 0;                   /* overflow */
    356   memcpy (&cbc->dn_buf[cbc->dn_pos], ptr, size * nmemb);
    357   cbc->dn_pos += size * nmemb;
    358   return size * nmemb;
    359 }
    360 
    361 
    362 #define TEST_MAGIC_MARKER0 0xFEE1C0DE
    363 #define TEST_MAGIC_MARKER1 (TEST_MAGIC_MARKER0 + 1)
    364 #define TEST_MAGIC_MARKER2 (TEST_MAGIC_MARKER0 + 2)
    365 
    366 struct content_cb_param_strct
    367 {
    368   unsigned int magic0;    /**< Must have TEST_MAGIC_MARKER0 value */
    369   struct MHD_Response *response; /**< The pointer to the response structure */
    370 };
    371 
    372 /**
    373  * MHD content reader callback that returns
    374  * data in chunks.
    375  */
    376 static ssize_t
    377 content_cb (void *cls, uint64_t pos, char *buf, size_t max)
    378 {
    379   struct content_cb_param_strct *param = (struct content_cb_param_strct *) cls;
    380   size_t fill_size;
    381 
    382   if ((unsigned int) TEST_MAGIC_MARKER0 != param->magic0)
    383   {
    384     fprintf (stderr, "Wrong cls pointer "
    385              "at line %d.\n", (int) __LINE__);
    386     fflush (stderr);
    387     abort ();
    388   }
    389 
    390   if (pos >= 128 * 10)
    391   {
    392     if (MHD_YES !=
    393         MHD_add_response_footer (param->response, "Footer", "working"))
    394     {
    395       fprintf (stderr, "MHD_add_response_footer() failed "
    396                "at line %d.\n", (int) __LINE__);
    397       fflush (stderr);
    398       abort ();
    399     }
    400     return MHD_CONTENT_READER_END_OF_STREAM;
    401   }
    402 
    403   if (128 > max)
    404     fill_size = 128;
    405   else
    406     fill_size = max;
    407   memset (buf, 'A' + (char) (unsigned int) (pos / 128), fill_size);
    408 
    409   return (ssize_t) fill_size;
    410 }
    411 
    412 
    413 /**
    414  * Deallocate memory for callback cls.
    415  */
    416 static void
    417 crcf (void *ptr)
    418 {
    419   free (ptr);
    420 }
    421 
    422 
    423 struct req_process_strct
    424 {
    425   unsigned int magic2;   /**< Must have TEST_MAGIC_MARKER2 value */
    426   int is_static;         /**< Non-zero if statically allocated, zero if malloc()'ed */
    427   struct MHD_PostProcessor *postprocsr;
    428   unsigned int post_data_sum;
    429 };
    430 
    431 static enum MHD_Result
    432 post_iterator (void *cls,
    433                enum MHD_ValueKind kind,
    434                const char *key,
    435                const char *filename,
    436                const char *content_type,
    437                const char *transfer_encoding,
    438                const char *value, uint64_t off, size_t size)
    439 {
    440   struct req_process_strct *param = (struct req_process_strct *) cls;
    441   size_t i;
    442 
    443   (void) filename; (void) content_type; (void) transfer_encoding;
    444   (void) off; /* Unused. Mute compiler warnings. */
    445 
    446   if (TEST_MAGIC_MARKER2 != param->magic2)
    447   {
    448     fprintf (stderr, "The 'param->magic2' has wrong value "
    449              "at line %d.\n", (int) __LINE__);
    450     abort ();
    451   }
    452 
    453   if (MHD_POSTDATA_KIND != kind)
    454   {
    455     fprintf (stderr, "The 'kind' parameter has wrong value "
    456              "at line %d.\n", (int) __LINE__);
    457     abort ();
    458   }
    459 
    460   if (NULL != key)
    461     param->post_data_sum += (unsigned int) strlen (key);
    462 
    463   for (i = 0; size > i; ++i)
    464     param->post_data_sum += (unsigned int) (unsigned char) value[i];
    465 
    466   return MHD_YES;
    467 }
    468 
    469 
    470 static void
    471 free_req_pr_data (struct req_process_strct *pr_data)
    472 {
    473   if (NULL == pr_data)
    474     return;
    475   if (TEST_MAGIC_MARKER2 != pr_data->magic2)
    476   {
    477     fprintf (stderr, "The 'pr_data->magic2' has wrong value "
    478              "at line %d.\n", (int) __LINE__);
    479     abort ();
    480   }
    481   if (pr_data->is_static)
    482   {
    483     if (NULL != pr_data->postprocsr)
    484     {
    485       fprintf (stderr, "The 'pr_data->postprocsr' has wrong value "
    486                "at line %d.\n", (int) __LINE__);
    487       abort ();
    488     }
    489     return;
    490   }
    491   if (NULL != pr_data->postprocsr)
    492     MHD_destroy_post_processor (pr_data->postprocsr);
    493   pr_data->postprocsr = NULL;
    494   free (pr_data);
    495 }
    496 
    497 
    498 struct ahc_param_strct
    499 {
    500   unsigned int magic1;   /**< Must have TEST_MAGIC_MARKER1 value */
    501   unsigned int err_flag; /**< Non-zero if any error is encountered */
    502   unsigned int num_replies; /**< The number of replies sent for the current request */
    503 };
    504 
    505 static enum MHD_Result
    506 send_error_response (struct MHD_Connection *connection,
    507                      struct ahc_param_strct *param,
    508                      unsigned int status_code,
    509                      const char *static_text,
    510                      const size_t static_text_len)
    511 {
    512   struct MHD_Response *response;
    513   response =
    514     MHD_create_response_from_buffer_static (static_text_len,
    515                                             static_text);
    516   if (NULL != response)
    517   {
    518     if (MHD_YES == MHD_add_response_header (response,
    519                                             MHD_HTTP_HEADER_CONNECTION,
    520                                             "close"))
    521     {
    522       if (MHD_YES == MHD_queue_response (connection, status_code, response))
    523       {
    524         MHD_destroy_response (response);
    525         return MHD_YES; /* Success exit point */
    526       }
    527       else
    528         fprintf (stderr, "MHD_queue_response() failed "
    529                  "at line %d.\n", (int) __LINE__);
    530     }
    531     else
    532       fprintf (stderr, "MHD_add_response_header() failed "
    533                "at line %d.\n", (int) __LINE__);
    534     MHD_destroy_response (response);
    535   }
    536   else
    537     fprintf (stderr, "MHD_create_response_from_callback() failed "
    538              "at line %d.\n", (int) __LINE__);
    539 
    540   param->err_flag = 1;
    541   return MHD_NO; /* Failure exit point */
    542 }
    543 
    544 
    545 static enum MHD_Result
    546 ahc_check (void *cls,
    547            struct MHD_Connection *connection,
    548            const char *url,
    549            const char *method,
    550            const char *version,
    551            const char *upload_data, size_t *upload_data_size,
    552            void **req_cls)
    553 {
    554   static struct req_process_strct static_req_pr_data = {
    555     TEST_MAGIC_MARKER2, ! 0, NULL, 0
    556   };
    557   struct req_process_strct *req_pr_data;
    558   struct ahc_param_strct *param = (struct ahc_param_strct *) cls;
    559   struct MHD_Response *response;
    560   enum MHD_Result ret;
    561   unsigned char data_sum;
    562   int is_post_req;
    563 
    564   if (NULL == cls)
    565   {
    566     fprintf (stderr, "The 'cls' parameter is NULL "
    567              "at line %d.\n", (int) __LINE__);
    568     fflush (stderr);
    569     abort ();
    570   }
    571   if ((unsigned int) TEST_MAGIC_MARKER1 != param->magic1)
    572   {
    573     fprintf (stderr, "The 'param->magic1' has wrong value "
    574              "at line %d.\n", (int) __LINE__);
    575     fflush (stderr);
    576     abort ();
    577   }
    578   if (NULL == connection)
    579   {
    580     fprintf (stderr, "The 'connection' parameter is NULL "
    581              "at line %d.\n", (int) __LINE__);
    582     param->err_flag = 1;
    583     return MHD_NO; /* Should not reply */
    584   }
    585   if (1)
    586   { /* Simple check for 'connection' parameter validity */
    587     const union MHD_ConnectionInfo *conn_info;
    588     conn_info =
    589       MHD_get_connection_info (connection,
    590                                MHD_CONNECTION_INFO_CONNECTION_TIMEOUT);
    591     if (NULL == conn_info)
    592     {
    593       fprintf (stderr, "The 'MHD_get_connection_info' has returned NULL "
    594                "at line %d.\n", (int) __LINE__);
    595       param->err_flag = 1;
    596     }
    597     else if (expected_conn_timeout != conn_info->connection_timeout)
    598     {
    599       fprintf (stderr, "The 'MHD_get_connection_info' has returned "
    600                "unexpected timeout value "
    601                "at line %d.\n", (int) __LINE__);
    602       param->err_flag = 1;
    603     }
    604   }
    605   if (NULL == url)
    606   {
    607     fprintf (stderr, "The 'url' parameter is NULL "
    608              "at line %d.\n", (int) __LINE__);
    609     param->err_flag = 1;
    610   }
    611   if (NULL == method)
    612   {
    613     fprintf (stderr, "The 'method' parameter is NULL "
    614              "at line %d.\n", (int) __LINE__);
    615     param->err_flag = 1;
    616     return MHD_NO; /* Should not reply */
    617   }
    618   if (NULL == version)
    619   {
    620     fprintf (stderr, "The 'version' parameter is NULL "
    621              "at line %d.\n", (int) __LINE__);
    622     param->err_flag = 1;
    623     return MHD_NO; /* Should not reply */
    624   }
    625   if (NULL == upload_data_size)
    626   {
    627     fprintf (stderr, "The 'upload_data_size' parameter is NULL "
    628              "at line %d.\n", (int) __LINE__);
    629     param->err_flag = 1;
    630     return MHD_NO; /* Should not reply */
    631   }
    632   if ((0 != *upload_data_size) && (NULL == upload_data))
    633   {
    634     fprintf (stderr, "The 'upload_data' parameter is NULL "
    635              "while '*upload_data_size' is not zero "
    636              "at line %d.\n", (int) __LINE__);
    637     param->err_flag = 1;
    638     return MHD_NO; /* Should not reply */
    639   }
    640   if ((NULL != upload_data) && (0 == *upload_data_size))
    641   {
    642     fprintf (stderr, "The 'upload_data' parameter is NOT NULL "
    643              "while '*upload_data_size' is zero "
    644              "at line %d.\n", (int) __LINE__);
    645     param->err_flag = 1;
    646     return MHD_NO; /* Should not reply */
    647   }
    648 
    649   if (0 != param->num_replies)
    650   {
    651     /* Phantom "second" request due to the fuzzing of the input. Refuse. */
    652     return MHD_NO;
    653   }
    654 
    655   is_post_req = (0 == strcmp (method, MHD_HTTP_METHOD_POST));
    656   if ((0 != strcmp (method, MHD_HTTP_METHOD_GET))
    657       && (0 != strcmp (method, MHD_HTTP_METHOD_HEAD))
    658       && (0 != strcmp (method, MHD_HTTP_METHOD_PUT))
    659       && (! is_post_req))
    660   {
    661     /* Unsupported method for this callback */
    662     return send_error_response (connection, param, MHD_HTTP_NOT_IMPLEMENTED,
    663                                 METHOD_NOT_SUPPORTED,
    664                                 MHD_STATICSTR_LEN_ (METHOD_NOT_SUPPORTED));
    665   }
    666 
    667   if (NULL == *req_cls)
    668   {
    669     if (! is_post_req)
    670     { /* Use static memory */
    671       *req_cls = &static_req_pr_data;
    672     }
    673     else
    674     { /* POST request, use PostProcessor */
    675       req_pr_data =
    676         (struct req_process_strct *) malloc (sizeof (struct req_process_strct));
    677       if (NULL == req_pr_data)
    678       {
    679         fprintf (stderr, "malloc() failed "
    680                  "at line %d.\n", (int) __LINE__);
    681         return MHD_NO;
    682       }
    683       req_pr_data->magic2 = TEST_MAGIC_MARKER2;
    684       req_pr_data->is_static = 0;
    685       req_pr_data->post_data_sum = 0;
    686       req_pr_data->postprocsr = MHD_create_post_processor (connection, 1024,
    687                                                            &post_iterator,
    688                                                            req_pr_data);
    689       if (NULL == req_pr_data->postprocsr)
    690       {
    691         free (req_pr_data);
    692         if (NULL == upload_data)
    693           return send_error_response (connection, param, MHD_HTTP_BAD_REQUEST,
    694                                       POST_DATA_BROKEN,
    695                                       MHD_STATICSTR_LEN_ (POST_DATA_BROKEN));
    696         else
    697           return MHD_NO; /* Cannot handle request, broken POST */
    698       }
    699       *req_cls = req_pr_data;
    700     }
    701     if (NULL == upload_data)
    702       return MHD_YES;
    703   }
    704   req_pr_data = (struct req_process_strct *) *req_cls;
    705 
    706   data_sum = 0;
    707   if (NULL != upload_data)
    708   {
    709     if (is_post_req)
    710     {
    711       if (MHD_YES != MHD_post_process (req_pr_data->postprocsr,
    712                                        upload_data, *upload_data_size))
    713       {
    714         free_req_pr_data (req_pr_data);
    715         *req_cls = NULL;
    716         /* Processing upload body (context), error reply cannot be queued here */
    717         return MHD_NO;
    718       }
    719       *upload_data_size = 0; /* All data have been processed */
    720     }
    721     else
    722     {
    723       /* Check that all 'upload_data' is addressable */
    724       size_t pos;
    725       for (pos = 0; pos < *upload_data_size; ++pos)
    726         data_sum =
    727           (unsigned char) (data_sum + (unsigned char) upload_data[pos]);
    728       if (0 != *upload_data_size)
    729       {
    730         if (3 >= *upload_data_size)
    731           *upload_data_size = 0;                             /* Consume all incoming data */
    732         else
    733           *upload_data_size = data_sum % *upload_data_size;  /* Pseudo-random */
    734       }
    735     }
    736     return MHD_YES;
    737   }
    738   if (is_post_req)
    739   {
    740     if (MHD_YES != MHD_destroy_post_processor (req_pr_data->postprocsr))
    741     {
    742       free (req_pr_data);
    743       *req_cls = NULL;
    744       return send_error_response (connection, param, MHD_HTTP_BAD_REQUEST,
    745                                   POST_DATA_BROKEN,
    746                                   MHD_STATICSTR_LEN_ (POST_DATA_BROKEN));
    747     }
    748     req_pr_data->postprocsr = NULL;
    749   }
    750   data_sum += (unsigned char) req_pr_data->post_data_sum;
    751   free_req_pr_data (req_pr_data);
    752   *req_cls = NULL;
    753 
    754   ret = MHD_YES;
    755   if (use_get_chunked)
    756   {
    757     struct content_cb_param_strct *cnt_cb_param;
    758     cnt_cb_param = malloc (sizeof (struct content_cb_param_strct));
    759     if (NULL == cnt_cb_param)
    760     {
    761       fprintf (stderr, "malloc() failed "
    762                "at line %d.\n", (int) __LINE__);
    763       /* External error, do not rise the error flag */
    764       return MHD_NO;
    765     }
    766     cnt_cb_param->magic0 = (unsigned int) TEST_MAGIC_MARKER0;
    767     response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN,
    768                                                   1024,
    769                                                   &content_cb, cnt_cb_param,
    770                                                   &crcf);
    771     if (NULL == response)
    772     {
    773       fprintf (stderr, "MHD_create_response_from_callback() failed "
    774                "at line %d.\n", (int) __LINE__);
    775       free (cnt_cb_param);
    776       param->err_flag = 1;
    777       ret = MHD_NO;
    778     }
    779     else
    780       cnt_cb_param->response = response;
    781   }
    782   else if (use_get || use_put || use_post)
    783   {
    784     /* Randomly choose the response page for the POST requests */
    785     if (0 == data_sum % 2)
    786       response =
    787         MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ (EMPTY_PAGE),
    788                                                 EMPTY_PAGE);
    789     else
    790       response =
    791         MHD_create_response_from_buffer_static (MHD_STATICSTR_LEN_ ( \
    792                                                   EMPTY_PAGE_ALT),
    793                                                 EMPTY_PAGE_ALT);
    794 
    795     if (NULL == response)
    796     {
    797       fprintf (stderr, "MHD_create_response_from_buffer_static() failed "
    798                "at line %d.\n", (int) __LINE__);
    799       param->err_flag = 1;
    800       ret = MHD_NO;
    801     }
    802   }
    803   else
    804   {
    805     fprintf (stderr, "Response is not implemented for this test. "
    806              "Internal logic is broken. "
    807              "At line %d.\n", (int) __LINE__);
    808     abort ();
    809   }
    810 
    811   if (NULL != response)
    812   {
    813     if ((MHD_YES == ret) &&
    814         (use_close || (! oneone && (0 != strcmp (version,
    815                                                  MHD_HTTP_VERSION_1_0)))))
    816     {
    817       ret = MHD_add_response_header (response,
    818                                      MHD_HTTP_HEADER_CONNECTION,
    819                                      "close");
    820       if (MHD_YES != ret)
    821       {
    822         fprintf (stderr, "MHD_add_response_header() failed "
    823                  "at line %d.\n", (int) __LINE__);
    824         param->err_flag = 1;
    825       }
    826     }
    827     if (MHD_YES == ret)
    828     {
    829       ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
    830       if (MHD_YES != ret)
    831       {
    832         fprintf (stderr, "MHD_queue_response() failed "
    833                  "at line %d.\n", (int) __LINE__);
    834         param->err_flag = 1;
    835       }
    836     }
    837     else
    838       param->num_replies++;
    839 
    840     MHD_destroy_response (response);
    841   }
    842   else
    843   {
    844     fprintf (stderr, "MHD_create_response_from_buffer_static() failed "
    845              "at line %d.\n", (int) __LINE__);
    846     ret = MHD_NO;
    847   }
    848   return ret;
    849 }
    850 
    851 
    852 static void
    853 req_completed_cleanup (void *cls,
    854                        struct MHD_Connection *connection,
    855                        void **req_cls,
    856                        enum MHD_RequestTerminationCode toe)
    857 {
    858   struct ahc_param_strct *param = (struct ahc_param_strct *) cls;
    859   struct req_process_strct *req_pr_data = (struct req_process_strct *) *req_cls;
    860   (void) connection; /* Unused. Mute compiler warning. */
    861 
    862   if (NULL == param)
    863   {
    864     fprintf (stderr, "The 'cls' parameter is NULL at line %d.\n",
    865              (int) __LINE__);
    866     fflush (stderr);
    867     abort ();
    868   }
    869   if ((unsigned int) TEST_MAGIC_MARKER1 != param->magic1)
    870   {
    871     fprintf (stderr, "The 'param->magic1' has wrong value at line %d.\n",
    872              (int) __LINE__);
    873     fflush (stderr);
    874     abort ();
    875   }
    876   if (NULL == req_pr_data)
    877     return; /* The data have been freed */
    878   if ((unsigned int) TEST_MAGIC_MARKER2 != req_pr_data->magic2)
    879   {
    880     fprintf (stderr, "The 'req_pr_data->magic2' has wrong value at line %d.\n",
    881              (int) __LINE__);
    882     fflush (stderr);
    883     abort ();
    884   }
    885   if (MHD_REQUEST_TERMINATED_COMPLETED_OK == toe)
    886   {
    887     fprintf (stderr, "The request completed successful, but request cls has"
    888              "not been cleared. "
    889              "At line %d.\n", (int) __LINE__);
    890     param->err_flag = 1;
    891   }
    892   if (req_pr_data->is_static)
    893     return;
    894   if (NULL != req_pr_data->postprocsr)
    895     MHD_destroy_post_processor (req_pr_data->postprocsr);
    896   req_pr_data->postprocsr = NULL;
    897   free (req_pr_data);
    898   *req_cls = NULL;
    899 }
    900 
    901 
    902 /* Un-comment the next line (or use CPPFLAGS) to avoid
    903    logging of the traffic with debug builds */
    904 /* #define TEST_NO_PRINT_TRAFFIC 1 */
    905 
    906 #ifdef _DEBUG
    907 #ifdef TEST_PRINT_BODY
    908 #ifndef TEST_PRINT_BODY_RQ
    909 #define TEST_PRINT_BODY_RQ 1
    910 #endif /* TEST_PRINT_BODY_RQ */
    911 #ifndef TEST_PRINT_BODY_RP
    912 #define TEST_PRINT_BODY_RP 1
    913 #endif /* TEST_PRINT_BODY_RP */
    914 #endif /* TEST_PRINT_BODY */
    915 #endif /* _DEBUG */
    916 
    917 static int
    918 libcurl_debug_cb (CURL *handle,
    919                   curl_infotype type,
    920                   char *data,
    921                   size_t size,
    922                   void *ctx)
    923 {
    924   static const char excess_mark[] = "Excess found";
    925   static const size_t excess_mark_len = MHD_STATICSTR_LEN_ (excess_mark);
    926   struct CBC *cbc = ctx;
    927   (void) handle;
    928 
    929 #if defined(_DEBUG) && ! defined(TEST_NO_PRINT_TRAFFIC)
    930   switch (type)
    931   {
    932   case CURLINFO_TEXT:
    933     fprintf (stderr, "* %.*s", (int) size, data);
    934     break;
    935   case CURLINFO_HEADER_IN:
    936     fprintf (stderr, "< %.*s", (int) size, data);
    937     break;
    938   case CURLINFO_HEADER_OUT:
    939     fprintf (stderr, "> %.*s", (int) size, data);
    940     break;
    941   case CURLINFO_DATA_IN:
    942 #ifdef TEST_PRINT_BODY_RP
    943     fprintf (stderr, "<| %.*s\n", (int) size, data);
    944 #endif /* TEST_PRINT_BODY_RP */
    945     break;
    946   case CURLINFO_DATA_OUT:
    947 #ifdef TEST_PRINT_BODY_RQ
    948     fprintf (stderr, ">| %.*s\n", (int) size, data);
    949 #endif /* TEST_PRINT_BODY_RQ */
    950     break;
    951   case CURLINFO_SSL_DATA_IN:
    952   case CURLINFO_SSL_DATA_OUT:
    953   case CURLINFO_END:
    954   default:
    955     break;
    956   }
    957 #endif /* _DEBUG  && ! TEST_NO_PRINT_TRAFFIC */
    958   if (use_close || ! oneone)
    959   {
    960     /* Check for extra data only if every connection is terminated by MHD
    961        after one request, otherwise MHD may react on garbage after request
    962        data. */
    963     if (CURLINFO_TEXT == type)
    964     {
    965       if ((size >= excess_mark_len) &&
    966           (0 == memcmp (data, excess_mark, excess_mark_len)))
    967       {
    968         fprintf (stderr, "Extra data has been detected in MHD reply "
    969                  "at line %d.\n", (int) __LINE__);
    970         cbc->excess_found++;
    971       }
    972     }
    973   }
    974   return 0;
    975 }
    976 
    977 
    978 static CURL *
    979 setupCURL (struct CBC *cbc, uint16_t port
    980 #ifndef TEST_USE_STATIC_POST_DATA
    981            , curl_mime **mime
    982 #endif /* ! TEST_USE_STATIC_POST_DATA */
    983            )
    984 {
    985   CURL *c;
    986   CURLcode e;
    987   char *buf;
    988   const char *uri_to_use;
    989   const char *base_uri;
    990 
    991 #ifndef TEST_USE_STATIC_POST_DATA
    992   *mime = NULL;
    993 #endif /* ! TEST_USE_STATIC_POST_DATA */
    994 
    995   base_uri = run_with_socat ? TEST_BASE_URI_SOCAT : TEST_BASE_URI;
    996   if (! use_long_uri)
    997   {
    998     uri_to_use = base_uri;
    999     buf = NULL;
   1000   }
   1001   else
   1002   {
   1003     size_t pos;
   1004     size_t base_uri_len;
   1005 
   1006     base_uri_len = strlen (base_uri);
   1007     buf = malloc (TEST_STRING_VLONG_LEN + 1);
   1008     if (NULL == buf)
   1009     {
   1010       fprintf (stderr, "malloc() failed "
   1011                "at line %d.\n", (int) __LINE__);
   1012       return NULL;
   1013     }
   1014     memcpy (buf, base_uri, base_uri_len);
   1015     for (pos = base_uri_len;
   1016          pos < TEST_STRING_VLONG_LEN;
   1017          ++pos)
   1018     {
   1019       if (0 == pos % 9)
   1020         buf[pos] = '/';
   1021       else
   1022         buf[pos] = 'a' + (char) (unsigned char) (pos % ((unsigned char)
   1023                                                         ('z' - 'a' + 1)));
   1024     }
   1025     buf[TEST_STRING_VLONG_LEN] = 0;
   1026     uri_to_use = buf;
   1027   }
   1028   if (run_with_socat)
   1029     port = SOCAT_PORT;
   1030 
   1031   c = curl_easy_init ();
   1032   if (NULL == c)
   1033   {
   1034     fprintf (stderr, "curl_easy_init() failed "
   1035              "at line %d.\n", (int) __LINE__);
   1036     return NULL;
   1037   }
   1038 
   1039   if ((CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_URL,
   1040                                           uri_to_use))) &&
   1041       (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L))) &&
   1042       (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_PROXY, ""))) &&
   1043       (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_WRITEFUNCTION,
   1044                                           &copyBuffer))) &&
   1045       (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_WRITEDATA, cbc))) &&
   1046       (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT,
   1047                                           ((long) CURL_TIMEOUT)))) &&
   1048       (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_TIMEOUT,
   1049                                           ((long) CURL_TIMEOUT)))) &&
   1050       (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_FAILONERROR, 0L))) &&
   1051 #ifdef _DEBUG
   1052       (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_VERBOSE, 1L))) &&
   1053 #endif /* _DEBUG */
   1054       (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_DEBUGFUNCTION,
   1055                                           &libcurl_debug_cb))) &&
   1056       (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_DEBUGDATA,
   1057                                           cbc))) &&
   1058 #if CURL_AT_LEAST_VERSION (7, 45, 0)
   1059       (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_DEFAULT_PROTOCOL,
   1060                                           "http"))) &&
   1061 #endif /* CURL_AT_LEAST_VERSION (7, 45, 0) */
   1062 #if CURL_AT_LEAST_VERSION (7, 85, 0)
   1063       (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_PROTOCOLS_STR,
   1064                                           "http"))) &&
   1065 #elif CURL_AT_LEAST_VERSION (7, 19, 4)
   1066       (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_PROTOCOLS,
   1067                                           CURLPROTO_HTTP))) &&
   1068 #endif /* CURL_AT_LEAST_VERSION (7, 19, 4) */
   1069       (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_HTTP_VERSION,
   1070                                           oneone ?
   1071                                           CURL_HTTP_VERSION_1_1 :
   1072                                           CURL_HTTP_VERSION_1_0))) &&
   1073 #if CURL_AT_LEAST_VERSION (7, 24, 0)
   1074       (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_INTERFACE,
   1075                                           "host!127.0.0.101"))) &&
   1076 #else  /* ! CURL_AT_LEAST_VERSION (7, 24, 0) */
   1077       (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_INTERFACE,
   1078                                           "127.0.0.101"))) &&
   1079 #endif /* ! CURL_AT_LEAST_VERSION (7, 24, 0) */
   1080       (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_PORT, ((long) port)))) &&
   1081       (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_HTTPHEADER,
   1082                                           use_long_header ?
   1083                                           libcurl_long_header : NULL)))
   1084       )
   1085   {
   1086     if (NULL != buf)
   1087     {
   1088       free (buf);
   1089       buf = NULL;
   1090     }
   1091     if (use_put)
   1092     {
   1093       if ((CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_READFUNCTION,
   1094                                               &putBuffer))) &&
   1095           (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_READDATA, cbc))) &&
   1096           (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_UPLOAD, (long) 1))) &&
   1097           (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_INFILESIZE_LARGE,
   1098                                               use_put_chunked ?
   1099                                               ((curl_off_t) -1) :
   1100                                               ((curl_off_t) cbc->up_size)))))
   1101       {
   1102         return c; /* Success exit point for 'use_put' */
   1103       }
   1104       else
   1105         fprintf (stderr, "PUT-related curl_easy_setopt() failed at line %d, "
   1106                  "error: %s\n", (int) __LINE__,
   1107                  curl_easy_strerror (e));
   1108     }
   1109     else if (use_post)
   1110     {
   1111       if (! use_post_form)
   1112       {
   1113         if ((CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_POST, (long) 1))) &&
   1114             (CURLE_OK == (e = curl_easy_setopt (c, CURLOPT_POSTFIELDS,
   1115                                                 POST_URLENC_DATA))) &&
   1116             (CURLE_OK ==
   1117              (e = curl_easy_setopt (c, CURLOPT_POSTFIELDSIZE,
   1118                                     MHD_STATICSTR_LEN_ (POST_URLENC_DATA)))))
   1119         {
   1120           return c; /* Success exit point for 'use_post' */
   1121         }
   1122         else
   1123           fprintf (stderr,
   1124                    "POST-related curl_easy_setopt() failed at line %d, "
   1125                    "error: %s\n", (int) __LINE__,
   1126                    curl_easy_strerror (e));
   1127       }
   1128       else
   1129       {
   1130 #ifndef TEST_USE_STATIC_POST_DATA
   1131         *mime = curl_mime_init (c);
   1132         if (NULL != *mime)
   1133         {
   1134           curl_mimepart *part;
   1135           if ((NULL != (part = curl_mime_addpart (*mime))) &&
   1136               (CURLE_OK == curl_mime_name (part, POST_KEY1)) &&
   1137               (CURLE_OK == curl_mime_data (part, POST_VALUE1,
   1138                                            MHD_STATICSTR_LEN_ (POST_VALUE1))) &&
   1139               (NULL != (part = curl_mime_addpart (*mime))) &&
   1140               (CURLE_OK == curl_mime_name (part, POST_KEY2)) &&
   1141               (CURLE_OK == curl_mime_data (part, POST_VALUE2,
   1142                                            MHD_STATICSTR_LEN_ (POST_VALUE2))))
   1143           {
   1144             if (CURLE_OK ==
   1145                 (e = curl_easy_setopt (c, CURLOPT_MIMEPOST, *mime)))
   1146               return c; /* Success exit point for 'use_post' */
   1147             else
   1148               fprintf (stderr, "curl_easy_setopt(c, CURLOPT_MIMEPOST, mime) "
   1149                        "failed at line %d, error: %s\n",
   1150                        (int) __LINE__, curl_easy_strerror (e));
   1151           }
   1152           else
   1153             fprintf (stderr, "curl_mime_addpart(), curl_mime_name() or "
   1154                      "curl_mime_data() failed.\n");
   1155         }
   1156         else
   1157           fprintf (stderr, "curl_mime_init() failed.\n");
   1158 
   1159 #else  /* TEST_USE_STATIC_POST_DATA */
   1160         if (CURLE_OK == (e = curl_easy_setopt (c,
   1161                                                CURLOPT_HTTPPOST, post_first)))
   1162         {
   1163           return c; /* Success exit point for 'use_post' */
   1164         }
   1165         else
   1166           fprintf (stderr, "POST form-related curl_easy_setopt() failed, "
   1167                    "error: %s\n", curl_easy_strerror (e));
   1168 #endif /* TEST_USE_STATIC_POST_DATA */
   1169       }
   1170     }
   1171     else
   1172       return c; /* Success exit point */
   1173   }
   1174   else
   1175     fprintf (stderr, "curl_easy_setopt() failed at line %d, "
   1176              "error: %s\n", (int) __LINE__,
   1177              curl_easy_strerror (e));
   1178 
   1179   curl_easy_cleanup (c);
   1180 #ifndef TEST_USE_STATIC_POST_DATA
   1181   if (NULL != *mime)
   1182     curl_mime_free (*mime);
   1183 #endif /* ! TEST_USE_STATIC_POST_DATA */
   1184 
   1185   if (NULL != buf)
   1186     free (buf);
   1187 
   1188   return NULL; /* Failure exit point */
   1189 }
   1190 
   1191 
   1192 static struct MHD_Daemon *
   1193 start_daemon_for_test (unsigned int daemon_flags, uint16_t *pport,
   1194                        struct ahc_param_strct *callback_param)
   1195 {
   1196   struct MHD_Daemon *d;
   1197   struct MHD_OptionItem ops[] = {
   1198     { MHD_OPTION_END, 0, NULL },
   1199     { MHD_OPTION_END, 0, NULL },
   1200     { MHD_OPTION_END, 0, NULL },
   1201     { MHD_OPTION_END, 0, NULL },
   1202     { MHD_OPTION_END, 0, NULL },
   1203     { MHD_OPTION_END, 0, NULL }
   1204   };
   1205   size_t num_opt;
   1206   size_t mem_limit;
   1207 
   1208   num_opt = 0;
   1209 
   1210   callback_param->magic1 = (unsigned int) TEST_MAGIC_MARKER1;
   1211   callback_param->err_flag = 0;
   1212   callback_param->num_replies = 0;
   1213 
   1214   /* The tests with intentionally huge URIs, headers or bodies need a memory
   1215      limit that matches the data they send; for all other tests the limit
   1216      comes from the option profile (which may be "keep the default"). */
   1217   if (use_put_large)
   1218     mem_limit = (size_t) (PUT_LARGE_SIZE / 4);
   1219   else if (use_long_header || use_long_uri)
   1220     mem_limit = (size_t) (TEST_STRING_VLONG_LEN / 2);
   1221   else
   1222     mem_limit = cur_profile->mem_limit;
   1223   if (0 != mem_limit)
   1224   {
   1225     ops[num_opt].option = MHD_OPTION_CONNECTION_MEMORY_LIMIT;
   1226     ops[num_opt].value = (intptr_t) mem_limit;
   1227     ++num_opt;
   1228   }
   1229   if (0 != cur_profile->conn_limit)
   1230   {
   1231     ops[num_opt].option = MHD_OPTION_CONNECTION_LIMIT;
   1232     ops[num_opt].value = (intptr_t) cur_profile->conn_limit;
   1233     ++num_opt;
   1234   }
   1235   if (0 != cur_profile->discipline_lvl)
   1236   {
   1237     ops[num_opt].option = cur_profile->use_legacy_strict ?
   1238                           MHD_OPTION_STRICT_FOR_CLIENT :
   1239                           MHD_OPTION_CLIENT_DISCIPLINE_LVL;
   1240     ops[num_opt].value = (intptr_t) cur_profile->discipline_lvl;
   1241     ++num_opt;
   1242   }
   1243   if (0 == (MHD_USE_INTERNAL_POLLING_THREAD & daemon_flags))
   1244   {
   1245     ops[num_opt].option = MHD_OPTION_APP_FD_SETSIZE;
   1246     ops[num_opt].value = (intptr_t) (FD_SETSIZE);
   1247     ++num_opt;
   1248   }
   1249   expected_conn_timeout = cur_profile->timeout;
   1250   d = MHD_start_daemon (daemon_flags /* | MHD_USE_ERROR_LOG */,
   1251                         *pport, NULL, NULL,
   1252                         &ahc_check, callback_param,
   1253                         MHD_OPTION_CONNECTION_TIMEOUT,
   1254                         expected_conn_timeout,
   1255                         MHD_OPTION_NOTIFY_COMPLETED,
   1256                         &req_completed_cleanup, callback_param,
   1257                         MHD_OPTION_ARRAY, ops,
   1258                         MHD_OPTION_END);
   1259   if (NULL == d)
   1260   {
   1261     fprintf (stderr, "MHD_start_daemon() failed "
   1262              "at line %d.\n", (int) __LINE__);
   1263     return NULL;
   1264   }
   1265 
   1266   /* Do not use accept4() as only accept() is intercepted by zzuf */
   1267   if (! run_with_socat)
   1268     MHD_avoid_accept4_ (d);
   1269 
   1270   if (0 == *pport)
   1271   {
   1272     const union MHD_DaemonInfo *dinfo;
   1273 
   1274     dinfo = MHD_get_daemon_info (d,
   1275                                  MHD_DAEMON_INFO_BIND_PORT);
   1276     if ( (NULL == dinfo) ||
   1277          (0 == dinfo->port) )
   1278     {
   1279       fprintf (stderr, "MHD_get_daemon_info() failed "
   1280                "at line %d.\n", (int) __LINE__);
   1281       MHD_stop_daemon (d);
   1282       return NULL;
   1283     }
   1284     *pport = dinfo->port;
   1285   }
   1286   return d;
   1287 }
   1288 
   1289 
   1290 /**
   1291  * Select the daemon option profile for the next daemon and print
   1292  * a description of the test that is about to start.
   1293  *
   1294  * @param daemon_flags the flags of the daemon that is about to be started
   1295  */
   1296 static void
   1297 print_test_starting (unsigned int daemon_flags)
   1298 {
   1299   static unsigned int profile_num;
   1300 
   1301   /* Every started daemon uses the next profile of the matrix, so that a
   1302      single run of a "_hostile" program sweeps the whole option matrix. */
   1303   cur_profile = zzuf_opt_profile (use_hostile_opts ? profile_num++ : 0);
   1304   fflush (stderr);
   1305   if (0 != (MHD_USE_INTERNAL_POLLING_THREAD & daemon_flags))
   1306   {
   1307     if (0 != (MHD_USE_THREAD_PER_CONNECTION & daemon_flags))
   1308     {
   1309       if (0 != (MHD_USE_POLL & daemon_flags))
   1310         printf ("\nStarting test with internal polling by poll() and "
   1311                 "thread-per-connection.\n");
   1312       else
   1313         printf ("\nStarting test with internal polling by select() and "
   1314                 "thread-per-connection.\n");
   1315     }
   1316     else
   1317     {
   1318       if (0 != (MHD_USE_POLL & daemon_flags))
   1319         printf ("\nStarting test with internal polling by poll().\n");
   1320       else if (0 != (MHD_USE_EPOLL & daemon_flags))
   1321         printf ("\nStarting test with internal polling by 'epoll'.\n");
   1322       else
   1323         printf ("\nStarting test with internal polling by select().\n");
   1324     }
   1325   }
   1326   else
   1327   {
   1328     if (0 != (MHD_USE_EPOLL & daemon_flags))
   1329       printf ("\nStarting test with%s thread safety with external polling "
   1330               "and internal 'epoll'.\n",
   1331               ((0 != (MHD_USE_NO_THREAD_SAFETY & daemon_flags)) ? "out" : ""));
   1332     else
   1333       printf ("\nStarting test with%s thread safety with external polling.\n",
   1334               ((0 != (MHD_USE_NO_THREAD_SAFETY & daemon_flags)) ? "out" : ""));
   1335   }
   1336   if (use_hostile_opts)
   1337     printf ("Daemon options profile '%s' "
   1338             "(mem_limit=%lu, conn_limit=%u, timeout=%u, %s=%d).\n",
   1339             cur_profile->name,
   1340             (unsigned long) cur_profile->mem_limit,
   1341             cur_profile->conn_limit,
   1342             cur_profile->timeout,
   1343             cur_profile->use_legacy_strict ?
   1344             "strict_for_client" : "discipline_lvl",
   1345             cur_profile->discipline_lvl);
   1346   fflush (stdout);
   1347 }
   1348 
   1349 
   1350 static unsigned int
   1351 testInternalPolling (uint16_t *pport, unsigned int daemon_flags)
   1352 {
   1353   struct MHD_Daemon *d;
   1354   CURL *c;
   1355   char buf[2048];
   1356   struct CBC cbc;
   1357   struct ahc_param_strct callback_param;
   1358   unsigned int ret;
   1359 #ifndef TEST_USE_STATIC_POST_DATA
   1360   curl_mime *mime;
   1361 #endif /* ! TEST_USE_STATIC_POST_DATA */
   1362 
   1363   if (0 == (MHD_USE_INTERNAL_POLLING_THREAD & daemon_flags))
   1364   {
   1365     fprintf (stderr, "Wrong internal flags, the test is broken. "
   1366              "At line %d.\n", (int) __LINE__);
   1367     abort (); /* Wrong flags, error in code */
   1368   }
   1369 
   1370   print_test_starting (daemon_flags);
   1371   initCBC (&cbc, buf, sizeof(buf));
   1372   d = start_daemon_for_test (daemon_flags, pport, &callback_param);
   1373   if (d == NULL)
   1374     return 1;
   1375 
   1376   ret = 0;
   1377   c = setupCURL (&cbc, *pport
   1378 #ifndef TEST_USE_STATIC_POST_DATA
   1379                  , &mime
   1380 #endif /* ! TEST_USE_STATIC_POST_DATA */
   1381                  );
   1382   if (NULL != c)
   1383   {
   1384     int i;
   1385 
   1386     for (i = dry_run ? LOOP_COUNT : 0; i < LOOP_COUNT; i++)
   1387     {
   1388       fprintf (stderr, ".");
   1389       callback_param.num_replies = 0;
   1390       resetCBC (&cbc);
   1391       /* Run libcurl without checking the result */
   1392       curl_easy_perform (c);
   1393       fflush (stderr);
   1394     }
   1395     curl_easy_cleanup (c);
   1396 #ifndef TEST_USE_STATIC_POST_DATA
   1397     if (NULL != mime)
   1398       curl_mime_free (mime);
   1399 #endif /* ! TEST_USE_STATIC_POST_DATA */
   1400   }
   1401   else
   1402     ret = 99; /* Not an MHD error */
   1403 
   1404   if ((0 == ret) && callback_param.err_flag)
   1405   {
   1406     fprintf (stderr, "One or more errors have been detected by "
   1407              "access handler callback function. "
   1408              "At line %d.\n", (int) __LINE__);
   1409     ret = 1;
   1410   }
   1411   else if ((0 == ret) && cbc.excess_found)
   1412   {
   1413     fprintf (stderr, "The extra reply data have been detected one "
   1414              "or more times. "
   1415              "At line %d.\n", (int) __LINE__);
   1416     ret = 1;
   1417   }
   1418 
   1419   fprintf (stderr, "\n");
   1420   MHD_stop_daemon (d);
   1421   fflush (stderr);
   1422   return ret;
   1423 }
   1424 
   1425 
   1426 static unsigned int
   1427 testExternalPolling (uint16_t *pport, unsigned int daemon_flags)
   1428 {
   1429   struct MHD_Daemon *d;
   1430   CURLM *multi;
   1431   char buf[2048];
   1432   struct CBC cbc;
   1433   struct ahc_param_strct callback_param;
   1434   unsigned int ret;
   1435 #ifndef TEST_USE_STATIC_POST_DATA
   1436   curl_mime *mime;
   1437 #endif /* ! TEST_USE_STATIC_POST_DATA */
   1438 
   1439   if (0 != (MHD_USE_INTERNAL_POLLING_THREAD & daemon_flags))
   1440   {
   1441     fprintf (stderr, "Wrong internal flags, the test is broken. "
   1442              "At line %d.\n", (int) __LINE__);
   1443     abort (); /* Wrong flags, error in code */
   1444   }
   1445 
   1446   print_test_starting (daemon_flags);
   1447   initCBC (&cbc, buf, sizeof(buf));
   1448   d = start_daemon_for_test (daemon_flags, pport, &callback_param);
   1449   if (d == NULL)
   1450     return 1;
   1451 
   1452   ret = 0;
   1453   multi = curl_multi_init ();
   1454   if (multi == NULL)
   1455   {
   1456     fprintf (stderr, "curl_multi_init() failed "
   1457              "at line %d.\n", (int) __LINE__);
   1458     ret = 99; /* Not an MHD error */
   1459   }
   1460   else
   1461   {
   1462     CURL *c;
   1463     c = setupCURL (&cbc, *pport
   1464 #ifndef TEST_USE_STATIC_POST_DATA
   1465                    , &mime
   1466 #endif /* ! TEST_USE_STATIC_POST_DATA */
   1467                    );
   1468 
   1469     if (NULL == c)
   1470       ret = 99; /* Not an MHD error */
   1471     else
   1472     {
   1473       int i;
   1474 
   1475       for (i = dry_run ? LOOP_COUNT : 0;
   1476            (i < LOOP_COUNT) && (0 == ret); i++)
   1477       {
   1478         CURLMcode mret;
   1479 
   1480         /* The same 'multi' handle will be used in transfers so
   1481            connection will be reused.
   1482            The same 'easy' handle is added (and removed later) to (re-)start
   1483            the same transfer. */
   1484         mret = curl_multi_add_handle (multi, c);
   1485         if (CURLM_OK != mret)
   1486         {
   1487           fprintf (stderr, "curl_multi_add_handle() failed at %d, "
   1488                    "error: %s\n", (int) __LINE__,
   1489                    curl_multi_strerror (mret));
   1490           ret = 99; /* Not an MHD error */
   1491         }
   1492         else
   1493         {
   1494           time_t start;
   1495 
   1496           fprintf (stderr, ".");
   1497           callback_param.num_replies = 0;
   1498           resetCBC (&cbc);
   1499           start = time (NULL);
   1500           do
   1501           {
   1502             fd_set rs;
   1503             fd_set ws;
   1504             fd_set es;
   1505             int maxfd_curl;
   1506             MHD_socket maxfd_mhd;
   1507             int maxfd;
   1508             int running;
   1509             struct timeval tv;
   1510 
   1511             maxfd_curl = 0;
   1512             maxfd_mhd = MHD_INVALID_SOCKET;
   1513             FD_ZERO (&rs);
   1514             FD_ZERO (&ws);
   1515             FD_ZERO (&es);
   1516             curl_multi_perform (multi, &running);
   1517             if (0 == running)
   1518             {
   1519               int msgs_left;
   1520               do
   1521               {
   1522                 (void) curl_multi_info_read (multi, &msgs_left);
   1523               } while (0 != msgs_left);
   1524               break; /* The transfer has been finished */
   1525             }
   1526             mret = curl_multi_fdset (multi, &rs, &ws, &es, &maxfd_curl);
   1527             if (CURLM_OK != mret)
   1528             {
   1529               fprintf (stderr, "curl_multi_fdset() failed at line %d, "
   1530                        "error: %s\n", (int) __LINE__,
   1531                        curl_multi_strerror (mret));
   1532               ret = 99; /* Not an MHD error */
   1533               break;
   1534             }
   1535             if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxfd_mhd))
   1536             {
   1537               fprintf (stderr, "MHD_get_fdset() failed "
   1538                        "at line %d.\n", (int) __LINE__);
   1539               ret = 1;
   1540               break;
   1541             }
   1542 #ifndef MHD_WINSOCK_SOCKETS
   1543             if ((int) maxfd_mhd > maxfd_curl)
   1544               maxfd = (int) maxfd_mhd;
   1545             else
   1546 #endif /* ! MHD_WINSOCK_SOCKETS */
   1547             maxfd = maxfd_curl;
   1548             tv.tv_sec = 0;
   1549             tv.tv_usec = 100 * 1000;
   1550             if (0 == MHD_get_timeout64s (d))
   1551               tv.tv_usec = 0;
   1552             else
   1553             {
   1554               long curl_to = -1;
   1555               curl_multi_timeout (multi, &curl_to);
   1556               if (0 == curl_to)
   1557                 tv.tv_usec = 0;
   1558             }
   1559             if (-1 == select (maxfd + 1, &rs, &ws, &es, &tv))
   1560             {
   1561 #ifdef MHD_POSIX_SOCKETS
   1562               if (EINTR != errno)
   1563                 fprintf (stderr, "Unexpected select() error "
   1564                          "at line %d.\n", (int) __LINE__);
   1565 #else  /* ! MHD_POSIX_SOCKETS */
   1566               if ((WSAEINVAL != WSAGetLastError ()) ||
   1567                   (0 != rs.fd_count) || (0 != ws.fd_count) ||
   1568                   (0 != es.fd_count))
   1569                 fprintf (stderr, "Unexpected select() error "
   1570                          "at line %d.\n", (int) __LINE__);
   1571               Sleep ((unsigned long) tv.tv_usec / 1000);
   1572 #endif /* ! MHD_POSIX_SOCKETS */
   1573             }
   1574             MHD_run (d);
   1575           } while (time (NULL) - start <= MHD_TIMEOUT);
   1576           /* Remove 'easy' handle from 'multi' handle to
   1577            * restart the transfer or to finish. */
   1578           curl_multi_remove_handle (multi, c);
   1579         }
   1580       }
   1581       curl_easy_cleanup (c);
   1582     }
   1583     curl_multi_cleanup (multi);
   1584 #ifndef TEST_USE_STATIC_POST_DATA
   1585     if (NULL != mime)
   1586       curl_mime_free (mime);
   1587 #endif /* ! TEST_USE_STATIC_POST_DATA */
   1588   }
   1589 
   1590   if ((0 == ret) && callback_param.err_flag)
   1591   {
   1592     fprintf (stderr, "One or more errors have been detected by "
   1593              "access handler callback function. "
   1594              "At line %d.\n", (int) __LINE__);
   1595     ret = 1;
   1596   }
   1597   else if ((0 == ret) && cbc.excess_found)
   1598   {
   1599     fprintf (stderr, "The extra reply data have been detected one "
   1600              "or more times. "
   1601              "At line %d.\n", (int) __LINE__);
   1602     ret = 1;
   1603   }
   1604 
   1605   fprintf (stderr, "\n");
   1606   MHD_stop_daemon (d);
   1607   return 0;
   1608 }
   1609 
   1610 
   1611 static unsigned int
   1612 run_all_checks (void)
   1613 {
   1614   uint16_t port;
   1615   unsigned int testRes;
   1616   unsigned int ret = 0;
   1617 
   1618   if (! run_with_socat)
   1619   {
   1620     if (MHD_are_sanitizers_enabled_ ())
   1621     {
   1622       fprintf (stderr, "Direct run with zzuf does not work with sanitizers. "
   1623                "At line %d.\n", (int) __LINE__);
   1624       return 77;
   1625     }
   1626     if (! MHD_is_avoid_accept4_possible_ ())
   1627     {
   1628       fprintf (stderr,
   1629                "Non-debug build of MHD on this platform use accept4() function. "
   1630                "Direct run with zzuf is not possible. "
   1631                "At line %d.\n", (int) __LINE__);
   1632       return 77;
   1633     }
   1634     if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT))
   1635       port = 0;     /* Use system automatic assignment */
   1636     else
   1637     {
   1638       port = TEST_BASE_PORT;  /* Use predefined port, may break parallel testing of another MHD build */
   1639       if (oneone)
   1640         port += 100;
   1641       if (use_long_uri)
   1642         port += 30;
   1643       else if (use_long_header)
   1644         port += 35;
   1645       else if (use_get_chunked)
   1646         port += 0;
   1647       else if (use_get)
   1648         port += 5;
   1649       else if (use_post_form)
   1650         port += 10;
   1651       else if (use_post)
   1652         port += 15;
   1653       else if (use_put_large)
   1654         port += 20;
   1655       else if (use_put_chunked)
   1656         port += 25;
   1657       if (use_hostile_opts)
   1658         port += 40;
   1659     }
   1660   }
   1661   else
   1662     port = TEST_BASE_PORT;  /* Use predefined port, may break parallel testing of another MHD build */
   1663 
   1664   if (! dry_run && (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)))
   1665   {
   1666     testRes = testInternalPolling (&port, MHD_USE_SELECT_INTERNALLY);
   1667     if ((77 == testRes) || (99 == testRes))
   1668       return testRes;
   1669     ret += testRes;
   1670     testRes = testInternalPolling (&port, MHD_USE_SELECT_INTERNALLY
   1671                                    | MHD_USE_THREAD_PER_CONNECTION);
   1672     if ((77 == testRes) || (99 == testRes))
   1673       return testRes;
   1674     ret += testRes;
   1675 
   1676     if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL))
   1677     {
   1678       testRes = testInternalPolling (&port, MHD_USE_POLL_INTERNALLY);
   1679       if ((77 == testRes) || (99 == testRes))
   1680         return testRes;
   1681       ret += testRes;
   1682       testRes = testInternalPolling (&port, MHD_USE_POLL_INTERNALLY
   1683                                      | MHD_USE_THREAD_PER_CONNECTION);
   1684       if ((77 == testRes) || (99 == testRes))
   1685         return testRes;
   1686       ret += testRes;
   1687     }
   1688 
   1689     if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL))
   1690     {
   1691       testRes = testInternalPolling (&port, MHD_USE_EPOLL_INTERNALLY);
   1692       if ((77 == testRes) || (99 == testRes))
   1693         return testRes;
   1694     }
   1695     testRes = testExternalPolling (&port, MHD_NO_FLAG);
   1696   }
   1697   testRes = testExternalPolling (&port, MHD_USE_NO_THREAD_SAFETY);
   1698   if ((77 == testRes) || (99 == testRes))
   1699     return testRes;
   1700   ret += testRes;
   1701 
   1702   return ret;
   1703 }
   1704 
   1705 
   1706 int
   1707 main (int argc, char *const *argv)
   1708 {
   1709   unsigned int res;
   1710   int use_magic_exit_codes;
   1711 
   1712   oneone = ! has_in_name (argv[0], "10");
   1713   use_get = has_in_name (argv[0], "_get");
   1714   use_get_chunked = has_in_name (argv[0], "_get_chunked");
   1715   use_put = has_in_name (argv[0], "_put");
   1716   use_put_large = has_in_name (argv[0], "_put_large");
   1717   use_put_chunked = has_in_name (argv[0], "_put_chunked");
   1718   use_post = has_in_name (argv[0], "_post");
   1719   use_post_form = has_in_name (argv[0], "_post_form");
   1720   use_long_header = has_in_name (argv[0], "_long_header");
   1721   use_long_uri = has_in_name (argv[0], "_long_uri");
   1722   use_close = has_in_name (argv[0], "_close");
   1723   use_hostile_opts = has_in_name (argv[0], "_hostile");
   1724   cur_profile = zzuf_opt_profile (0);
   1725 
   1726   run_with_socat = has_param (argc, argv, "--with-socat");
   1727   dry_run = has_param (argc, argv, "--dry-run") ||
   1728             has_param (argc, argv, "-n");
   1729 
   1730   if (1 !=
   1731       ((use_get ? 1 : 0) + (use_put ? 1 : 0) + (use_post ? 1 : 0)))
   1732   {
   1733     fprintf (stderr, "Wrong test name '%s': no or multiple indications "
   1734              "for the test type.\n", argv[0] ? argv[0] : "(NULL)");
   1735     return 99;
   1736   }
   1737   use_magic_exit_codes = run_with_socat || dry_run;
   1738 
   1739   /* zzuf cannot bypass exit values.
   1740      Unless 'dry run' is used, do not return errors for external error
   1741      conditions (like out-of-memory) as they will be reported as test failures. */
   1742   if (! test_global_init ())
   1743     return use_magic_exit_codes ? 99 : 0;
   1744   res = run_all_checks ();
   1745   test_global_deinit ();
   1746   if (99 == res)
   1747     return use_magic_exit_codes ? 99 : 0;
   1748   if (77 == res)
   1749     return use_magic_exit_codes ? 77 : 0;
   1750   return (0 == res) ? 0 : 1;       /* 0 == pass */
   1751 }