13#include <boost/test/unit_test.hpp>
28 "Connection: close\r\n"
29 "Content-Type: application/json\r\n"
30 "Authorization: Basic X19jb29raWVfXzo5OGQ5ODQ3MWNmNjg0NzAzYTkzN2EzNzk0ZDFlODQ1NjZmYTRkZjJiMzFkYjhhODI4ZGY4MjVjOTg5ZGI4OTVl\r\n"
31 "Content-Length: 46\r\n"
33 R
"({"method":"getblockcount","params":[],"id":1})""\n";
35BOOST_FIXTURE_TEST_SUITE(httpserver_tests, SocketTestingSetup)
37BOOST_AUTO_TEST_CASE(test_query_parameters)
41 // Tolerate a URI with invalid characters (% not followed by hex digits)
42 uri = "/rest/endpoint/someresource.json?p1=v1&p2=v2%";
43 BOOST_CHECK_EQUAL(GetQueryParameterFromUri(uri, "p1"), "v1");
44 BOOST_CHECK_EQUAL(GetQueryParameterFromUri(uri, "p2"), "v2%");
47 uri = "localhost:8080/rest/headers/someresource.json";
48 BOOST_CHECK(!GetQueryParameterFromUri(uri, "p1"));
51 uri = "localhost:8080/rest/endpoint/someresource.json?p1=v1";
52 BOOST_CHECK_EQUAL(GetQueryParameterFromUri(uri, "p1"), "v1");
53 BOOST_CHECK(!GetQueryParameterFromUri(uri, "p2"));
55 // Multiple parameters
56 uri = "/rest/endpoint/someresource.json?p1=v1&p2=v2";
57 BOOST_CHECK_EQUAL(GetQueryParameterFromUri(uri, "p1"), "v1");
58 BOOST_CHECK_EQUAL(GetQueryParameterFromUri(uri, "p2"), "v2");
60 // If the query string contains duplicate keys, the first value is returned
61 uri = "/rest/endpoint/someresource.json?p1=v1&p1=v2";
62 BOOST_CHECK_EQUAL(GetQueryParameterFromUri(uri, "p1"), "v1");
64 // Invalid query string syntax is the same as not having parameters
65 uri = "/rest/endpoint/someresource.json&p1=v1&p2=v2";
66 BOOST_CHECK(!GetQueryParameterFromUri(uri, "p1"));
68 // Multiple parameters, some characters encoded
69 uri = "/rest/endpoint/someresource.json?p1=v1%20&p2=100%25";
70 BOOST_CHECK_EQUAL(GetQueryParameterFromUri(uri, "p1"), "v1 ");
71 BOOST_CHECK_EQUAL(GetQueryParameterFromUri(uri, "p2"), "100%");
73 // Encoded query delimiters are part of the parameter value, not structure.
74 uri = "/rest/endpoint/someresource.json?p=a%26b%3Dc%23frag&other=x";
75 BOOST_CHECK_EQUAL(GetQueryParameterFromUri(uri, "p"), "a&b=c#frag");
76 BOOST_CHECK_EQUAL(GetQueryParameterFromUri(uri, "other"), "x");
78 // An encoded question mark in the path does not introduce a query section.
79 uri = "/rest/endpoint/someresource.json%3Fp1%3Dv1%26p2%3D100%25";
80 BOOST_CHECK(!GetQueryParameterFromUri(uri, "p1"));
83BOOST_AUTO_TEST_CASE(http_headers_tests)
86 // Writing response headers
87 HTTPHeaders headers{};
88 BOOST_CHECK(!headers.FindFirst("Cache-Control"));
89 headers.Write("Cache-Control", "no-cache");
90 // Check case-insensitive key matching
91 BOOST_CHECK_EQUAL(headers.FindFirst("Cache-Control"), "no-cache");
92 BOOST_CHECK_EQUAL(headers.FindFirst("cache-control"), "no-cache");
93 // Additional values are appended, compared case-insensitive
94 headers.Write("cache-control", "max-age=60");
95 BOOST_CHECK_EQUAL(headers.FindFirst("Cache-Control"), "no-cache");
96 BOOST_CHECK((headers.FindAll("Cache-Control") == std::vector<std::string_view>{"no-cache", "max-age=60"}));
98 headers.Write("Pie", "apple");
99 headers.Write("Sandwich", "ham");
100 headers.Write("Coffee", "black");
101 BOOST_CHECK_EQUAL(headers.FindFirst("Pie"), "apple");
103 headers.RemoveAll("Pie");
104 BOOST_CHECK(!headers.FindFirst("Pie"));
105 // Combine for transmission
106 std::string headers_string{headers.Stringify()};
107 BOOST_CHECK_EQUAL(headers_string, "Cache-Control: no-cache\r\n"
108 "cache-control: max-age=60\r\n"
114 // Reading request headers captured from bitcoin-cli
115 constexpr std::string_view bitcoin_cli_headers = "Host: 127.0.0.1\r\n"
116 "Connection: close\r\n"
117 "Content-Type: application/json\r\n"
118 "Authorization: Basic X19jb29raWVfXzozYzJkNTAxNDFlMGJiYmVhMTI5ODg3NzI5MTM3NTRmNThkNjc2OWMwZTYxZjgzNTgyNzEwYTY1OGRkYjVmZGQ3\r\n"
119 "Content-Length: 46\r\n";
120 util::LineReader reader(bitcoin_cli_headers, /*max_line_length=*/MAX_HEADERS_SIZE);
121 HTTPHeaders headers{};
122 headers.Read(reader);
123 BOOST_CHECK_EQUAL(headers.FindFirst("Host"), "127.0.0.1");
124 BOOST_CHECK_EQUAL(headers.FindFirst("Connection"), "close");
125 BOOST_CHECK_EQUAL(headers.FindFirst("Content-Type"), "application/json");
126 BOOST_CHECK_EQUAL(headers.FindFirst("Authorization"), "Basic X19jb29raWVfXzozYzJkNTAxNDFlMGJiYmVhMTI5ODg3NzI5MTM3NTRmNThkNjc2OWMwZTYxZjgzNTgyNzEwYTY1OGRkYjVmZGQ3");
127 BOOST_CHECK_EQUAL(headers.FindFirst("Content-Length"), "46");
128 BOOST_CHECK(!headers.FindFirst("Pizza"));
130 // Ensure invalid headers are rejected
133 util::LineReader reader{"key value\n", /*max_line_length=*/MAX_HEADERS_SIZE};
134 BOOST_CHECK_EXCEPTION(HTTPHeaders{}.Read(reader), std::runtime_error, HasReason{"HTTP header missing colon (:)"});
164 lines.reserve(820 * 10);
165 for (
int i = 0; i < 820; ++i) {
166 lines.append(
"key:value\n");
196 "HTTP/1.1 200 OK\r\n"
197 "Content-Length: 41\r\n"
224 // Malformed: no spaces between data
226 LineReader reader("GET/HTTP/1.0\r\nHost: 127.0.0.1\r\n\r\n", MAX_HEADERS_SIZE);
227 BOOST_CHECK_EXCEPTION(req.LoadControlData(reader), std::runtime_error, HasReason{"HTTP request line too short"});
230 // Malformed: too many spaces
232 LineReader reader("GET / HTTP / 1.0\r\nHost: 127.0.0.1\r\n\r\n", MAX_HEADERS_SIZE);
233 BOOST_CHECK_EXCEPTION(req.LoadControlData(reader), std::runtime_error, HasReason{"HTTP request line malformed"});
236 // Malformed: slash missing before version
238 LineReader reader("GET / HTTP1.0\r\nHost: 127.0.0.1\r\n\r\n", MAX_HEADERS_SIZE);
239 BOOST_CHECK_EXCEPTION(req.LoadControlData(reader), std::runtime_error, HasReason{"HTTP request line too short"});
242 // Malformed: no decimal in version
244 LineReader reader("GET / HTTP/11\r\nHost: 127.0.0.1\r\n\r\n", MAX_HEADERS_SIZE);
245 BOOST_CHECK_EXCEPTION(req.LoadControlData(reader), std::runtime_error, HasReason{"HTTP request line too short"});
248 // Malformed: version is not a number
250 LineReader reader("GET / HTTP/1.x\r\nHost: 127.0.0.1\r\n\r\n", MAX_HEADERS_SIZE);
251 BOOST_CHECK_EXCEPTION(req.LoadControlData(reader), std::runtime_error, HasReason{"HTTP bad version"});
254 // Malformed: version is out of range
256 LineReader reader("GET / HTTP/2.0\r\nHost: 127.0.0.1\r\n\r\n", MAX_HEADERS_SIZE);
257 BOOST_CHECK_EXCEPTION(req.LoadControlData(reader), std::runtime_error, HasReason{"HTTP bad version"});
260 // Malformed: version is out of range
262 LineReader reader("GET / HTTP/0.9\r\nHost: 127.0.0.1\r\n\r\n", MAX_HEADERS_SIZE);
263 BOOST_CHECK_EXCEPTION(req.LoadControlData(reader), std::runtime_error, HasReason{"HTTP bad version"});
266 // Malformed: version is out of range
268 LineReader reader("GET / HTTP/-1.0\r\nHost: 127.0.0.1\r\n\r\n", MAX_HEADERS_SIZE);
269 BOOST_CHECK_EXCEPTION(req.LoadControlData(reader), std::runtime_error, HasReason{"HTTP bad version"});
272 // Malformed: version is not exactly two integers and a dot
274 LineReader reader("GET / HTTP/1.00\r\nHost: 127.0.0.1\r\n\r\n", MAX_HEADERS_SIZE);
275 BOOST_CHECK_EXCEPTION(req.LoadControlData(reader), std::runtime_error, HasReason{"HTTP bad version"});
278 // Malformed: contains NUL
280 LineReader reader{std::string_view{"GET /safe\0/etc/passwd HTTP/1.00\r\nHost: 127.0.0.1\r\n\r\n", 50}, MAX_HEADERS_SIZE};
281 BOOST_CHECK_EXCEPTION(req.LoadControlData(reader), std::runtime_error, HasReason{"Invalid request line contains NUL"});
284 // Malformed: differing Content-Length values, case insensitive
285 constexpr std::string_view differing_length = "GET / HTTP/1.1\n"
287 "Content-Length: 8\n"
288 "content-length: 9\n\n"
291 util::LineReader reader{differing_length, /*max_line_length=*/MAX_HEADERS_SIZE};
292 BOOST_CHECK(req.LoadControlData(reader));
293 BOOST_CHECK(req.LoadHeaders(reader));
294 BOOST_CHECK_EXCEPTION(req.LoadBody(reader), std::runtime_error, HasReason{"Differing Content-Length values"});
297 // Ok: multiple same Content-Length values
298 constexpr std::string_view differing_length = "GET / HTTP/1.1\n"
300 "Content-Length: 8\n"
301 "content-length: 8\n\n"
304 util::LineReader reader{differing_length, /*max_line_length=*/MAX_HEADERS_SIZE};
305 BOOST_CHECK(req.LoadControlData(reader));
306 BOOST_CHECK(req.LoadHeaders(reader));
307 BOOST_CHECK(req.LoadBody(reader));
312 LineReader reader("GET / HTTP/1.0\r\nHost: 127.0.0.1\r\n\r\n", MAX_HEADERS_SIZE);
313 BOOST_CHECK(req.LoadControlData(reader));
314 BOOST_CHECK(req.LoadHeaders(reader));
315 BOOST_CHECK(req.LoadBody(reader));
316 BOOST_CHECK_EQUAL(req.m_method, HTTPRequestMethod::GET);
317 BOOST_CHECK_EQUAL(req.m_target, "/");
318 BOOST_CHECK_EQUAL(req.m_version.major, 1);
319 BOOST_CHECK_EQUAL(req.m_version.minor, 0);
320 BOOST_CHECK_EQUAL(req.m_headers.FindFirst("Host"), "127.0.0.1");
322 BOOST_CHECK_EQUAL(req.m_body.size(), 0);
325 // Malformed: missing colon
327 LineReader reader("GET / HTTP/1.0\r\nHost=127.0.0.1\r\n\r\n", MAX_HEADERS_SIZE);
328 BOOST_CHECK(req.LoadControlData(reader));
329 BOOST_CHECK_EXCEPTION(req.LoadHeaders(reader), std::runtime_error, HasReason{"HTTP header missing colon (:)"});
369 std::string huge_body(excessive_size,
'x');
370 const std::string request{
"GET / HTTP/1.0\r\nContent-Length: " +
util::ToString(excessive_size) +
"\r\n\r\n" + std::move(huge_body)};
380 const std::string request{
"GET / HTTP/1.0\r\nContent-Length: " +
util::ToString(
MAX_BODY_SIZE) +
"\r\n\r\n" + std::move(max_body)};
399 std::string_view ok_chunked =
"GET / HTTP/1.0\n"
400 "Transfer-Encoding: chunked\n"
403 R
"({"method":"getbl)""\n"
408 LineReader reader(ok_chunked, MAX_HEADERS_SIZE);
409 BOOST_CHECK(req.LoadControlData(reader));
410 BOOST_CHECK(req.LoadHeaders(reader));
411 BOOST_CHECK(req.LoadBody(reader));
412 BOOST_CHECK_EQUAL(req.m_body, R"({"method":"getblockcount"})");
417 std::string_view excessive_chunk_size =
"GET / HTTP/1.0\n"
418 "Transfer-Encoding: chunked\n"
421 R
"({"method":"getbl)""\n"
426 LineReader reader(excessive_chunk_size, MAX_HEADERS_SIZE);
427 BOOST_CHECK(req.LoadControlData(reader));
428 BOOST_CHECK(req.LoadHeaders(reader));
429 BOOST_CHECK_EXCEPTION(req.LoadBody(reader), http_bitcoin::ContentTooLargeError, HasReason{"Chunk will exceed max body size"});
432 // Allow (but ignore) Chunk Extensions
434 std::string_view ok_chunked = "GET / HTTP/1.0\n"
435 "Transfer-Encoding: chunked\n"
437 "10;sha256=715790e8a3b09d704ac9641f42d183a5ebc5fd939663de23da548519ac2165e5\n"
438 R"({"method":"getbl)""\n"
441 "0;why;would;anyone;do;this;\n"
442 "Expires: Wed, 21 Oct 2026 07:28:00 GMT\n"
444 LineReader reader(ok_chunked, MAX_HEADERS_SIZE);
445 BOOST_CHECK(req.LoadControlData(reader));
446 BOOST_CHECK(req.LoadHeaders(reader));
447 BOOST_CHECK(req.LoadBody(reader));
448 BOOST_CHECK_EQUAL(req.m_body, R"({"method":"getblockcount"})");
456 std::string_view invalid_chunked =
"GET / HTTP/1.0\n"
457 "Transfer-Encoding: chunked\n"
460 R
"({"method":"getbl)""\n"
465 LineReader reader(invalid_chunked, MAX_HEADERS_SIZE);
466 BOOST_CHECK(req.LoadControlData(reader));
467 BOOST_CHECK(req.LoadHeaders(reader));
468 BOOST_CHECK_EXCEPTION(req.LoadBody(reader), std::runtime_error, HasReason{"Cannot parse chunk length value"});
471 // Invalid "chunked" transfer, missing chunk termination \n
473 std::string_view invalid_chunked = "GET / HTTP/1.0\n"
474 "Transfer-Encoding: chunked\n"
477 R"({"method":"getbl)"
497 void receive(std::string_view
s)
499 m_recv_buffer.insert(
508 std::shared_ptr<DummyClient>
client{std::make_shared<DummyClient>()};
512 client->receive(
"POST / HTTP/1.0\n");
516 client->receive(
"Host: 127.0.0.1\n"
517 "Content-Length: 10\n\n");
521 client->receive(
"I miss you\n");
527 std::shared_ptr<DummyClient>
client{std::make_shared<DummyClient>()};
531 client->receive(
"POST / HTTP/1.0\n"
533 "Content-Length: 10\n\n"
541 "GET /endpoint HTTP/1.0\n\n");
567 std::shared_ptr<DummyClient>
client{std::make_shared<DummyClient>()};
571 client->receive(
"POST / HTTP/1.0\n"
572 "Content-Length: 30000\n\n");
578 for (
int i = 1; i <= 3; ++i) {
579 client->receive(std::string(10000,
'x'));
589 std::shared_ptr<DummyClient>
client{std::make_shared<DummyClient>()};
593 client->receive(
"POST / HTTP/1.0\n"
594 "Content-Length: 4\n\n"
596 "GET /next HTTP/1.0\n\n");
605 std::shared_ptr<DummyClient>
client{std::make_shared<DummyClient>()};
614 client->receive(
"GET / HTTP/1.0\n"
615 "Transfer-Encoding: chunked\n"
627 client->receive(R
"(":"getbl)""\n");
628 client->ReadRequest(*client->m_req);
630 BOOST_CHECK(!client->m_req->m_chunk_size);
631 BOOST_CHECK_EQUAL(client->m_req->m_chunk_read, 0);
632 // New data is added to body but body is still incomplete
633 BOOST_CHECK_EQUAL(client->m_req->m_body.size(), 16);
634 BOOST_CHECK_EQUAL(client->m_req->GetState(), HTTPRequest::State::NeedsBody);
636 // Next chunk arrives without terminal CRLF
637 client->receive("a\n"
647 client->receive(
"\n0\n\n");
657 std::shared_ptr<DummyClient>
client{std::make_shared<DummyClient>()};
661 client->receive(
"POST / HTTP/1.0\n"
663 "Invalid header with no colon\n"
671 HasReason{
"HTTP header missing colon (:)"});
680 client->receive(
"Content-Length: 2\n\nok");
687 std::shared_ptr<DummyClient>
client{std::make_shared<DummyClient>()};
692 client->receive(
"POST /huge HTTP/1.0\n");
696 for (
int i = 0; i < 410; ++i) {
697 client->receive(
"key:value\n");
702 for (
int i = 0; i < 409; ++i) {
703 client->receive(
"key:value\n");
713 HasReason{
"HTTP headers exceed size limit"});
718 std::shared_ptr<DummyClient>
client{std::make_shared<DummyClient>()};
723 client->receive(
"POST /huge HTTP/1.0\n");
727 client->receive(
"Transfer-Encoding: chunked\n\n");
732 client->receive(
"10\nno auto updates!\n");
739 client->receive(
"1fffff1\n");
742 HasReason{
"Chunk will exceed max body size"});
747 std::shared_ptr<DummyClient>
client{std::make_shared<DummyClient>()};
752 "Transfer-Encoding: chunked\n"
757 "Digest: sha-4=deadbeef\n");
762 client->receive(
"Expires:");
767 client->receive(
"never\n");
779 std::shared_ptr<DummyClient>
client{std::make_shared<DummyClient>()};
782 client->receive(
"POST /huge HTTP/1.0\n"
783 "Transfer-Encoding: chunked\n");
784 for (
int i = 0; i < 816; ++i) {
785 client->receive(
"key:value\n");
796 client->receive(
"k:vv\n");
799 HasReason{
"HTTP headers exceed size limit"});
812 Mutex requests_mutex;
813 std::deque<std::unique_ptr<HTTPRequest>> requests;
814 auto StoreRequest = [&](std::unique_ptr<HTTPRequest>&& req) {
815 LOCK(requests_mutex);
816 requests.push_back(std::move(req));
824 CService onion_address{
Lookup(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaam2dqd.onion", 0,
false).value()};
825 auto result{server.BindAndStartListening(onion_address)};
826 BOOST_REQUIRE(!result);
827 BOOST_CHECK_EQUAL(result.error(),
"Bind address family for aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaam2dqd.onion:0 not supported");
834 BOOST_REQUIRE_EQUAL(server.GetListeningSocketCount(), 0);
836 BOOST_REQUIRE(server.BindAndStartListening(addr_bind));
838 BOOST_REQUIRE_EQUAL(server.GetListeningSocketCount(), 1);
841 server.StartSocketsThreads();
849 std::shared_ptr<DynSock::Pipes> mock_client_socket_pipes{ConnectClient(std::as_bytes(std::span(
full_request)))};
853 while (server.GetConnectionsCount() < 1) {
854 std::this_thread::sleep_for(10ms);
855 BOOST_REQUIRE(--attempts > 0);
859 std::shared_ptr<HTTPRemoteClient>
client;
867 LOCK(requests_mutex);
869 if (requests.size() == 1) {
871 BOOST_CHECK_EQUAL(requests.front()->m_body, R
"({"method":"getblockcount","params":[],"id":1})""\n");
872 BOOST_CHECK_EQUAL(requests.front()->GetPeer().ToStringAddrPort(), "5.5.5.5:6789");
874 // Inspect the connection pointed to from the request
875 client = requests.front()->m_client.lock();
876 BOOST_REQUIRE(client);
877 BOOST_CHECK_EQUAL(client->m_origin, "5.5.5.5:6789");
879 // Respond to request
880 requests.front()->WriteReply(HTTP_OK, "874140\n");
885 std::this_thread::sleep_for(10ms);
886 BOOST_REQUIRE(--attempts > 0);
889 // Check the sent response from the mock client at the other end of the mock socket
891 // Wait up to one minute for all the bytes to appear in the "send" pipe.
892 char buf[0x10000] = {};
896 ssize_t bytes_read = mock_client_socket_pipes->send.GetBytes(buf, sizeof(buf), 0);
897 if (bytes_read > 0) {
898 actual.append(buf, bytes_read);
899 if (actual.length() == 146) {
903 std::this_thread::sleep_for(10ms);
906 BOOST_CHECK(actual.starts_with("HTTP/1.1 200 OK\r\n"));
907 BOOST_CHECK(actual.ends_with("\r\n874140\n"));
908 // Headers can be sorted in any order, and will be, since we use unordered_map
909 BOOST_CHECK(actual.find("Connection: close\r\n") != std::string::npos);
910 BOOST_CHECK(actual.find("Content-Length: 7\r\n") != std::string::npos);
911 BOOST_CHECK(actual.find("Content-Type: text/html; charset=ISO-8859-1\r\n") != std::string::npos);
912 BOOST_CHECK(actual.find("Date: Wed, 11 Dec 2024 00:47:09 GMT\r\n") != std::string::npos);
914 // Wait up to one minute for connection to be automatically closed, because
915 // keep-alive was not set by the client and we are done responding to their request.
917 while (server.GetConnectionsCount() != 0) {
918 std::this_thread::sleep_for(10ms);
919 BOOST_REQUIRE(--attempts > 0);
922 // Stop the I/O loop and shutdown
923 server.InterruptNet();
924 // Wait for I/O loop to finish, after all connected sockets are closed
925 server.JoinSocketsThreads();
926 // Close all listening sockets
927 server.StopListening();
930BOOST_AUTO_TEST_CASE(http_socket_error_tests)
932 // Create a tiny threadpool for the HTTPRequest handler
933 ThreadPool workers("http");
936 // Hard-code the server's request handler to respond to each request with
937 // an incremented block count. Handle the replies in the worker thread.
938 std::atomic<int> height{0};
939 HTTPServer server{[&](std::shared_ptr<HTTPRequest> req) {
940 auto item = [req, &height]() {
941 const int h = height.fetch_add(1);
942 req->WriteReply(HTTP_OK, strprintf("height: %d\n", h));
944 // Can't call BOOST_REQUIRE from worker thread
945 Assert(workers.Submit(std::move(item)));
947 server.InitHTTPAllowList();
949 // All replies will be the same size
950 static constexpr std::size_t reply_length = std::string_view{
951 "HTTP/1.1 200 OK\r\n"
952 "Date: Thu, 01 Jan 2026 00:00:00 GMT\r\n" // All RFC1123 dates are 29 characters
953 "Content-Length: 10\r\n"
954 "Content-Type: text/html; charset=ISO-8859-1\r\n"
968 class ErrorSock : public DynSock
971 explicit ErrorSock(std::shared_ptr<Pipes> pipes) : DynSock{std::move(pipes)} {}
972 DynSock& operator=(Sock&&) override { assert(false); return *this; }
974 ssize_t Send(const void* buf, size_t len, int flags) const override
976 if (len <= reply_length && !m_have_sent) {
978 WSASetLastError(WSAEWOULDBLOCK);
985 return DynSock::Send(buf, len, flags);
989 mutable bool m_have_sent{false};
992 // Simpler server startup than the last test
993 CService addr_bind{Lookup("0.0.0.0", /*portDefault=*/0, /*fAllowLookup=*/false).value()};
994 BOOST_REQUIRE(server.BindAndStartListening(addr_bind));
995 server.StartSocketsThreads();
997 // Prepare initial requests
998 int num_requests = 2;
999 // Use keep-alive so the server holds the connection open for all requests.
1000 std::string keepalive_request{full_request};
1001 keepalive_request.replace(keepalive_request.find("Connection: close"), 17, "Connection: keep-alive");
1002 // Combine all requests so they are read from the socket on a single iteration of the I/O loop
1003 std::string all_requests;
1004 for (int i = 0; i < num_requests; i++) {
1005 all_requests += keepalive_request;
1008 // Watch the log messages to ensure that the first two replies were sent
1009 // together. This indicates the non-optimistic send path was used
1010 // because a reply was already sitting in the send buffer when a second reply
1012 DebugLogHelper find_two_replies{strprintf("Sent %d bytes to client", reply_length * 2),
1013 [&](const std::string* s) {
1016 // Last reply should be sent on its own by optimistic send path, because
1017 // the send buffer was empty when the reply was written.
1018 DebugLogHelper find_one_reply{strprintf("Sent %d bytes to client", reply_length),
1019 [&](const std::string* s) {
1023 // Connect the ErrorSock as mock client with the preloaded data and get a handle on the I/O pipes
1024 std::shared_ptr<ErrorSock::Pipes> mock_client_socket_pipes{
1025 ConnectClient<ErrorSock>(std::as_bytes(std::span(all_requests)))
1028 // Wait up to one minute for the last reply from the server
1030 char buf[0x10000] = {};
1031 int attempts = 6000;
1032 while (attempts > 0)
1034 ssize_t bytes_read = mock_client_socket_pipes->send.GetBytes(buf, sizeof(buf), 0);
1035 if (bytes_read > 0) {
1036 actual.append(buf, bytes_read);
1037 if (actual.find(strprintf("height: %d", num_requests - 1)) != std::string::npos) {
1041 std::this_thread::sleep_for(10ms);
1045 // Send the third request.
1046 // If there was a race between WriteReply() in the worker thread setting m_send_ready=true
1047 // and SocketHandlerConnected() in the I/O thread flushing the send buffer,
1048 // then the socket would be stuck in write mode with nothing to write,
1049 // the server would never read from the socket, and this request would time out.
1050 // Wait a second to ensure both the worker thread and I/O thread are idle.
1051 // If we send the next request too soon it might get accepted by the server before
1052 // it gets wedged shut.
1053 std::this_thread::sleep_for(1000ms);
1054 mock_client_socket_pipes->recv.PushBytes(keepalive_request.data(), keepalive_request.size());
1057 // Wait up to one minute for reply
1059 while (attempts > 0)
1061 ssize_t bytes_read = mock_client_socket_pipes->send.GetBytes(buf, sizeof(buf), 0);
1062 if (bytes_read > 0) {
1063 actual.append(buf, bytes_read);
1064 if (actual.find(strprintf("height: %d", num_requests - 1)) != std::string::npos) {
1068 std::this_thread::sleep_for(10ms);
1072 // All replies were received
1073 for (int i = 0; i < num_requests; i++) {
1074 BOOST_REQUIRE(actual.find(strprintf("height: %d", i)) != std::string::npos);
1077 // Close the keep-alive connection
1078 server.DisconnectAllClients();
1082 server.InterruptNet();
1083 server.JoinSocketsThreads();
1084 server.StopListening();
1087BOOST_AUTO_TEST_CASE(http_server_rejects_disallowed_client_before_read)
1089 // DynSock reports accepted connections as coming from 5.5.5.5.
1090 gArgs.ForceSetArg("-rpcallowip", "4.4.4.4");
1092 std::atomic_bool request_dispatched{false};
1093 HTTPServer server{[&request_dispatched](std::unique_ptr<HTTPRequest>&&) {
1094 request_dispatched = true;
1096 BOOST_REQUIRE(server.InitHTTPAllowList());
1098 CService addr_bind{Lookup("0.0.0.0", /*portDefault=*/0, /*fAllowLookup=*/false).value()};
1099 BOOST_REQUIRE(server.BindAndStartListening(addr_bind));
1100 server.StartSocketsThreads();
1102 // Queue a complete request; the server should never read from it.
1103 std::shared_ptr<DynSock::Pipes> client_pipes{
1104 ConnectClient(std::as_bytes(std::span(full_request)))};
1106 // Wait for the socket to close with an EOF (bytes_read == 0)
1107 // 'bytes_read > 0' means the server replied to the prohibited client
1108 // 'bytes_read < 0' is an error, expected until the connection is fully processed by the I/O loop
1109 ssize_t bytes_read{};
1110 char buf[0x10000]{};
1111 for (int attempts{0}; attempts != 1'000; ++attempts) {
1112 bytes_read = client_pipes->send.GetBytes(&buf, sizeof(buf), MSG_PEEK);
1113 if (bytes_read >= 0) break;
1114 std::this_thread::sleep_for(10ms);
1117 BOOST_CHECK_EQUAL(bytes_read, 0);
1118 BOOST_CHECK(!request_dispatched);
1119 BOOST_CHECK_EQUAL(server.GetConnectionsCount(), 0);
1121 server.InterruptNet();
1122 server.JoinSocketsThreads();
1123 server.StopListening();
1125 // 'recv' buffer still holds the client's request untouched which
1126 // proves the server never called Recv()
1127 const ssize_t recv_bytes{client_pipes->recv.GetBytes(&buf, sizeof(buf))};
1128 BOOST_REQUIRE_EQUAL(recv_bytes, static_cast<ssize_t>(full_request.size()));
1129 BOOST_CHECK_EQUAL(std::string_view(buf, recv_bytes), full_request);
1132BOOST_AUTO_TEST_SUITE_END()
A combination of a network address (CNetAddr) and a (TCP) port.
Helper to initialize the global NodeClock, let a duration elapse, and reset it after use in a test.
BOOST_CHECK_EXCEPTION predicates to check the specific validation error.
std::string GetURI() const
HTTPRequestMethod m_method
bool LoadHeaders(LineReader &reader)
std::pair< bool, std::string > GetHeader(std::string_view hdr) const
bool LoadControlData(LineReader &reader)
Methods that attempt to parse HTTP request fields line-by-line from a receive buffer.
HTTPRequestMethod GetRequestMethod() const
bool LoadBody(LineReader &reader)
std::string StringifyHeaders() const
bool InitHTTPAllowList()
Parse the user's -rpcallowip settings and populate m_allow_subnets.
size_t Remaining() const
Returns remaining size of bytes in buffer.
BOOST_AUTO_TEST_CASE(http_response_tests)
std::string_view excessive_headers
BOOST_CHECK_GT(excessive_headers.size(), MAX_HEADERS_SIZE)
BOOST_CHECK_EQUAL(headers.FindFirst("key"), "value")
BOOST_CHECK_EXCEPTION(HTTPHeaders{}.Read(reader), std::runtime_error, HasReason{"Empty HTTP header name"})
constexpr std::string_view full_request
std::unique_ptr< ProxyClient< messages::FooInterface > > client
std::optional< std::string > GetQueryParameterFromUri(const std::string_view uri, const std::string_view key)
constexpr uint64_t MAX_BODY_SIZE
Maximum size of an HTTP request body.
constexpr size_t MAX_HEADERS_SIZE
Maximum size of each headers line in an HTTP request, also the maximum size of all headers total.
std::string ToString(const T &t)
Locale-independent version of std::to_string.
std::vector< CService > Lookup(const std::string &name, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
Resolve a service string to its corresponding service.
std::function< std::unique_ptr< Sock >(int, int, int)> CreateSock
Socket factory.
#define BOOST_CHECK(expr)
Thrown when a request body exceeds MAX_BODY_SIZE (or will exceed, in chunked transfer) so the server ...
uint8_t major
Default HTTP protocol version 1.1 is used by error responses when a request is unreadable.