test_add_conn.c (37724B)
1 /* 2 This file is part of libmicrohttpd 3 Copyright (C) 2007, 2009, 2011 Christian Grothoff 4 Copyright (C) 2014-2022 Evgeny Grin (Karlson2k) - large rework, 5 multithreading. 6 7 libmicrohttpd is free software; you can redistribute it and/or modify 8 it under the terms of the GNU General Public License as published 9 by the Free Software Foundation; either version 2, or (at your 10 option) any later version. 11 12 libmicrohttpd is distributed in the hope that it will be useful, but 13 WITHOUT ANY WARRANTY; without even the implied warranty of 14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 General Public License for more details. 16 17 You should have received a copy of the GNU General Public License 18 along with libmicrohttpd; see the file COPYING. If not, write to the 19 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, 20 Boston, MA 02110-1301, USA. 21 */ 22 /** 23 * @file test_add_conn.c 24 * @brief Testcase for libmicrohttpd GET operations 25 * @author Christian Grothoff 26 * @author Karlson2k (Evgeny Grin) 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 <errno.h> 36 #include "mhd_has_in_name.h" 37 #include "mhd_has_param.h" 38 #include "mhd_sockets.h" /* only macros used */ 39 40 /* Turn any MHD_PANIC() or failing mhd_assert() reached from this 41 test into a marked, classifiable test error (TESTING.md, P5). */ 42 #include "mhd_panic_tripwire.h" 43 44 45 #ifdef _WIN32 46 #ifndef WIN32_LEAN_AND_MEAN 47 #define WIN32_LEAN_AND_MEAN 1 48 #endif /* !WIN32_LEAN_AND_MEAN */ 49 #include <windows.h> 50 #endif 51 52 #ifndef WINDOWS 53 #include <unistd.h> 54 #include <sys/socket.h> 55 #endif 56 57 #ifdef HAVE_LIMITS_H 58 #include <limits.h> 59 #endif /* HAVE_LIMITS_H */ 60 61 #ifdef HAVE_PTHREAD_H 62 #include <pthread.h> 63 #endif /* HAVE_PTHREAD_H */ 64 65 #if defined(MHD_CPU_COUNT) && (MHD_CPU_COUNT + 0) < 2 66 #undef MHD_CPU_COUNT 67 #endif 68 #if ! defined(MHD_CPU_COUNT) 69 #define MHD_CPU_COUNT 2 70 #endif 71 #if MHD_CPU_COUNT > 32 72 #undef MHD_CPU_COUNT 73 /* Limit to reasonable value */ 74 #define MHD_CPU_COUNT 32 75 #endif /* MHD_CPU_COUNT > 32 */ 76 77 /* Could be increased to facilitate debugging */ 78 #define TIMEOUTS_VAL 5 79 80 /* Number of requests per daemon in cleanup test, 81 * the number must be more than one as the first connection 82 * will be processed and the rest will stay in the list of unprocessed */ 83 #define CLEANUP_NUM_REQS_PER_DAEMON 6 84 85 /* Cleanup test: max number of concurrent daemons depending on maximum number 86 * of open FDs. */ 87 #define CLEANUP_MAX_DAEMONS(max_fds) (unsigned int) \ 88 ( ((max_fds) < 10) ? \ 89 0 : ( (((max_fds) - 10) / (CLEANUP_NUM_REQS_PER_DAEMON * 5 + 3)) ) ) 90 91 #define EXPECTED_URI_BASE_PATH "/hello_world" 92 #define EXPECTED_URI_QUERY "a=%26&b=c" 93 #define EXPECTED_URI_FULL_PATH EXPECTED_URI_BASE_PATH "?" EXPECTED_URI_QUERY 94 95 /* Global parameters */ 96 static int oneone; /**< Use HTTP/1.1 instead of HTTP/1.0 */ 97 static int no_listen; /**< Start MHD daemons without listen socket */ 98 static uint16_t global_port; /**< MHD daemons listen port number */ 99 static int cleanup_test; /**< Test for final cleanup */ 100 static int slow_reply = 0; /**< Slowdown MHD replies */ 101 static int ignore_response_errors = 0; /**< Do not fail test if CURL 102 returns error */ 103 static int response_timeout_val = TIMEOUTS_VAL; 104 static int sys_max_fds; /**< Current system limit for number of open 105 files. */ 106 107 108 struct CBC 109 { 110 char *buf; 111 size_t pos; 112 size_t size; 113 }; 114 115 116 static size_t 117 copyBuffer (void *ptr, size_t size, size_t nmemb, void *ctx) 118 { 119 struct CBC *cbc = ctx; 120 121 if (cbc->pos + size * nmemb > cbc->size) 122 return 0; /* overflow */ 123 memcpy (&cbc->buf[cbc->pos], ptr, size * nmemb); 124 cbc->pos += size * nmemb; 125 return size * nmemb; 126 } 127 128 129 static void * 130 log_cb (void *cls, 131 const char *uri, 132 struct MHD_Connection *con) 133 { 134 (void) cls; 135 (void) con; 136 if (0 != strcmp (uri, 137 EXPECTED_URI_FULL_PATH)) 138 { 139 fprintf (stderr, 140 "Wrong URI: `%s'\n", 141 uri); 142 _exit (22); 143 } 144 return NULL; 145 } 146 147 148 static enum MHD_Result 149 ahc_echo (void *cls, 150 struct MHD_Connection *connection, 151 const char *url, 152 const char *method, 153 const char *version, 154 const char *upload_data, size_t *upload_data_size, 155 void **req_cls) 156 { 157 static int ptr; 158 struct MHD_Response *response; 159 enum MHD_Result ret; 160 const char *v; 161 (void) cls; 162 (void) version; 163 (void) upload_data; 164 (void) upload_data_size; /* Unused. Silence compiler warning. */ 165 166 if (0 != strcmp (MHD_HTTP_METHOD_GET, method)) 167 return MHD_NO; /* unexpected method */ 168 if (&ptr != *req_cls) 169 { 170 *req_cls = &ptr; 171 return MHD_YES; 172 } 173 *req_cls = NULL; 174 v = MHD_lookup_connection_value (connection, 175 MHD_GET_ARGUMENT_KIND, 176 "a"); 177 if ( (NULL == v) || 178 (0 != strcmp ("&", 179 v)) ) 180 { 181 fprintf (stderr, "Found while looking for 'a=&': 'a=%s'\n", 182 NULL == v ? "NULL" : v); 183 _exit (17); 184 } 185 v = NULL; 186 if (MHD_YES != MHD_lookup_connection_value_n (connection, 187 MHD_GET_ARGUMENT_KIND, 188 "b", 189 1, 190 &v, 191 NULL)) 192 { 193 fprintf (stderr, "Not found 'b' GET argument.\n"); 194 _exit (18); 195 } 196 if ( (NULL == v) || 197 (0 != strcmp ("c", 198 v)) ) 199 { 200 fprintf (stderr, "Found while looking for 'b=c': 'b=%s'\n", 201 NULL == v ? "NULL" : v); 202 _exit (19); 203 } 204 if (slow_reply) 205 usleep (200000); 206 207 response = MHD_create_response_from_buffer_copy (strlen (url), 208 (const void *) url); 209 ret = MHD_queue_response (connection, 210 MHD_HTTP_OK, 211 response); 212 MHD_destroy_response (response); 213 if (ret == MHD_NO) 214 { 215 fprintf (stderr, "Failed to queue response.\n"); 216 _exit (19); 217 } 218 return ret; 219 } 220 221 222 _MHD_NORETURN static void 223 _externalErrorExit_func (const char *errDesc, const char *funcName, int lineNum) 224 { 225 if ((NULL != errDesc) && (0 != errDesc[0])) 226 fprintf (stderr, "%s", errDesc); 227 else 228 fprintf (stderr, "System or external library call failed"); 229 if ((NULL != funcName) && (0 != funcName[0])) 230 fprintf (stderr, " in %s", funcName); 231 if (0 < lineNum) 232 fprintf (stderr, " at line %d", lineNum); 233 234 fprintf (stderr, ".\nLast errno value: %d (%s)\n", (int) errno, 235 strerror (errno)); 236 #ifdef MHD_WINSOCK_SOCKETS 237 fprintf (stderr, "WSAGetLastError() value: %d\n", (int) WSAGetLastError ()); 238 #endif /* MHD_WINSOCK_SOCKETS */ 239 fflush (stderr); 240 _exit (99); 241 } 242 243 244 #if defined(HAVE___FUNC__) 245 #define externalErrorExit(ignore) \ 246 _externalErrorExit_func (NULL, __func__, __LINE__) 247 #define externalErrorExitDesc(errDesc) \ 248 _externalErrorExit_func (errDesc, __func__, __LINE__) 249 #elif defined(HAVE___FUNCTION__) 250 #define externalErrorExit(ignore) \ 251 _externalErrorExit_func (NULL, __FUNCTION__, __LINE__) 252 #define externalErrorExitDesc(errDesc) \ 253 _externalErrorExit_func (errDesc, __FUNCTION__, __LINE__) 254 #else 255 #define externalErrorExit(ignore) _externalErrorExit_func (NULL, NULL, __LINE__) 256 #define externalErrorExitDesc(errDesc) \ 257 _externalErrorExit_func (errDesc, NULL, __LINE__) 258 #endif 259 260 261 /* Static const value, indicates that result value was not set yet */ 262 static const unsigned int eMarker = 0xCE; 263 264 265 static MHD_socket 266 createListeningSocket (uint16_t *pport) 267 { 268 MHD_socket skt; 269 struct sockaddr_in sin; 270 socklen_t sin_len; 271 #ifdef MHD_POSIX_SOCKETS 272 static int on = 1; 273 #endif /* MHD_POSIX_SOCKETS */ 274 275 skt = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP); 276 if (MHD_INVALID_SOCKET == skt) 277 externalErrorExitDesc ("socket() failed"); 278 279 #ifdef MHD_POSIX_SOCKETS 280 setsockopt (skt, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof (on)); 281 /* Ignore possible error */ 282 #endif /* MHD_POSIX_SOCKETS */ 283 284 memset (&sin, 0, sizeof(sin)); 285 sin.sin_family = AF_INET; 286 sin.sin_port = htons (*pport); 287 sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK); 288 if (0 != bind (skt, (struct sockaddr *) &sin, sizeof(sin))) 289 externalErrorExitDesc ("bind() failed"); 290 291 if (0 != listen (skt, SOMAXCONN)) 292 externalErrorExitDesc ("listen() failed"); 293 294 if (0 == *pport) 295 { 296 memset (&sin, 0, sizeof(sin)); 297 sin_len = (socklen_t) sizeof(sin); 298 if (0 != getsockname (skt, (struct sockaddr *) &sin, &sin_len)) 299 externalErrorExitDesc ("getsockname() failed"); 300 301 if (sizeof(sin) < (size_t) sin_len) 302 externalErrorExitDesc ("getsockname() failed"); 303 304 if (AF_INET != sin.sin_family) 305 externalErrorExitDesc ("getsockname() returned wrong socket family"); 306 307 *pport = ntohs (sin.sin_port); 308 } 309 310 return skt; 311 } 312 313 314 static MHD_socket 315 acceptTimeLimited (MHD_socket lstn_sk, struct sockaddr *paddr, 316 socklen_t *paddr_len) 317 { 318 fd_set rs; 319 struct timeval timeoutval; 320 MHD_socket accepted; 321 322 FD_ZERO (&rs); 323 FD_SET (lstn_sk, &rs); 324 timeoutval.tv_sec = TIMEOUTS_VAL; 325 timeoutval.tv_usec = 0; 326 if (1 != select (((int) lstn_sk) + 1, &rs, NULL, NULL, &timeoutval)) 327 externalErrorExitDesc ("select() failed"); 328 329 accepted = accept (lstn_sk, paddr, paddr_len); 330 if (MHD_INVALID_SOCKET == accepted) 331 externalErrorExitDesc ("accept() failed"); 332 333 return accepted; 334 } 335 336 337 struct addConnParam 338 { 339 struct MHD_Daemon *d; 340 341 MHD_socket lstn_sk; 342 343 MHD_socket clent_sk; 344 /* Non-zero indicate error */ 345 volatile unsigned int result; 346 347 #ifdef HAVE_PTHREAD_H 348 pthread_t addConnThread; 349 #endif /* HAVE_PTHREAD_H */ 350 }; 351 352 static unsigned int 353 doAcceptAndAddConnInThread (struct addConnParam *p) 354 { 355 struct sockaddr addr; 356 socklen_t addr_len = sizeof(addr); 357 358 p->clent_sk = acceptTimeLimited (p->lstn_sk, &addr, &addr_len); 359 360 p->result = (MHD_YES == MHD_add_connection (p->d, p->clent_sk, 361 &addr, addr_len)) ? 362 0 : 1; 363 if (p->result) 364 fprintf (stderr, "MHD_add_connection() failed, errno=%d.\n", errno); 365 return p->result; 366 } 367 368 369 #ifdef HAVE_PTHREAD_H 370 static void * 371 doAcceptAndAddConn (void *param) 372 { 373 struct addConnParam *p = param; 374 375 (void) doAcceptAndAddConnInThread (p); 376 377 return (void *) p; 378 } 379 380 381 static void 382 startThreadAddConn (struct addConnParam *param) 383 { 384 /* thread must reset this value to zero if succeed */ 385 param->result = eMarker; 386 387 if (0 != pthread_create (¶m->addConnThread, NULL, &doAcceptAndAddConn, 388 (void *) param)) 389 externalErrorExitDesc ("pthread_create() failed"); 390 } 391 392 393 static unsigned int 394 finishThreadAddConn (struct addConnParam *param) 395 { 396 struct addConnParam *result; 397 398 if (0 != pthread_join (param->addConnThread, (void **) &result)) 399 externalErrorExitDesc ("pthread_join() failed"); 400 401 if (param != result) 402 abort (); /* Test used in a wrong way */ 403 404 if (eMarker == param->result) 405 abort (); /* Test used in a wrong way */ 406 407 return result->result; 408 } 409 410 411 #endif /* HAVE_PTHREAD_H */ 412 413 414 struct curlQueryParams 415 { 416 /* Destination path for CURL query */ 417 const char *queryPath; 418 419 /* Destination port for CURL query */ 420 uint16_t queryPort; 421 422 /* CURL query result error flag */ 423 volatile unsigned int queryError; 424 425 #ifdef HAVE_PTHREAD_H 426 pthread_t queryThread; 427 #endif /* HAVE_PTHREAD_H */ 428 }; 429 430 static CURL * 431 curlEasyInitForTest (const char *queryPath, uint16_t port, struct CBC *pcbc) 432 { 433 CURL *c; 434 435 c = curl_easy_init (); 436 if (NULL == c) 437 { 438 fprintf (stderr, "curl_easy_init() failed.\n"); 439 _exit (99); 440 } 441 if ((CURLE_OK != curl_easy_setopt (c, CURLOPT_NOSIGNAL, 1L)) || 442 (CURLE_OK != curl_easy_setopt (c, CURLOPT_PROXY, "")) || 443 (CURLE_OK != curl_easy_setopt (c, CURLOPT_URL, queryPath)) || 444 (CURLE_OK != curl_easy_setopt (c, CURLOPT_PORT, (long) port)) || 445 (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEFUNCTION, 446 ©Buffer)) || 447 (CURLE_OK != curl_easy_setopt (c, CURLOPT_WRITEDATA, pcbc)) || 448 (CURLE_OK != curl_easy_setopt (c, CURLOPT_CONNECTTIMEOUT, 449 (long) response_timeout_val)) || 450 (CURLE_OK != curl_easy_setopt (c, CURLOPT_TIMEOUT, 451 (long) response_timeout_val)) || 452 (CURLE_OK != curl_easy_setopt (c, CURLOPT_FAILONERROR, 1L)) || 453 (CURLE_OK != curl_easy_setopt (c, CURLOPT_HTTP_VERSION, 454 (oneone) ? 455 CURL_HTTP_VERSION_1_1 : 456 CURL_HTTP_VERSION_1_0))) 457 { 458 fprintf (stderr, "curl_easy_setopt() failed.\n"); 459 _exit (99); 460 } 461 462 return c; 463 } 464 465 466 static unsigned int 467 doCurlQueryInThread (struct curlQueryParams *p) 468 { 469 CURL *c; 470 char buf[2048]; 471 struct CBC cbc; 472 CURLcode errornum; 473 474 if (NULL == p->queryPath) 475 abort (); 476 477 if (0 == p->queryPort) 478 abort (); 479 480 cbc.buf = buf; 481 cbc.size = sizeof(buf); 482 cbc.pos = 0; 483 484 c = curlEasyInitForTest (p->queryPath, p->queryPort, &cbc); 485 486 errornum = curl_easy_perform (c); 487 if (ignore_response_errors) 488 { 489 p->queryError = 0; 490 curl_easy_cleanup (c); 491 492 return p->queryError; 493 } 494 if (CURLE_OK != errornum) 495 { 496 fprintf (stderr, 497 "curl_easy_perform failed: `%s'\n", 498 curl_easy_strerror (errornum)); 499 p->queryError = 2; 500 } 501 else 502 { 503 if (cbc.pos != strlen (EXPECTED_URI_BASE_PATH)) 504 { 505 fprintf (stderr, "curl reports wrong size of MHD reply body data.\n"); 506 p->queryError = 4; 507 } 508 else if (0 != strncmp (EXPECTED_URI_BASE_PATH, cbc.buf, 509 strlen (EXPECTED_URI_BASE_PATH))) 510 { 511 fprintf (stderr, "curl reports wrong MHD reply body data.\n"); 512 p->queryError = 4; 513 } 514 else 515 p->queryError = 0; 516 } 517 curl_easy_cleanup (c); 518 519 return p->queryError; 520 } 521 522 523 #ifdef HAVE_PTHREAD_H 524 static void * 525 doCurlQuery (void *param) 526 { 527 struct curlQueryParams *p = (struct curlQueryParams *) param; 528 529 (void) doCurlQueryInThread (p); 530 531 return param; 532 } 533 534 535 static void 536 startThreadCurlQuery (struct curlQueryParams *param) 537 { 538 /* thread must reset this value to zero if succeed */ 539 param->queryError = eMarker; 540 541 if (0 != pthread_create (¶m->queryThread, NULL, &doCurlQuery, 542 (void *) param)) 543 externalErrorExitDesc ("pthread_create() failed"); 544 } 545 546 547 static unsigned int 548 finishThreadCurlQuery (struct curlQueryParams *param) 549 { 550 struct curlQueryParams *result; 551 552 if (0 != pthread_join (param->queryThread, (void **) &result)) 553 externalErrorExitDesc ("pthread_join() failed"); 554 555 if (param != result) 556 abort (); /* Test used in wrong way */ 557 558 if (eMarker == param->queryError) 559 abort (); /* Test used in wrong way */ 560 561 return result->queryError; 562 } 563 564 565 /* Perform test queries and shut down MHD daemon */ 566 static unsigned int 567 performTestQueries (struct MHD_Daemon *d, uint16_t d_port) 568 { 569 struct curlQueryParams qParam; 570 struct addConnParam aParam; 571 uint16_t a_port; /* Additional listening socket port */ 572 unsigned int ret = 0; /* Return value */ 573 574 qParam.queryPath = "http://127.0.0.1" EXPECTED_URI_FULL_PATH; 575 a_port = 0; /* auto-assign */ 576 577 aParam.d = d; 578 aParam.lstn_sk = createListeningSocket (&a_port); /* Sets a_port */ 579 580 /* Test of adding connection in the same thread */ 581 qParam.queryError = eMarker; /* to be zeroed in new thread */ 582 qParam.queryPort = a_port; /* Connect to additional socket */ 583 startThreadCurlQuery (&qParam); 584 ret |= doAcceptAndAddConnInThread (&aParam); 585 ret |= finishThreadCurlQuery (&qParam); 586 587 if (! no_listen) 588 { 589 /* Test of the daemon itself can accept and process new connection. */ 590 ret <<= 3; /* Remember errors for each step */ 591 qParam.queryPort = d_port; /* Connect to the daemon */ 592 ret |= doCurlQueryInThread (&qParam); 593 } 594 595 /* Test of adding connection in an external thread */ 596 ret <<= 3; /* Remember errors for each step */ 597 aParam.result = eMarker; /* to be zeroed in new thread */ 598 qParam.queryPort = a_port; /* Connect to the daemon */ 599 startThreadAddConn (&aParam); 600 ret |= doCurlQueryInThread (&qParam); 601 ret |= finishThreadAddConn (&aParam); 602 603 (void) MHD_socket_close_ (aParam.lstn_sk); 604 MHD_stop_daemon (d); 605 606 return ret; 607 } 608 609 610 /* Perform test for cleanup and shutdown MHD daemon */ 611 static unsigned int 612 performTestCleanup (struct MHD_Daemon *d, unsigned int num_queries) 613 { 614 struct curlQueryParams *qParamList; 615 struct addConnParam aParam; 616 MHD_socket lstn_sk; /* Additional listening socket */ 617 MHD_socket *clntSkList; 618 uint16_t a_port; /* Additional listening socket port */ 619 unsigned int i; 620 unsigned int ret = 0; /* Return value */ 621 622 a_port = 0; /* auto-assign */ 623 624 if (0 >= num_queries) 625 abort (); /* Test's API violation */ 626 627 lstn_sk = createListeningSocket (&a_port); /* Sets a_port */ 628 629 qParamList = malloc (sizeof(struct curlQueryParams) * num_queries); 630 clntSkList = malloc (sizeof(MHD_socket) * num_queries); 631 if ((NULL == qParamList) || (NULL == clntSkList)) 632 externalErrorExitDesc ("malloc failed"); 633 634 /* Start CURL queries */ 635 for (i = 0; i < num_queries; i++) 636 { 637 qParamList[i].queryPath = "http://127.0.0.1" EXPECTED_URI_FULL_PATH; 638 qParamList[i].queryError = 0; 639 qParamList[i].queryPort = a_port; 640 641 startThreadCurlQuery (qParamList + i); 642 } 643 644 /* Accept and add required number of client sockets */ 645 aParam.d = d; 646 aParam.lstn_sk = lstn_sk; 647 for (i = 0; i < num_queries; i++) 648 { 649 aParam.clent_sk = MHD_INVALID_SOCKET; 650 ret |= doAcceptAndAddConnInThread (&aParam); 651 clntSkList[i] = aParam.clent_sk; 652 } 653 654 /* Stop daemon while some of new connection are not yet 655 * processed because of slow response to the first queries. */ 656 MHD_stop_daemon (d); 657 (void) MHD_socket_close_ (aParam.lstn_sk); 658 659 /* Check whether all client sockets were closed by MHD. 660 * Closure of socket by MHD indicate valid cleanup performed. */ 661 for (i = 0; i < num_queries; i++) 662 { 663 if (MHD_INVALID_SOCKET != clntSkList[i]) 664 { /* Check whether socket could be closed one more time. */ 665 if (MHD_socket_close_ (clntSkList[i])) 666 { 667 ret |= 2; 668 fprintf (stderr, "Client socket was not closed by MHD during" \ 669 "cleanup process.\n"); 670 } 671 } 672 } 673 674 /* Wait for CURL threads to complete. */ 675 /* Ignore soft CURL errors as many connection shouldn't get any response. 676 * Hard failures are detected in processing function. */ 677 for (i = 0; i < num_queries; i++) 678 (void) finishThreadCurlQuery (qParamList + i); 679 680 free (clntSkList); 681 free (qParamList); 682 683 return ret; 684 } 685 686 687 #endif /* HAVE_PTHREAD_H */ 688 689 enum testMhdThreadsType 690 { 691 testMhdThreadExternal = 0, 692 testMhdThreadInternal = MHD_USE_INTERNAL_POLLING_THREAD, 693 testMhdThreadInternalPerConnection = MHD_USE_THREAD_PER_CONNECTION 694 | MHD_USE_INTERNAL_POLLING_THREAD, 695 testMhdThreadInternalPool 696 }; 697 698 enum testMhdPollType 699 { 700 testMhdPollBySelect = 0, 701 testMhdPollByPoll = MHD_USE_POLL, 702 testMhdPollByEpoll = MHD_USE_EPOLL, 703 testMhdPollAuto = MHD_USE_AUTO 704 }; 705 706 /* Get number of threads for thread pool depending 707 * on used poll function and test type. */ 708 static unsigned int 709 testNumThreadsForPool (enum testMhdPollType pollType) 710 { 711 unsigned int numThreads = MHD_CPU_COUNT; 712 if (! cleanup_test) 713 return numThreads; /* No practical limit for non-cleanup test */ 714 if (CLEANUP_MAX_DAEMONS (sys_max_fds) < numThreads) 715 numThreads = CLEANUP_MAX_DAEMONS (sys_max_fds); 716 if ((testMhdPollBySelect == pollType) && 717 (CLEANUP_MAX_DAEMONS (FD_SETSIZE) < numThreads)) 718 numThreads = CLEANUP_MAX_DAEMONS (FD_SETSIZE); 719 720 if (2 > numThreads) 721 abort (); 722 return (unsigned int) numThreads; 723 } 724 725 726 static struct MHD_Daemon * 727 startTestMhdDaemon (enum testMhdThreadsType thrType, 728 enum testMhdPollType pollType, uint16_t *pport) 729 { 730 struct MHD_Daemon *d; 731 const union MHD_DaemonInfo *dinfo; 732 733 if ( (0 == *pport) && 734 (MHD_NO == MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) ) 735 { 736 *pport = 1550; 737 if (oneone) 738 *pport += 1; 739 if (no_listen) 740 *pport += 2; 741 if (cleanup_test) 742 *pport += 4; 743 } 744 745 switch (thrType) 746 { 747 case testMhdThreadExternal: 748 d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType) 749 | MHD_USE_NO_THREAD_SAFETY 750 | (no_listen ? MHD_USE_NO_LISTEN_SOCKET : 0) 751 | MHD_USE_ERROR_LOG, 752 *pport, NULL, NULL, 753 &ahc_echo, NULL, 754 MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, 755 MHD_OPTION_APP_FD_SETSIZE, (int) FD_SETSIZE, 756 MHD_OPTION_END); 757 break; 758 case testMhdThreadInternalPool: 759 d = MHD_start_daemon (MHD_USE_INTERNAL_POLLING_THREAD 760 | ((unsigned int) pollType) 761 | MHD_USE_ITC 762 | (no_listen ? MHD_USE_NO_LISTEN_SOCKET : 0) 763 | MHD_USE_ERROR_LOG, 764 *pport, NULL, NULL, 765 &ahc_echo, NULL, 766 MHD_OPTION_THREAD_POOL_SIZE, 767 testNumThreadsForPool (pollType), 768 MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, 769 MHD_OPTION_END); 770 break; 771 case testMhdThreadInternal: 772 case testMhdThreadInternalPerConnection: 773 d = MHD_start_daemon (((unsigned int) thrType) | ((unsigned int) pollType) 774 | MHD_USE_ITC 775 | (no_listen ? MHD_USE_NO_LISTEN_SOCKET : 0) 776 | MHD_USE_ERROR_LOG, 777 *pport, NULL, NULL, 778 &ahc_echo, NULL, 779 MHD_OPTION_URI_LOG_CALLBACK, &log_cb, NULL, 780 MHD_OPTION_END); 781 break; 782 default: 783 abort (); 784 break; 785 } 786 787 if (NULL == d) 788 { 789 fprintf (stderr, "Failed to start MHD daemon, errno=%d.\n", errno); 790 abort (); 791 } 792 793 if ((! no_listen) && (0 == *pport)) 794 { 795 dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); 796 if ((NULL == dinfo) || (0 == dinfo->port) ) 797 { 798 fprintf (stderr, "MHD_get_daemon_info() failed.\n"); 799 abort (); 800 } 801 *pport = dinfo->port; 802 } 803 804 return d; 805 } 806 807 808 /* Test runners */ 809 810 811 static unsigned int 812 testExternalGet (void) 813 { 814 struct MHD_Daemon *d; 815 CURL *c_d; 816 char buf_d[2048]; 817 struct CBC cbc_d; 818 CURL *c_a; 819 char buf_a[2048]; 820 struct CBC cbc_a; 821 CURLM *multi; 822 time_t start; 823 struct timeval tv; 824 uint16_t d_port = global_port; /* Daemon's port */ 825 uint16_t a_port = 0; /* Additional listening socket port */ 826 struct addConnParam aParam; 827 unsigned int ret = 0; /* Return value of the test */ 828 const int c_no_listen = no_listen; /* Local const value to mute analyzer */ 829 830 d = startTestMhdDaemon (testMhdThreadExternal, testMhdPollBySelect, &d_port); 831 832 aParam.d = d; 833 aParam.lstn_sk = createListeningSocket (&a_port); 834 835 multi = NULL; 836 cbc_d.buf = buf_d; 837 cbc_d.size = sizeof(buf_d); 838 cbc_d.pos = 0; 839 cbc_a.buf = buf_a; 840 cbc_a.size = sizeof(buf_a); 841 cbc_a.pos = 0; 842 843 if (cleanup_test) 844 abort (); /* Not possible with "external poll" as connections are directly 845 added to the daemon processing in the mode. */ 846 847 if (! c_no_listen) 848 c_d = curlEasyInitForTest ("http://127.0.0.1" EXPECTED_URI_FULL_PATH, 849 d_port, &cbc_d); 850 else 851 c_d = NULL; /* To mute compiler warning only */ 852 853 c_a = curlEasyInitForTest ("http://127.0.0.1" EXPECTED_URI_FULL_PATH, 854 a_port, &cbc_a); 855 856 multi = curl_multi_init (); 857 if (multi == NULL) 858 { 859 fprintf (stderr, "curl_multi_init() failed.\n"); 860 _exit (99); 861 } 862 if (! c_no_listen) 863 { 864 if (CURLM_OK != curl_multi_add_handle (multi, c_d)) 865 { 866 fprintf (stderr, "curl_multi_add_handle() failed.\n"); 867 _exit (99); 868 } 869 } 870 871 if (CURLM_OK != curl_multi_add_handle (multi, c_a)) 872 { 873 fprintf (stderr, "curl_multi_add_handle() failed.\n"); 874 _exit (99); 875 } 876 877 start = time (NULL); 878 while (time (NULL) - start <= TIMEOUTS_VAL) 879 { 880 fd_set rs; 881 fd_set ws; 882 fd_set es; 883 MHD_socket maxMhdSk; 884 int maxCurlSk; 885 int running; 886 887 maxMhdSk = MHD_INVALID_SOCKET; 888 maxCurlSk = -1; 889 FD_ZERO (&rs); 890 FD_ZERO (&ws); 891 FD_ZERO (&es); 892 curl_multi_perform (multi, &running); 893 if (0 == running) 894 { 895 struct CURLMsg *msg; 896 int msgLeft; 897 int totalMsgs = 0; 898 do 899 { 900 msg = curl_multi_info_read (multi, &msgLeft); 901 if (NULL == msg) 902 { 903 fprintf (stderr, "curl_multi_info_read failed, NULL returned.\n"); 904 _exit (99); 905 } 906 totalMsgs++; 907 if (CURLMSG_DONE == msg->msg) 908 { 909 if (CURLE_OK != msg->data.result) 910 { 911 fprintf (stderr, "curl_multi_info_read failed, error: '%s'\n", 912 curl_easy_strerror (msg->data.result)); 913 ret |= 2; 914 } 915 } 916 } while (msgLeft > 0); 917 if ((no_listen ? 1 : 2) != totalMsgs) 918 { 919 fprintf (stderr, 920 "curl_multi_info_read returned wrong " 921 "number of results (%d).\n", 922 totalMsgs); 923 _exit (99); 924 } 925 break; /* All transfers have finished. */ 926 } 927 if (CURLM_OK != curl_multi_fdset (multi, &rs, &ws, &es, &maxCurlSk)) 928 { 929 fprintf (stderr, "curl_multi_fdset() failed.\n"); 930 _exit (99); 931 } 932 if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &maxMhdSk)) 933 { 934 ret |= 8; 935 break; 936 } 937 FD_SET (aParam.lstn_sk, &rs); 938 if (maxMhdSk < aParam.lstn_sk) 939 maxMhdSk = aParam.lstn_sk; 940 tv.tv_sec = 0; 941 tv.tv_usec = 1000; 942 #ifdef MHD_POSIX_SOCKETS 943 if (maxMhdSk > maxCurlSk) 944 maxCurlSk = maxMhdSk; 945 #endif /* MHD_POSIX_SOCKETS */ 946 if (-1 == select (maxCurlSk + 1, &rs, &ws, &es, &tv)) 947 { 948 #ifdef MHD_POSIX_SOCKETS 949 if (EINTR != errno) 950 { 951 fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", 952 (int) errno, __LINE__); 953 fflush (stderr); 954 exit (99); 955 } 956 #else 957 if ((WSAEINVAL != WSAGetLastError ()) || 958 (0 != rs.fd_count) || (0 != ws.fd_count) || (0 != es.fd_count) ) 959 { 960 fprintf (stderr, "Unexpected select() error: %d. Line: %d\n", 961 (int) WSAGetLastError (), __LINE__); 962 fflush (stderr); 963 exit (99); 964 } 965 Sleep (1); 966 #endif 967 } 968 if (FD_ISSET (aParam.lstn_sk, &rs)) 969 ret |= doAcceptAndAddConnInThread (&aParam); 970 971 if (MHD_YES != MHD_run_from_select (d, &rs, &ws, &es)) 972 { 973 fprintf (stderr, "MHD_run_from_select() failed.\n"); 974 ret |= 1; 975 break; 976 } 977 } 978 979 MHD_stop_daemon (d); 980 (void) MHD_socket_close_ (aParam.lstn_sk); 981 982 if (! c_no_listen) 983 { 984 curl_multi_remove_handle (multi, c_d); 985 curl_easy_cleanup (c_d); 986 if (cbc_d.pos != strlen ("/hello_world")) 987 { 988 fprintf (stderr, 989 "curl reports wrong size of MHD reply body data at line %d.\n", 990 __LINE__); 991 ret |= 4; 992 } 993 if (0 != strncmp ("/hello_world", cbc_d.buf, strlen ("/hello_world"))) 994 { 995 fprintf (stderr, "curl reports wrong MHD reply body data at line %d.\n", 996 __LINE__); 997 ret |= 4; 998 } 999 } 1000 curl_multi_remove_handle (multi, c_a); 1001 curl_easy_cleanup (c_a); 1002 curl_multi_cleanup (multi); 1003 if (cbc_a.pos != strlen ("/hello_world")) 1004 { 1005 fprintf (stderr, 1006 "curl reports wrong size of MHD reply body data at line %d.\n", 1007 __LINE__); 1008 ret |= 4; 1009 } 1010 if (0 != strncmp ("/hello_world", cbc_a.buf, strlen ("/hello_world"))) 1011 { 1012 fprintf (stderr, "curl reports wrong MHD reply body data at line %d.\n", 1013 __LINE__); 1014 ret |= 4; 1015 } 1016 return ret; 1017 } 1018 1019 1020 #ifdef HAVE_PTHREAD_H 1021 static unsigned int 1022 testInternalGet (enum testMhdPollType pollType) 1023 { 1024 struct MHD_Daemon *d; 1025 uint16_t d_port = global_port; /* Daemon's port */ 1026 1027 d = startTestMhdDaemon (testMhdThreadInternal, pollType, 1028 &d_port); 1029 if (cleanup_test) 1030 return performTestCleanup (d, CLEANUP_NUM_REQS_PER_DAEMON); 1031 1032 return performTestQueries (d, d_port); 1033 } 1034 1035 1036 static unsigned int 1037 testMultithreadedGet (enum testMhdPollType pollType) 1038 { 1039 struct MHD_Daemon *d; 1040 uint16_t d_port = global_port; /* Daemon's port */ 1041 1042 d = startTestMhdDaemon (testMhdThreadInternalPerConnection, pollType, 1043 &d_port); 1044 if (cleanup_test) 1045 abort (); /* Cannot be tested as main daemon thread cannot be slowed down 1046 by slow responses, so it processes all new connections before 1047 daemon could be stopped. */ 1048 1049 return performTestQueries (d, d_port); 1050 } 1051 1052 1053 static unsigned int 1054 testMultithreadedPoolGet (enum testMhdPollType pollType) 1055 { 1056 struct MHD_Daemon *d; 1057 uint16_t d_port = global_port; /* Daemon's port */ 1058 1059 d = startTestMhdDaemon (testMhdThreadInternalPool, pollType, 1060 &d_port); 1061 1062 if (cleanup_test) 1063 return performTestCleanup (d, CLEANUP_NUM_REQS_PER_DAEMON 1064 * testNumThreadsForPool (pollType)); 1065 return performTestQueries (d, d_port); 1066 } 1067 1068 1069 static unsigned int 1070 testStopRace (enum testMhdPollType pollType) 1071 { 1072 struct MHD_Daemon *d; 1073 uint16_t d_port = global_port; /* Daemon's port */ 1074 uint16_t a_port = 0; /* Additional listening socket port */ 1075 struct sockaddr_in sin; 1076 MHD_socket fd1; 1077 MHD_socket fd2; 1078 struct addConnParam aParam; 1079 unsigned int ret = 0; /* Return value of the test */ 1080 1081 d = startTestMhdDaemon (testMhdThreadInternal, pollType, 1082 &d_port); 1083 1084 if (! no_listen) 1085 { 1086 fd1 = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP); 1087 if (MHD_INVALID_SOCKET == fd1) 1088 externalErrorExitDesc ("socket() failed"); 1089 1090 memset (&sin, 0, sizeof(sin)); 1091 sin.sin_family = AF_INET; 1092 sin.sin_port = htons (d_port); 1093 sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK); 1094 if (connect (fd1, (struct sockaddr *) (&sin), sizeof(sin)) < 0) 1095 externalErrorExitDesc ("socket() failed"); 1096 } 1097 else 1098 fd1 = MHD_INVALID_SOCKET; 1099 1100 aParam.d = d; 1101 aParam.lstn_sk = createListeningSocket (&a_port); /* Sets a_port */ 1102 startThreadAddConn (&aParam); 1103 1104 fd2 = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP); 1105 if (MHD_INVALID_SOCKET == fd2) 1106 externalErrorExitDesc ("socket() failed"); 1107 memset (&sin, 0, sizeof(sin)); 1108 sin.sin_family = AF_INET; 1109 sin.sin_port = htons (a_port); 1110 sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK); 1111 if (connect (fd2, (struct sockaddr *) (&sin), sizeof(sin)) < 0) 1112 externalErrorExitDesc ("socket() failed"); 1113 ret |= finishThreadAddConn (&aParam); 1114 1115 /* Let the thread get going. */ 1116 usleep (500000); 1117 1118 MHD_stop_daemon (d); 1119 1120 if (MHD_INVALID_SOCKET != fd1) 1121 (void) MHD_socket_close_ (fd1); 1122 (void) MHD_socket_close_ (aParam.lstn_sk); 1123 (void) MHD_socket_close_ (fd2); 1124 1125 return ret; 1126 } 1127 1128 1129 #endif /* HAVE_PTHREAD_H */ 1130 1131 1132 int 1133 main (int argc, char *const *argv) 1134 { 1135 unsigned int errorCount = 0; 1136 unsigned int test_result = 0; 1137 int verbose = 0; 1138 1139 if ((NULL == argv) || (0 == argv[0])) 1140 return 99; 1141 oneone = has_in_name (argv[0], "11"); 1142 /* Whether to test MHD daemons without listening socket. */ 1143 no_listen = has_in_name (argv[0], "_nolisten"); 1144 /* Whether to test for correct final cleanup instead of 1145 * of test of normal processing. */ 1146 cleanup_test = has_in_name (argv[0], "_cleanup"); 1147 /* There are almost nothing that could be tested externally 1148 * for final cleanup. Cleanup test actually just tests that 1149 * all added client connections were closed by MHD and 1150 * nothing fails or crashes when final cleanup is performed. 1151 * Mostly useful when configured with '--enable-asserts. */ 1152 slow_reply = cleanup_test; 1153 ignore_response_errors = cleanup_test; 1154 #ifndef HAVE_PTHREAD_H 1155 if (cleanup_test) 1156 return 77; /* Cannot run without threads */ 1157 #endif /* HAVE_PTHREAD_H */ 1158 verbose = ! (has_param (argc, argv, "-q") || 1159 has_param (argc, argv, "--quiet") || 1160 has_param (argc, argv, "-s") || 1161 has_param (argc, argv, "--silent")); 1162 if (cleanup_test) 1163 { 1164 #ifndef _WIN32 1165 /* Find system limit for number of open FDs. */ 1166 #if defined(HAVE_SYSCONF) && defined(_SC_OPEN_MAX) 1167 sys_max_fds = sysconf (_SC_OPEN_MAX) > 500000 ? 1168 500000 : (int) sysconf (_SC_OPEN_MAX); 1169 #else /* ! HAVE_SYSCONF || ! _SC_OPEN_MAX */ 1170 sys_max_fds = -1; 1171 #endif /* ! HAVE_SYSCONF || ! _SC_OPEN_MAX */ 1172 if (0 > sys_max_fds) 1173 { 1174 #if defined(OPEN_MAX) && (0 < ((OPEN_MAX) +1)) 1175 sys_max_fds = OPEN_MAX > 500000 ? 500000 : (int) OPEN_MAX; 1176 #else /* ! OPEN_MAX */ 1177 sys_max_fds = 256; /* Use reasonable value */ 1178 #endif /* ! OPEN_MAX */ 1179 if (2 > CLEANUP_MAX_DAEMONS (sys_max_fds)) 1180 return 77; /* Multithreaded test cannot be run */ 1181 } 1182 #else /* _WIN32 */ 1183 sys_max_fds = 120; /* W32 has problems with ports exhaust */ 1184 #endif /* _WIN32 */ 1185 } 1186 if (0 != curl_global_init (CURL_GLOBAL_WIN32)) 1187 return 99; 1188 /* Could be set to non-zero value to enforce using specific port 1189 * in the test */ 1190 global_port = 0; 1191 if (! cleanup_test) 1192 { 1193 test_result = testExternalGet (); 1194 if (test_result) 1195 fprintf (stderr, "FAILED: testExternalGet () - %u.\n", test_result); 1196 else if (verbose) 1197 printf ("PASSED: testExternalGet ().\n"); 1198 errorCount += test_result; 1199 } 1200 #ifdef HAVE_PTHREAD_H 1201 if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_THREADS)) 1202 { 1203 test_result = testInternalGet (testMhdPollBySelect); 1204 if (test_result) 1205 fprintf (stderr, "FAILED: testInternalGet (testMhdPollBySelect) - %u.\n", 1206 test_result); 1207 else if (verbose) 1208 printf ("PASSED: testInternalGet (testMhdPollBySelect).\n"); 1209 errorCount += test_result; 1210 test_result = testMultithreadedPoolGet (testMhdPollBySelect); 1211 if (test_result) 1212 fprintf (stderr, 1213 "FAILED: testMultithreadedPoolGet (testMhdPollBySelect) - %u.\n", 1214 test_result); 1215 else if (verbose) 1216 printf ("PASSED: testMultithreadedPoolGet (testMhdPollBySelect).\n"); 1217 errorCount += test_result; 1218 if (! cleanup_test) 1219 { 1220 test_result = testMultithreadedGet (testMhdPollBySelect); 1221 if (test_result) 1222 fprintf (stderr, 1223 "FAILED: testMultithreadedGet (testMhdPollBySelect) - %u.\n", 1224 test_result); 1225 else if (verbose) 1226 printf ("PASSED: testMultithreadedGet (testMhdPollBySelect).\n"); 1227 errorCount += test_result; 1228 test_result = testStopRace (testMhdPollBySelect); 1229 if (test_result) 1230 fprintf (stderr, "FAILED: testStopRace (testMhdPollBySelect) - %u.\n", 1231 test_result); 1232 else if (verbose) 1233 printf ("PASSED: testStopRace (testMhdPollBySelect).\n"); 1234 errorCount += test_result; 1235 } 1236 if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_POLL)) 1237 { 1238 test_result = testInternalGet (testMhdPollByPoll); 1239 if (test_result) 1240 fprintf (stderr, "FAILED: testInternalGet (testMhdPollByPoll) - %u.\n", 1241 test_result); 1242 else if (verbose) 1243 printf ("PASSED: testInternalGet (testMhdPollByPoll).\n"); 1244 errorCount += test_result; 1245 test_result = testMultithreadedPoolGet (testMhdPollByPoll); 1246 if (test_result) 1247 fprintf (stderr, 1248 "FAILED: testMultithreadedPoolGet (testMhdPollByPoll) - %u.\n", 1249 test_result); 1250 else if (verbose) 1251 printf ("PASSED: testMultithreadedPoolGet (testMhdPollByPoll).\n"); 1252 errorCount += test_result; 1253 if (! cleanup_test) 1254 { 1255 test_result = testMultithreadedGet (testMhdPollByPoll); 1256 if (test_result) 1257 fprintf (stderr, 1258 "FAILED: testMultithreadedGet (testMhdPollByPoll) - %u.\n", 1259 test_result); 1260 else if (verbose) 1261 printf ("PASSED: testMultithreadedGet (testMhdPollByPoll).\n"); 1262 errorCount += test_result; 1263 test_result = testStopRace (testMhdPollByPoll); 1264 if (test_result) 1265 fprintf (stderr, "FAILED: testStopRace (testMhdPollByPoll) - %u.\n", 1266 test_result); 1267 else if (verbose) 1268 printf ("PASSED: testStopRace (testMhdPollByPoll).\n"); 1269 errorCount += test_result; 1270 } 1271 } 1272 if (MHD_YES == MHD_is_feature_supported (MHD_FEATURE_EPOLL)) 1273 { 1274 test_result = testInternalGet (testMhdPollByEpoll); 1275 if (test_result) 1276 fprintf (stderr, "FAILED: testInternalGet (testMhdPollByEpoll) - %u.\n", 1277 test_result); 1278 else if (verbose) 1279 printf ("PASSED: testInternalGet (testMhdPollByEpoll).\n"); 1280 errorCount += test_result; 1281 test_result = testMultithreadedPoolGet (testMhdPollByEpoll); 1282 if (test_result) 1283 fprintf (stderr, 1284 "FAILED: testMultithreadedPoolGet (testMhdPollByEpoll) - %u.\n", 1285 test_result); 1286 else if (verbose) 1287 printf ("PASSED: testMultithreadedPoolGet (testMhdPollByEpoll).\n"); 1288 errorCount += test_result; 1289 } 1290 } 1291 #endif /* HAVE_PTHREAD_H */ 1292 if (0 != errorCount) 1293 fprintf (stderr, 1294 "Error (code: %u)\n", 1295 errorCount); 1296 else if (verbose) 1297 printf ("All tests passed.\n"); 1298 curl_global_cleanup (); 1299 return (errorCount == 0) ? 0 : 1; /* 0 == pass */ 1300 }