Branch data Line data Source code
1 : : // Copyright (c) 2012-present The Bitcoin Core developers
2 : : // Distributed under the MIT software license, see the accompanying
3 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 : :
5 : : #include <httpserver.h>
6 : : #include <rpc/protocol.h>
7 : : #include <test/util/common.h>
8 : : #include <test/util/logging.h>
9 : : #include <test/util/net.h>
10 : : #include <test/util/setup_common.h>
11 : : #include <util/check.h>
12 : : #include <util/overflow.h>
13 : : #include <util/string.h>
14 : : #include <util/threadpool.h>
15 : :
16 : : #include <boost/test/unit_test.hpp>
17 : :
18 : : #include <memory>
19 : :
20 : : using util::LineReader;
21 : : using namespace bitcoin_http;
22 : :
23 : : // HTTP request captured from bitcoin-cli
24 : : constexpr std::string_view full_request = "POST / HTTP/1.1\r\n"
25 : : "Host: 127.0.0.1\r\n"
26 : : "Connection: close\r\n"
27 : : "Content-Type: application/json\r\n"
28 : : "Authorization: Basic X19jb29raWVfXzo5OGQ5ODQ3MWNmNjg0NzAzYTkzN2EzNzk0ZDFlODQ1NjZmYTRkZjJiMzFkYjhhODI4ZGY4MjVjOTg5ZGI4OTVl\r\n"
29 : : "Content-Length: 46\r\n"
30 : : "\r\n"
31 : : R"({"method":"getblockcount","params":[],"id":1})""\n";
32 : :
33 : : BOOST_FIXTURE_TEST_SUITE(httpserver_tests, SocketTestingSetup)
34 : :
35 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(test_query_parameters)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
36 : : {
37 [ + - ]: 1 : std::string uri {};
38 : :
39 : : // Tolerate a URI with invalid characters (% not followed by hex digits)
40 [ + - ]: 1 : uri = "/rest/endpoint/someresource.json?p1=v1&p2=v2%";
41 [ + - - + : 1 : BOOST_CHECK_EQUAL(GetQueryParameterFromUri(uri, "p1"), "v1");
+ - + - ]
42 [ + - - + : 1 : BOOST_CHECK_EQUAL(GetQueryParameterFromUri(uri, "p2"), "v2%");
+ - + - ]
43 : :
44 : : // No parameters
45 [ + - ]: 1 : uri = "localhost:8080/rest/headers/someresource.json";
46 [ + - - + : 2 : BOOST_CHECK(!GetQueryParameterFromUri(uri, "p1"));
+ - + - +
- ]
47 : :
48 : : // Single parameter
49 [ + - ]: 1 : uri = "localhost:8080/rest/endpoint/someresource.json?p1=v1";
50 [ + - - + : 1 : BOOST_CHECK_EQUAL(GetQueryParameterFromUri(uri, "p1"), "v1");
+ - + - ]
51 [ + - - + : 2 : BOOST_CHECK(!GetQueryParameterFromUri(uri, "p2"));
+ - + - +
- ]
52 : :
53 : : // Multiple parameters
54 [ + - ]: 1 : uri = "/rest/endpoint/someresource.json?p1=v1&p2=v2";
55 [ + - - + : 1 : BOOST_CHECK_EQUAL(GetQueryParameterFromUri(uri, "p1"), "v1");
+ - + - ]
56 [ + - - + : 1 : BOOST_CHECK_EQUAL(GetQueryParameterFromUri(uri, "p2"), "v2");
+ - + - ]
57 : :
58 : : // If the query string contains duplicate keys, the first value is returned
59 [ + - ]: 1 : uri = "/rest/endpoint/someresource.json?p1=v1&p1=v2";
60 [ + - - + : 1 : BOOST_CHECK_EQUAL(GetQueryParameterFromUri(uri, "p1"), "v1");
+ - + - ]
61 : :
62 : : // Invalid query string syntax is the same as not having parameters
63 [ + - ]: 1 : uri = "/rest/endpoint/someresource.json&p1=v1&p2=v2";
64 [ + - - + : 2 : BOOST_CHECK(!GetQueryParameterFromUri(uri, "p1"));
+ - + - +
- ]
65 : :
66 : : // Multiple parameters, some characters encoded
67 [ + - ]: 1 : uri = "/rest/endpoint/someresource.json?p1=v1%20&p2=100%25";
68 [ + - - + : 1 : BOOST_CHECK_EQUAL(GetQueryParameterFromUri(uri, "p1"), "v1 ");
+ - + - ]
69 [ + - - + : 1 : BOOST_CHECK_EQUAL(GetQueryParameterFromUri(uri, "p2"), "100%");
+ - + - ]
70 : :
71 : : // Encoded query delimiters are part of the parameter value, not structure.
72 [ + - ]: 1 : uri = "/rest/endpoint/someresource.json?p=a%26b%3Dc%23frag&other=x";
73 [ + - - + : 1 : BOOST_CHECK_EQUAL(GetQueryParameterFromUri(uri, "p"), "a&b=c#frag");
+ - + - ]
74 [ + - - + : 1 : BOOST_CHECK_EQUAL(GetQueryParameterFromUri(uri, "other"), "x");
+ - + - ]
75 : :
76 : : // An encoded question mark in the path does not introduce a query section.
77 [ + - ]: 1 : uri = "/rest/endpoint/someresource.json%3Fp1%3Dv1%26p2%3D100%25";
78 [ + - - + : 2 : BOOST_CHECK(!GetQueryParameterFromUri(uri, "p1"));
+ - + - ]
79 : 1 : }
80 : :
81 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(http_headers_tests)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
82 : : {
83 : 1 : {
84 : : // Writing response headers
85 : 1 : HTTPHeaders headers{};
86 [ + - + - : 2 : BOOST_CHECK(!headers.FindFirst("Cache-Control"));
+ - + - ]
87 [ + - + - : 2 : headers.Write("Cache-Control", "no-cache");
+ - ]
88 : : // Check case-insensitive key matching
89 [ + - + - : 1 : BOOST_CHECK_EQUAL(headers.FindFirst("Cache-Control"), "no-cache");
+ - ]
90 [ + - + - : 1 : BOOST_CHECK_EQUAL(headers.FindFirst("cache-control"), "no-cache");
+ - ]
91 : : // Additional values are appended, compared case-insensitive
92 [ + - + - : 2 : headers.Write("cache-control", "max-age=60");
+ - ]
93 [ + - + - : 1 : BOOST_CHECK_EQUAL(headers.FindFirst("Cache-Control"), "no-cache");
+ - ]
94 [ + - + - : 2 : BOOST_CHECK((headers.FindAll("Cache-Control") == std::vector<std::string_view>{"no-cache", "max-age=60"}));
+ - + - +
- ]
95 : : // Add a few more
96 [ + - + - : 2 : headers.Write("Pie", "apple");
+ - ]
97 [ + - + - : 2 : headers.Write("Sandwich", "ham");
+ - ]
98 [ + - + - : 2 : headers.Write("Coffee", "black");
+ - ]
99 [ + - + - : 1 : BOOST_CHECK_EQUAL(headers.FindFirst("Pie"), "apple");
+ - ]
100 : : // Remove
101 [ + - ]: 1 : headers.RemoveAll("Pie");
102 [ + - + - : 2 : BOOST_CHECK(!headers.FindFirst("Pie"));
+ - + - ]
103 : : // Combine for transmission
104 [ + - ]: 1 : std::string headers_string{headers.Stringify()};
105 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(headers_string, "Cache-Control: no-cache\r\n"
106 : : "cache-control: max-age=60\r\n"
107 : : "Sandwich: ham\r\n"
108 : : "Coffee: black\r\n"
109 : : "\r\n");
110 : 1 : }
111 : 1 : {
112 : : // Reading request headers captured from bitcoin-cli
113 : 1 : constexpr std::string_view bitcoin_cli_headers = "Host: 127.0.0.1\r\n"
114 : : "Connection: close\r\n"
115 : : "Content-Type: application/json\r\n"
116 : : "Authorization: Basic X19jb29raWVfXzozYzJkNTAxNDFlMGJiYmVhMTI5ODg3NzI5MTM3NTRmNThkNjc2OWMwZTYxZjgzNTgyNzEwYTY1OGRkYjVmZGQ3\r\n"
117 : : "Content-Length: 46\r\n";
118 : 1 : util::LineReader reader(bitcoin_cli_headers, /*max_line_length=*/MAX_HEADERS_SIZE);
119 : 1 : HTTPHeaders headers{};
120 [ + - ]: 1 : headers.Read(reader);
121 [ + - + - : 1 : BOOST_CHECK_EQUAL(headers.FindFirst("Host"), "127.0.0.1");
+ - ]
122 [ + - + - : 1 : BOOST_CHECK_EQUAL(headers.FindFirst("Connection"), "close");
+ - ]
123 [ + - + - : 1 : BOOST_CHECK_EQUAL(headers.FindFirst("Content-Type"), "application/json");
+ - ]
124 [ + - + - : 1 : BOOST_CHECK_EQUAL(headers.FindFirst("Authorization"), "Basic X19jb29raWVfXzozYzJkNTAxNDFlMGJiYmVhMTI5ODg3NzI5MTM3NTRmNThkNjc2OWMwZTYxZjgzNTgyNzEwYTY1OGRkYjVmZGQ3");
+ - ]
125 [ + - + - : 1 : BOOST_CHECK_EQUAL(headers.FindFirst("Content-Length"), "46");
+ - ]
126 [ + - + - : 2 : BOOST_CHECK(!headers.FindFirst("Pizza"));
+ - ]
127 : 0 : }
128 : : // Ensure invalid headers are rejected
129 : 1 : {
130 : : // missing a colon
131 : 1 : util::LineReader reader{"key value\n", /*max_line_length=*/MAX_HEADERS_SIZE};
132 [ + - - + : 3 : BOOST_CHECK_EXCEPTION(HTTPHeaders{}.Read(reader), std::runtime_error, HasReason{"HTTP header missing colon (:)"});
- - - - -
+ + - + -
+ - ]
133 : : }
134 : 1 : {
135 : : // missing a key
136 : 1 : util::LineReader reader{":value\n", /*max_line_length=*/MAX_HEADERS_SIZE};
137 [ + - - + : 3 : BOOST_CHECK_EXCEPTION(HTTPHeaders{}.Read(reader), std::runtime_error, HasReason{"Empty HTTP header name"});
- - - - -
+ + - + -
+ - ]
138 : : }
139 : 1 : {
140 : : // contains NUL
141 : 1 : util::LineReader reader{std::string_view{"X-Custom: foo\0bar\n", 18}, /*max_line_length=*/MAX_HEADERS_SIZE};
142 [ + - - + : 3 : BOOST_CHECK_EXCEPTION(HTTPHeaders{}.Read(reader), std::runtime_error, HasReason{"Header contains invalid character"});
- - - - -
+ + - + -
+ - ]
143 : : }
144 : 1 : {
145 : : // contains bare \r (not followed by \n)
146 : 1 : util::LineReader reader{std::string_view{"X-Custom: foo\rbar\n"}, /*max_line_length=*/MAX_HEADERS_SIZE};
147 [ + - - + : 3 : BOOST_CHECK_EXCEPTION(HTTPHeaders{}.Read(reader), std::runtime_error, HasReason{"Header contains invalid character"});
- - - - -
+ + - + -
+ - ]
148 : : }
149 : 1 : {
150 : : // contains odd \r preceding the expected CRLF
151 : 1 : util::LineReader reader{"X-Custom: foo\r\r\n", /*max_line_length=*/MAX_HEADERS_SIZE};
152 [ + - - + : 3 : BOOST_CHECK_EXCEPTION(HTTPHeaders{}.Read(reader), std::runtime_error, HasReason{"Header contains invalid character"});
- - - - -
+ + - + -
+ - ]
153 : : }
154 : 1 : {
155 : : // key contains whitespace
156 : 1 : util::LineReader reader{"key : value\n", /*max_line_length=*/MAX_HEADERS_SIZE};
157 [ + - - + : 3 : BOOST_CHECK_EXCEPTION(HTTPHeaders{}.Read(reader), std::runtime_error, HasReason{"Invalid header field-name contains whitespace"});
- - - - -
+ + - + -
+ - ]
158 : : }
159 : 1 : {
160 : : // Individual lines are below MAX_HEADERS_SIZE but the total is excessive
161 [ + - ]: 1 : std::string lines;
162 [ + - ]: 1 : lines.reserve(820 * 10);
163 [ + + ]: 821 : for (int i = 0; i < 820; ++i) {
164 [ + - ]: 820 : lines.append("key:value\n");
165 : : }
166 [ - + ]: 1 : std::string_view excessive_headers{lines};
167 [ + - + - ]: 1 : BOOST_CHECK_GT(excessive_headers.size(), MAX_HEADERS_SIZE);
168 [ + - ]: 1 : util::LineReader reader{excessive_headers, /*max_line_length=*/MAX_HEADERS_SIZE};
169 [ + - - + : 3 : BOOST_CHECK_EXCEPTION(HTTPHeaders{}.Read(reader), std::runtime_error, HasReason{"HTTP headers exceed size limit"});
- - - - -
+ + - + -
+ - ]
170 : 0 : }
171 : 1 : {
172 : : // Ok
173 : 1 : util::LineReader reader{"key: value\n", /*max_line_length=*/MAX_HEADERS_SIZE};
174 : 1 : HTTPHeaders headers{};
175 [ + - ]: 1 : headers.Read(reader);
176 [ + - + - : 1 : BOOST_CHECK_EQUAL(headers.FindFirst("key"), "value");
+ - ]
177 : 1 : }
178 : 1 : }
179 : :
180 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(http_response_tests)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
181 : : {
182 : : // Typical HTTP 1.1 response headers
183 : 1 : HTTPHeaders headers{};
184 [ + - + - : 2 : headers.Write("Content-Length", "41");
+ - ]
185 : :
186 : : // Response points to headers which already exist because some of them
187 : : // are set before we even know what the response will be.
188 : 1 : HTTPResponse res;
189 : 1 : res.version = {.major = 1, .minor = 1};
190 : 1 : res.status = HTTP_OK;
191 : 1 : res.headers = std::move(headers);
192 [ + - + - : 1 : BOOST_CHECK_EQUAL(
+ - ]
193 : : res.StringifyHeaders(),
194 : : "HTTP/1.1 200 OK\r\n"
195 : : "Content-Length: 41\r\n"
196 : : "\r\n");
197 : 1 : }
198 : :
199 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(http_request_tests)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
200 : : {
201 : 1 : {
202 : 1 : HTTPRequest req;
203 [ + - ]: 1 : LineReader reader(full_request, MAX_HEADERS_SIZE);
204 [ + - + - : 1 : BOOST_CHECK_EQUAL(req.Load(reader), HTTPRequest::State::Complete);
+ - ]
205 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(req.GetRequestMethod(), HTTPRequestMethod::POST);
206 [ + - - + : 2 : BOOST_CHECK_EQUAL(req.GetURI(), "/");
+ - ]
207 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(req.GetVersion().major, 1);
208 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(req.GetVersion().minor, 1);
209 [ + - + - : 1 : BOOST_CHECK_EQUAL(req.GetHeader("Host"), "127.0.0.1");
+ - ]
210 [ + - + - : 1 : BOOST_CHECK_EQUAL(req.GetHeader("Connection"), "close");
+ - ]
211 [ + - + - : 1 : BOOST_CHECK_EQUAL(req.GetHeader("Content-Type"), "application/json");
+ - ]
212 [ + - + - : 1 : BOOST_CHECK_EQUAL(req.GetHeader("Authorization"), "Basic X19jb29raWVfXzo5OGQ5ODQ3MWNmNjg0NzAzYTkzN2EzNzk0ZDFlODQ1NjZmYTRkZjJiMzFkYjhhODI4ZGY4MjVjOTg5ZGI4OTVl");
+ - ]
213 [ + - + - : 1 : BOOST_CHECK_EQUAL(req.GetHeader("Content-Length"), "46");
+ - ]
214 [ + - - + : 2 : BOOST_CHECK_EQUAL(req.ReadBody(), R"({"method":"getblockcount","params":[],"id":1})""\n");
+ - ]
215 : 1 : }
216 : 1 : {
217 : : // Malformed: no spaces between data
218 : 1 : HTTPRequest req;
219 [ + - ]: 1 : LineReader reader("GET/HTTP/1.0\r\nHost: 127.0.0.1\r\n\r\n", MAX_HEADERS_SIZE);
220 [ + - - + : 2 : BOOST_CHECK_EXCEPTION(req.Load(reader), std::runtime_error, HasReason{"HTTP request line too short"});
- - - - -
+ + - + -
+ - ]
221 : 1 : }
222 : 1 : {
223 : : // Malformed: too many spaces
224 : 1 : HTTPRequest req;
225 [ + - ]: 1 : LineReader reader("GET / HTTP / 1.0\r\nHost: 127.0.0.1\r\n\r\n", MAX_HEADERS_SIZE);
226 [ + - - + : 2 : BOOST_CHECK_EXCEPTION(req.Load(reader), std::runtime_error, HasReason{"HTTP request line malformed"});
- - - - -
+ + - + -
+ - ]
227 : 1 : }
228 : 1 : {
229 : : // Malformed: slash missing before version
230 : 1 : HTTPRequest req;
231 [ + - ]: 1 : LineReader reader("GET / HTTP1.0\r\nHost: 127.0.0.1\r\n\r\n", MAX_HEADERS_SIZE);
232 [ + - - + : 2 : BOOST_CHECK_EXCEPTION(req.Load(reader), std::runtime_error, HasReason{"HTTP request line too short"});
- - - - -
+ + - + -
+ - ]
233 : 1 : }
234 : 1 : {
235 : : // Malformed: no decimal in version
236 : 1 : HTTPRequest req;
237 [ + - ]: 1 : LineReader reader("GET / HTTP/11\r\nHost: 127.0.0.1\r\n\r\n", MAX_HEADERS_SIZE);
238 [ + - - + : 2 : BOOST_CHECK_EXCEPTION(req.Load(reader), std::runtime_error, HasReason{"HTTP request line too short"});
- - - - -
+ + - + -
+ - ]
239 : 1 : }
240 : 1 : {
241 : : // Malformed: version is not a number
242 : 1 : HTTPRequest req;
243 [ + - ]: 1 : LineReader reader("GET / HTTP/1.x\r\nHost: 127.0.0.1\r\n\r\n", MAX_HEADERS_SIZE);
244 [ + - - + : 2 : BOOST_CHECK_EXCEPTION(req.Load(reader), std::runtime_error, HasReason{"HTTP bad version"});
- - - - -
+ + - + -
+ - ]
245 : 1 : }
246 : 1 : {
247 : : // Malformed: version is out of range
248 : 1 : HTTPRequest req;
249 [ + - ]: 1 : LineReader reader("GET / HTTP/2.0\r\nHost: 127.0.0.1\r\n\r\n", MAX_HEADERS_SIZE);
250 [ + - - + : 2 : BOOST_CHECK_EXCEPTION(req.Load(reader), std::runtime_error, HasReason{"HTTP bad version"});
- - - - -
+ + - + -
+ - ]
251 : 1 : }
252 : 1 : {
253 : : // Malformed: version is out of range
254 : 1 : HTTPRequest req;
255 [ + - ]: 1 : LineReader reader("GET / HTTP/0.9\r\nHost: 127.0.0.1\r\n\r\n", MAX_HEADERS_SIZE);
256 [ + - - + : 2 : BOOST_CHECK_EXCEPTION(req.Load(reader), std::runtime_error, HasReason{"HTTP bad version"});
- - - - -
+ + - + -
+ - ]
257 : 1 : }
258 : 1 : {
259 : : // Malformed: version is out of range
260 : 1 : HTTPRequest req;
261 [ + - ]: 1 : LineReader reader("GET / HTTP/-1.0\r\nHost: 127.0.0.1\r\n\r\n", MAX_HEADERS_SIZE);
262 [ + - - + : 2 : BOOST_CHECK_EXCEPTION(req.Load(reader), std::runtime_error, HasReason{"HTTP bad version"});
- - - - -
+ + - + -
+ - ]
263 : 1 : }
264 : 1 : {
265 : : // Malformed: version is not exactly two integers and a dot
266 : 1 : HTTPRequest req;
267 [ + - ]: 1 : LineReader reader("GET / HTTP/1.00\r\nHost: 127.0.0.1\r\n\r\n", MAX_HEADERS_SIZE);
268 [ + - - + : 2 : BOOST_CHECK_EXCEPTION(req.Load(reader), std::runtime_error, HasReason{"HTTP bad version"});
- - - - -
+ + - + -
+ - ]
269 : 1 : }
270 : 1 : {
271 : : // Malformed: contains NUL
272 : 1 : HTTPRequest req;
273 [ + - ]: 1 : 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};
274 [ + - - + : 2 : BOOST_CHECK_EXCEPTION(req.Load(reader), std::runtime_error, HasReason{"Invalid request line contains NUL"});
- - - - -
+ + - + -
+ - ]
275 : 1 : }
276 : 1 : {
277 : : // Malformed: differing Content-Length values, case insensitive
278 : 1 : constexpr std::string_view differing_length = "GET / HTTP/1.1\n"
279 : : "Host: 127.0.0.1\n"
280 : : "Content-Length: 8\n"
281 : : "content-length: 9\n\n"
282 : : "12345678";
283 : 1 : HTTPRequest req;
284 [ + - ]: 1 : util::LineReader reader{differing_length, /*max_line_length=*/MAX_HEADERS_SIZE};
285 [ + - - + : 2 : BOOST_CHECK_EXCEPTION(req.Load(reader), std::runtime_error, HasReason{"Differing Content-Length values"});
- - - - -
+ + - + -
+ - ]
286 : 1 : }
287 : 1 : {
288 : : // Ok: multiple same Content-Length values
289 : 1 : constexpr std::string_view differing_length = "GET / HTTP/1.1\n"
290 : : "Host: 127.0.0.1\n"
291 : : "Content-Length: 8\n"
292 : : "content-length: 8\n\n"
293 : : "12345678";
294 : 1 : HTTPRequest req;
295 [ + - ]: 1 : util::LineReader reader{differing_length, /*max_line_length=*/MAX_HEADERS_SIZE};
296 [ + - + - : 1 : BOOST_CHECK_EQUAL(req.Load(reader), HTTPRequest::State::Complete);
+ - ]
297 : 1 : }
298 : 1 : {
299 : : // Ok
300 : 1 : HTTPRequest req;
301 [ + - ]: 1 : LineReader reader("GET / HTTP/1.0\r\nHost: 127.0.0.1\r\n\r\n", MAX_HEADERS_SIZE);
302 [ + - + - : 1 : BOOST_CHECK_EQUAL(req.Load(reader), HTTPRequest::State::Complete);
+ - ]
303 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(req.GetRequestMethod(), HTTPRequestMethod::GET);
304 [ + - - + : 2 : BOOST_CHECK_EQUAL(req.GetURI(), "/");
+ - ]
305 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(req.GetVersion().major, 1);
306 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(req.GetVersion().minor, 0);
307 [ + - + - : 1 : BOOST_CHECK_EQUAL(req.GetHeader("Host"), "127.0.0.1");
+ - ]
308 : : // no body is OK
309 [ + - - + : 2 : BOOST_CHECK_EQUAL(req.ReadBody(), "");
+ - ]
310 : 1 : }
311 : 1 : {
312 : : // Malformed: missing colon
313 : 1 : HTTPRequest req;
314 [ + - ]: 1 : LineReader reader("GET / HTTP/1.0\r\nHost=127.0.0.1\r\n\r\n", MAX_HEADERS_SIZE);
315 [ + - - + : 2 : BOOST_CHECK_EXCEPTION(req.Load(reader), std::runtime_error, HasReason{"HTTP header missing colon (:)"});
- - - - -
+ + - + -
+ - ]
316 : 1 : }
317 : 1 : {
318 : : // We might not have received enough data from the client which is not
319 : : // an error. We return false so the caller can try again later when the
320 : : // buffer has more data.
321 : 1 : HTTPRequest req;
322 [ + - ]: 1 : LineReader reader("GET / HTTP/1.0\r\nHost: ", MAX_HEADERS_SIZE);
323 [ + - + - : 1 : BOOST_CHECK_EQUAL(req.Load(reader), HTTPRequest::State::NeedsHeaders);
+ - ]
324 : 1 : }
325 : 1 : {
326 : : // No Content-Length: body is not read
327 : 1 : HTTPRequest req;
328 [ + - ]: 1 : LineReader reader("GET / HTTP/1.0\r\n\r\n" R"({"method":"getblockcount"})", MAX_HEADERS_SIZE);
329 [ + - + - : 1 : BOOST_CHECK_EQUAL(req.Load(reader), HTTPRequest::State::Complete);
+ - ]
330 : : // Don't try to read request body if Content-Length is missing
331 [ + - - + : 2 : BOOST_CHECK_EQUAL(req.ReadBody(), "");
+ - ]
332 : 1 : }
333 : 1 : {
334 : : // Malformed: Content-Length is not a number
335 : 1 : HTTPRequest req;
336 [ + - ]: 1 : LineReader reader("GET / HTTP/1.0\r\nContent-Length: eleven\r\n\r\n" R"({"method":"getblockcount"})", MAX_HEADERS_SIZE);
337 [ + - - + : 2 : BOOST_CHECK_EXCEPTION(req.Load(reader), std::runtime_error, HasReason{"Cannot parse Content-Length value"});
- - - - -
+ + - + -
+ - ]
338 : 1 : }
339 : 1 : {
340 : : // Malformed: Content-Length is negative
341 : 1 : HTTPRequest req;
342 [ + - ]: 1 : LineReader reader("GET / HTTP/1.0\r\nContent-Length: -8\r\n\r\n" R"({"method":"getblockcount"})", MAX_HEADERS_SIZE);
343 [ + - - + : 2 : BOOST_CHECK_EXCEPTION(req.Load(reader), std::runtime_error, HasReason{"Cannot parse Content-Length value"});
- - - - -
+ + - + -
+ - ]
344 : 1 : }
345 : 1 : {
346 : : // Content-Length exceeds limit
347 : 1 : constexpr auto excessive_size{MAX_BODY_SIZE + 1};
348 [ + - ]: 1 : std::string huge_body(excessive_size, 'x');
349 [ + - + - : 3 : const std::string request{"GET / HTTP/1.0\r\nContent-Length: " + util::ToString(excessive_size) + "\r\n\r\n" + std::move(huge_body)};
+ - ]
350 : 1 : HTTPRequest req;
351 [ - + + - ]: 1 : LineReader reader(request, MAX_HEADERS_SIZE);
352 [ + - - + : 2 : BOOST_CHECK_EXCEPTION(req.Load(reader), ContentTooLargeError, HasReason{"Max body size exceeded"});
- - - - -
+ + - + -
+ - + - ]
353 : 1 : }
354 : 1 : {
355 : : // Content-Length exactly on the limit
356 [ + - ]: 1 : std::string max_body(MAX_BODY_SIZE, 'x');
357 [ + - + - : 3 : const std::string request{"GET / HTTP/1.0\r\nContent-Length: " + util::ToString(MAX_BODY_SIZE) + "\r\n\r\n" + std::move(max_body)};
+ - ]
358 : 1 : HTTPRequest req;
359 [ - + + - ]: 1 : LineReader reader(request, MAX_HEADERS_SIZE);
360 [ + - + - : 1 : BOOST_CHECK_EQUAL(req.Load(reader), HTTPRequest::State::Complete);
+ - ]
361 : 1 : }
362 : 1 : {
363 : : // Content-Length indicates more data than we have in the buffer.
364 : : // Not an error; we wait for more data before completing the body.
365 : 1 : HTTPRequest req;
366 [ + - ]: 1 : LineReader reader("GET / HTTP/1.0\r\nContent-Length: 1024\r\n\r\n" R"({"method":"getblockcount"})", MAX_HEADERS_SIZE);
367 [ + - + - : 1 : BOOST_CHECK_EQUAL(req.Load(reader), HTTPRequest::State::NeedsBody);
+ - ]
368 : 1 : }
369 : 1 : {
370 : : // Support "chunked" transfer. Chunk lengths are ascii-encoded hex integers, whitespace ignored
371 : 1 : HTTPRequest req;
372 : 1 : std::string_view ok_chunked = "GET / HTTP/1.0\n"
373 : : "Transfer-Encoding: chunked\n"
374 : : "\n"
375 : : "10\n"
376 : : R"({"method":"getbl)""\n"
377 : : " a \n"
378 : : R"(ockcount"})""\n"
379 : : "0\n"
380 : : "\n";
381 [ + - ]: 1 : LineReader reader(ok_chunked, MAX_HEADERS_SIZE);
382 [ + - + - : 1 : BOOST_CHECK_EQUAL(req.Load(reader), HTTPRequest::State::Complete);
+ - ]
383 [ + - - + : 2 : BOOST_CHECK_EQUAL(req.ReadBody(), R"({"method":"getblockcount"})");
+ - ]
384 : 1 : }
385 : 1 : {
386 : : // Prevent "chunked" transfer from exceeding size limit
387 : 1 : HTTPRequest req;
388 : 1 : std::string_view excessive_chunk_size = "GET / HTTP/1.0\n"
389 : : "Transfer-Encoding: chunked\n"
390 : : "\n"
391 : : "10\n"
392 : : R"({"method":"getbl)""\n"
393 : : "20000000\n"
394 : : R"(ockcount"})""\n"
395 : : "0\n"
396 : : "\n";
397 [ + - ]: 1 : LineReader reader(excessive_chunk_size, MAX_HEADERS_SIZE);
398 [ + - - + : 2 : BOOST_CHECK_EXCEPTION(req.Load(reader), ContentTooLargeError, HasReason{"Chunk will exceed max body size"});
- - - - -
+ + - + -
+ - + - ]
399 : 1 : }
400 : 1 : {
401 : : // Allow (but ignore) Chunk Extensions
402 : 1 : HTTPRequest req;
403 : 1 : std::string_view ok_chunked = "GET / HTTP/1.0\n"
404 : : "Transfer-Encoding: chunked\n"
405 : : "\n"
406 : : "10;sha256=715790e8a3b09d704ac9641f42d183a5ebc5fd939663de23da548519ac2165e5\n"
407 : : R"({"method":"getbl)""\n"
408 : : " a ; compressed\n"
409 : : R"(ockcount"})""\n"
410 : : "0;why;would;anyone;do;this;\n"
411 : : "Expires: Wed, 21 Oct 2026 07:28:00 GMT\n"
412 : : "\n";
413 [ + - ]: 1 : LineReader reader(ok_chunked, MAX_HEADERS_SIZE);
414 [ + - + - : 1 : BOOST_CHECK_EQUAL(req.Load(reader), HTTPRequest::State::Complete);
+ - ]
415 [ + - - + : 2 : BOOST_CHECK_EQUAL(req.ReadBody(), R"({"method":"getblockcount"})");
+ - ]
416 : : // Chunk Trailer was parsed, but ignored
417 [ + - + - : 1 : BOOST_CHECK_EQUAL(reader.Remaining(), 0);
+ - ]
418 [ + - + - : 2 : BOOST_CHECK(!req.GetHeader("Expires"));
+ - ]
419 : 1 : }
420 : 1 : {
421 : : // Invalid "chunked" transfer, using roman numerals instead of hex for chunk length
422 : 1 : HTTPRequest req;
423 : 1 : std::string_view invalid_chunked = "GET / HTTP/1.0\n"
424 : : "Transfer-Encoding: chunked\n"
425 : : "\n"
426 : : "XVI\n"
427 : : R"({"method":"getbl)""\n"
428 : : "X\n"
429 : : R"(ockcount"})""\n"
430 : : "0\n"
431 : : "\n";
432 [ + - ]: 1 : LineReader reader(invalid_chunked, MAX_HEADERS_SIZE);
433 [ + - - + : 2 : BOOST_CHECK_EXCEPTION(req.Load(reader), std::runtime_error, HasReason{"Cannot parse chunk length value"});
- - - - -
+ + - + -
+ - ]
434 : 1 : }
435 : 1 : {
436 : : // Invalid "chunked" transfer, missing chunk termination \n
437 : 1 : HTTPRequest req;
438 : 1 : std::string_view invalid_chunked = "GET / HTTP/1.0\n"
439 : : "Transfer-Encoding: chunked\n"
440 : : "\n"
441 : : "10\n"
442 : : R"({"method":"getbl)"
443 : : "a\n" // interpreted as extra data at the end of `0x10`-sized chunk
444 : : R"(ockcount"})"
445 : : "0\n"
446 : : "\n";
447 [ + - ]: 1 : LineReader reader(invalid_chunked, MAX_HEADERS_SIZE);
448 [ + - - + : 2 : BOOST_CHECK_EXCEPTION(req.Load(reader), std::runtime_error, HasReason{"Improperly terminated chunk"});
- - - - -
+ + - + -
+ - ]
449 : 1 : }
450 : 1 : }
451 : :
452 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(http_request_state_tests)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
453 : : {
454 : : // For these tests we just need a receive buffer for the requests to read from.
455 : 10 : class DummyClient : public HTTPRemoteClient
456 : : {
457 : : public:
458 [ + - + - ]: 9 : DummyClient() : HTTPRemoteClient{/*id=*/0, /*addr=*/CService(), /*socket=*/CreateSock(0, 0, 0)} {}
459 : :
460 : 1662 : void Receive(std::string_view s)
461 : : {
462 [ + - + - : 1659 : MutateRecvBuffer().append(s);
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - +
- ]
463 : 1662 : }
464 : : };
465 : 1 : using enum HTTPRequest::State;
466 : :
467 : 1 : {
468 : : // Step through state machine
469 : 1 : HTTPRequest req;
470 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(req.GetState(), Init);
471 : :
472 : 1 : {
473 [ + - ]: 1 : util::LineReader reader{"POST / HTTP/1.0\n", /*max_line_length=*/MAX_HEADERS_SIZE};
474 [ + - + - : 1 : BOOST_CHECK_EQUAL(req.Load(reader), NeedsHeaders);
+ - ]
475 : : }
476 : 1 : {
477 : 1 : util::LineReader reader{"Host: 127.0.0.1\n"
478 : : "Content-Length: 10\n\n",
479 [ + - ]: 1 : /*max_line_length=*/MAX_HEADERS_SIZE};
480 [ + - + - : 1 : BOOST_CHECK_EQUAL(req.Load(reader), NeedsBody);
+ - ]
481 : : }
482 : 1 : {
483 : 1 : util::LineReader reader{"I miss you\n",
484 [ + - ]: 1 : /*max_line_length=*/MAX_HEADERS_SIZE};
485 [ + - + - : 1 : BOOST_CHECK_EQUAL(req.Load(reader), Complete);
+ - ]
486 : : }
487 : 1 : }
488 : 1 : {
489 : : // Read body over multiple data pushes, multiple requests in same push
490 : 1 : std::shared_ptr<DummyClient> client{std::make_shared<DummyClient>()};
491 [ + - + - : 2 : BOOST_CHECK(!client->GetRequest());
+ - ]
492 : :
493 [ + - ]: 1 : client->Receive("POST / HTTP/1.0\n"
494 : : "Host: 127.0.0.1\n"
495 : : "Content-Length: 10\n\n"
496 : : "I miss");
497 [ + - + - : 4 : BOOST_CHECK(!HTTPRemoteClient::TryReadRequest(client));
+ - + - +
- + - ]
498 : : // Because of the Content-Length header we know the body is not complete
499 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetState(), NeedsBody);
500 : :
501 : : // Finish sending first request and include second request in the same buffer
502 [ + - ]: 1 : client->Receive(" you"
503 : : "GET /endpoint HTTP/1.0\n\n");
504 [ + - + - ]: 2 : auto req{HTTPRemoteClient::TryReadRequest(client)};
505 [ + - + - : 2 : BOOST_REQUIRE(req);
+ - ]
506 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(req->GetState(), Complete);
507 [ + - - + : 2 : BOOST_CHECK_EQUAL(req->GetURI(), "/");
+ - ]
508 [ + - + - : 2 : BOOST_CHECK(!client->GetRequest());
+ - ]
509 [ + - - + : 2 : BOOST_CHECK_EQUAL(req->ReadBody(), "I miss you");
+ - ]
510 [ + - ]: 1 : req->WriteReply(HTTP_OK, ""); // Mark client as no longer busy
511 : : // Next request sitting in buffer
512 [ + - - + : 1 : BOOST_CHECK_EQUAL(client->GetRecvBuffer().size(), 24);
+ - ]
513 : :
514 : : // Read second request
515 [ + - + - : 3 : req = HTTPRemoteClient::TryReadRequest(client);
+ - ]
516 [ + - + - : 2 : BOOST_REQUIRE(req);
+ - ]
517 [ + - + - : 2 : BOOST_CHECK(!client->GetRequest());
+ - ]
518 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(req->GetState(), Complete);
519 [ + - - + : 2 : BOOST_CHECK_EQUAL(req->GetURI(), "/endpoint");
+ - ]
520 [ + - - + : 2 : BOOST_CHECK_EQUAL(req->ReadBody().size(), 0);
- + + - ]
521 : : // Buffer is cleared
522 [ + - - + : 1 : BOOST_CHECK_EQUAL(client->GetRecvBuffer().size(), 0);
+ - ]
523 [ + - ]: 1 : }
524 : 1 : {
525 : : // A Content-Length body is drained out of the receive buffer as it
526 : : // arrives, instead of accumulating there until the request is complete.
527 : :
528 : 1 : std::shared_ptr<DummyClient> client{std::make_shared<DummyClient>()};
529 [ + - + - : 2 : BOOST_CHECK(!client->GetRequest());
+ - ]
530 : :
531 [ + - ]: 1 : client->Receive("POST / HTTP/1.0\n"
532 : : "Content-Length: 30000\n\n");
533 [ + - + - : 2 : HTTPRemoteClient::TryReadRequest(client);
+ - ]
534 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetState(), NeedsBody);
535 : :
536 : : // Body arrives in 10kB pieces. Each one is copied onto m_body and
537 : : // erased from the receive buffer, which never holds more than one piece.
538 [ + + ]: 4 : for (int i = 1; i <= 3; ++i) {
539 [ + - - + : 6 : client->Receive(std::string(10000, 'x'));
+ - ]
540 [ + - - + : 3 : BOOST_CHECK_EQUAL(client->GetRecvBuffer().size(), 10000);
+ - ]
541 [ + - + - ]: 6 : auto req{HTTPRemoteClient::TryReadRequest(client)};
542 [ + + ]: 3 : if (i < 3) {
543 [ + - + - : 4 : BOOST_CHECK(!req.get());
+ - ]
544 [ + - - + : 4 : BOOST_CHECK_EQUAL(client->GetRequest()->ReadBody().size(), 10000 * i);
- + + - ]
545 : : } else {
546 [ + - + - : 2 : BOOST_CHECK(req.get());
+ - ]
547 [ + - - + : 2 : BOOST_CHECK_EQUAL(req->ReadBody().size(), 10000 * i);
- + + - ]
548 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(req->GetState(), Complete);
549 [ + - + - ]: 2 : BOOST_CHECK(!client->GetRequest());
550 : : }
551 [ + - - + : 3 : BOOST_CHECK_EQUAL(client->GetRecvBuffer().size(), 0);
+ - ]
552 : 3 : }
553 : 0 : }
554 : 1 : {
555 : : // A body sent in the same push as the next request is split correctly
556 : 1 : std::shared_ptr<DummyClient> client{std::make_shared<DummyClient>()};
557 [ + - + - : 2 : BOOST_CHECK(!client->GetRequest());
+ - ]
558 : :
559 [ + - ]: 1 : client->Receive("POST / HTTP/1.0\n"
560 : : "Content-Length: 4\n\n"
561 : : "body"
562 : : "GET /next HTTP/1.0\n\n");
563 [ + - + - ]: 2 : auto req{HTTPRemoteClient::TryReadRequest(client)};
564 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(req->GetState(), Complete);
565 [ + - - + : 2 : BOOST_CHECK_EQUAL(req->ReadBody(), "body");
+ - ]
566 : : // Only the second request is left over
567 [ + - - + : 1 : BOOST_CHECK_EQUAL(client->GetRecvBuffer().size(), 20);
+ - ]
568 [ + - ]: 1 : }
569 : 1 : {
570 : : // Chunked transfer with state
571 : 1 : std::shared_ptr<DummyClient> client{std::make_shared<DummyClient>()};
572 [ + - + - : 2 : BOOST_CHECK(!client->GetRequest());
+ - ]
573 : :
574 : : // First chunk is incomplete
575 [ + - ]: 1 : client->Receive("GET / HTTP/1.0\n"
576 : : "Transfer-Encoding: chunked\n"
577 : : "\n"
578 : : "10\n"
579 : : R"({"method)");
580 [ + - + - : 4 : BOOST_CHECK(!HTTPRemoteClient::TryReadRequest(client));
+ - + - +
- + - ]
581 [ + - + - : 2 : BOOST_REQUIRE(client->GetRequest()->GetChunkSize());
+ - ]
582 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(*client->GetRequest()->GetChunkSize(), 16);
583 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetChunkProgress(), 8);
584 [ + - - + : 2 : BOOST_CHECK_EQUAL(client->GetRequest()->ReadBody().size(), 8);
- + + - ]
585 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetState(), NeedsBody);
586 : :
587 : : // More data arrives, chunk is completed.
588 [ + - ]: 1 : client->Receive(R"(":"getbl)""\n");
589 [ + - + - : 4 : BOOST_CHECK(!HTTPRemoteClient::TryReadRequest(client));
+ - + - +
- + - ]
590 : : // State is reset
591 [ + - + - : 2 : BOOST_CHECK(!client->GetRequest()->GetChunkSize());
+ - ]
592 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetChunkProgress(), 0);
593 : : // New data is added to body but body is still incomplete
594 [ + - - + : 2 : BOOST_CHECK_EQUAL(client->GetRequest()->ReadBody().size(), 16);
- + + - ]
595 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetState(), NeedsBody);
596 : :
597 : : // Next chunk arrives without terminal CRLF
598 [ + - ]: 1 : client->Receive("a\n"
599 : : R"(ockcount"})");
600 [ + - + - : 4 : BOOST_CHECK(!HTTPRemoteClient::TryReadRequest(client));
+ - + - +
- + - ]
601 [ + - + - : 2 : BOOST_CHECK(client->GetRequest()->GetChunkSize());
+ - ]
602 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(*client->GetRequest()->GetChunkSize(), 10);
603 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetChunkProgress(), 10);
604 [ + - - + : 2 : BOOST_CHECK_EQUAL(client->GetRequest()->ReadBody().size(), 26);
- + + - ]
605 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetState(), NeedsBody);
606 : :
607 : : // Chunk terminal CRLF arrives with final (size 0) chunk
608 [ + - ]: 1 : client->Receive("\n0\n\n");
609 [ + - + - ]: 2 : auto req{HTTPRemoteClient::TryReadRequest(client)};
610 : : // Body size hasn't changed
611 [ + - - + : 2 : BOOST_CHECK_EQUAL(req->ReadBody().size(), 26);
- + + - ]
612 : : // We're done
613 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(req->GetState(), Complete);
614 [ + - - + : 2 : BOOST_CHECK_EQUAL(req->ReadBody(), R"({"method":"getblockcount"})");
+ - ]
615 [ + - ]: 1 : }
616 : 1 : {
617 : : // Invalid headers: error state stops reading
618 : 1 : std::shared_ptr<DummyClient> client{std::make_shared<DummyClient>()};
619 : :
620 : : // Request is in the buffer
621 [ + - ]: 1 : client->Receive("POST / HTTP/1.0\n"
622 : : "Host: 127.0.0.1\n");
623 [ + - + - : 2 : BOOST_CHECK(!client->GetRecvBuffer().empty());
+ - ]
624 [ + - + - : 4 : BOOST_CHECK(!HTTPRemoteClient::TryReadRequest(client));
+ - + - +
- + - ]
625 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetState(), NeedsHeaders);
626 [ + - ]: 1 : client->Receive("Invalid header with no colon\n"
627 : : "\n"
628 : : "body is not read");
629 : : // Reading throws an error, sets state
630 [ + - + - : 4 : BOOST_CHECK(!HTTPRemoteClient::TryReadRequest(client));
+ - + - +
- + - ]
631 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetState(), Error);
632 : :
633 : : // We read up to the invalid line
634 [ + - + - : 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetHeader("Host"), "127.0.0.1");
+ - ]
635 : : // Buffer was cleared, client should just be disconnected now
636 [ + - + - : 2 : BOOST_CHECK(client->GetRecvBuffer().empty());
+ - ]
637 : :
638 : : // Even if more data comes in, trying to read again in error state is a no-op
639 [ + - ]: 1 : client->Receive("Content-Length: 2\n\nok");
640 [ + - - + : 1 : BOOST_CHECK_EQUAL(client->GetRecvBuffer().size(), 21);
+ - ]
641 [ + - + - : 4 : BOOST_CHECK(!HTTPRemoteClient::TryReadRequest(client));
+ - + - +
- + - ]
642 [ + - - + : 1 : BOOST_CHECK_EQUAL(client->GetRecvBuffer().size(), 21);
+ - + - ]
643 : 0 : }
644 : 1 : {
645 : : // Headers sent in batches that are below MAX_HEADERS_SIZE but the total is excessive
646 : 1 : std::shared_ptr<DummyClient> client{std::make_shared<DummyClient>()};
647 [ + - + - : 2 : BOOST_CHECK(!client->GetRequest());
+ - ]
648 [ + - + - : 4 : BOOST_CHECK(!HTTPRemoteClient::TryReadRequest(client));
+ - + - +
- + - ]
649 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetState(), Init);
650 : :
651 [ + - ]: 1 : client->Receive("POST /huge HTTP/1.0\n");
652 [ + - + - : 4 : BOOST_CHECK(!HTTPRemoteClient::TryReadRequest(client));
+ - + - +
- + - ]
653 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetState(), NeedsHeaders);
654 : :
655 [ + + ]: 411 : for (int i = 0; i < 410; ++i) {
656 [ + - ]: 820 : client->Receive("key:value\n");
657 : : }
658 [ + - + - : 4 : BOOST_CHECK(!HTTPRemoteClient::TryReadRequest(client));
+ - + - +
- + - ]
659 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetState(), NeedsHeaders);
660 : :
661 [ + + ]: 410 : for (int i = 0; i < 409; ++i) {
662 [ + - ]: 818 : client->Receive("key:value\n");
663 : : }
664 [ + - + - : 4 : BOOST_CHECK(!HTTPRemoteClient::TryReadRequest(client));
+ - + - +
- + - ]
665 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetState(), NeedsHeaders);
666 : :
667 : : // We're at 819 x 10-byte headers
668 : : // The limit is 8192, three more bytes should throw.
669 [ + - ]: 1 : client->Receive("k:\n");
670 [ + - + - : 4 : BOOST_CHECK(!HTTPRemoteClient::TryReadRequest(client));
+ - + - +
- + - ]
671 [ + - + - : 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetState(), Error);
+ - ]
672 : 0 : }
673 : 1 : {
674 : : // Client sends chunks that are below the limit but the total is excessive
675 : 1 : std::shared_ptr<DummyClient> client{std::make_shared<DummyClient>()};
676 [ + - + - : 4 : BOOST_CHECK(!HTTPRemoteClient::TryReadRequest(client));
+ - + - +
- + - ]
677 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetState(), Init);
678 : :
679 [ + - ]: 1 : client->Receive("POST /huge HTTP/1.0\n");
680 [ + - + - : 4 : BOOST_CHECK(!HTTPRemoteClient::TryReadRequest(client));
+ - + - +
- + - ]
681 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetState(), NeedsHeaders);
682 : :
683 [ + - ]: 1 : client->Receive("Transfer-Encoding: chunked\n\n");
684 [ + - + - : 4 : BOOST_CHECK(!HTTPRemoteClient::TryReadRequest(client));
+ - + - +
- + - ]
685 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetState(), NeedsBody);
686 : :
687 : : // Send 16-byte chunk
688 [ + - ]: 1 : client->Receive("10\nno auto updates!\n");
689 [ + - + - : 4 : BOOST_CHECK(!HTTPRemoteClient::TryReadRequest(client));
+ - + - +
- + - ]
690 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetState(), NeedsBody);
691 : :
692 : : // The next chunk will be of size 32MiB - 16 + 1, below the limit
693 : : // on its own but not if it were added to the total cumulative body so far.
694 : : // We don't need to actually send or prepare this amount of data.
695 [ + - ]: 1 : client->Receive("1fffff1\n");
696 [ + - + - : 4 : BOOST_CHECK(!HTTPRemoteClient::TryReadRequest(client));
+ - + - +
- + - ]
697 [ + - + - : 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetState(), Error);
+ - ]
698 : 0 : }
699 : 1 : {
700 : : // Ensure chunk trailer is parsed over state lines
701 : 1 : std::shared_ptr<DummyClient> client{std::make_shared<DummyClient>()};
702 [ + - + - : 2 : BOOST_CHECK(!client->GetRequest());
+ - ]
703 : :
704 : : // Send a 1-byte chunk then send the 0-chunk with a trailer but no terminal CRLF
705 [ + - ]: 1 : client->Receive("GET / HTTP/1.0\n"
706 : : "Transfer-Encoding: chunked\n"
707 : : "\n"
708 : : "1\n"
709 : : "x\n"
710 : : "0\n"
711 : : "Digest: sha-4=deadbeef\n");
712 [ + - + - : 4 : BOOST_CHECK(!HTTPRemoteClient::TryReadRequest(client));
+ - + - +
- + - ]
713 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetState(), NeedsBody);
714 : :
715 : : // Send first part of another trailer line
716 [ + - ]: 1 : client->Receive("Expires:");
717 [ + - + - : 4 : BOOST_CHECK(!HTTPRemoteClient::TryReadRequest(client));
+ - + - +
- + - ]
718 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetState(), NeedsBody);
719 : :
720 : : // Finish the trailer line
721 [ + - ]: 1 : client->Receive("never\n");
722 [ + - + - : 4 : BOOST_CHECK(!HTTPRemoteClient::TryReadRequest(client));
+ - + - +
- + - ]
723 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetState(), NeedsBody);
724 : :
725 : : // Terminate
726 [ + - ]: 1 : client->Receive("\n");
727 [ + - + - ]: 2 : auto req{HTTPRemoteClient::TryReadRequest(client)};
728 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(req->GetState(), Complete);
729 [ + - - + : 2 : BOOST_CHECK_EQUAL(req->ReadBody(), "x");
+ - ]
730 [ + - ]: 1 : }
731 : 1 : {
732 : : // Ensure chunk trailer counts towards the headers size limit
733 : 1 : std::shared_ptr<DummyClient> client{std::make_shared<DummyClient>()};
734 [ + - + - : 2 : BOOST_CHECK(!client->GetRequest());
+ - ]
735 : :
736 [ + - ]: 1 : client->Receive("POST /huge HTTP/1.0\n"
737 : : "Transfer-Encoding: chunked\n"); // 27 bytes
738 [ + + ]: 817 : for (int i = 0; i < 816; ++i) {
739 [ + - ]: 1632 : client->Receive("key:value\n"); // 8160
740 : : }
741 [ + - ]: 1 : client->Receive("\n" // 1
742 : : "1\n"
743 : : "x\n"
744 : : "0\n");
745 [ + - + - : 4 : BOOST_CHECK(!HTTPRemoteClient::TryReadRequest(client));
+ - + - +
- + - ]
746 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetState(), NeedsBody);
747 : :
748 : : // We're in the trailer section with a total of 8188 bytes of headers.
749 : : // The limit is 8192, five more bytes should throw.
750 [ + - ]: 1 : client->Receive("k:vv\n");
751 [ + - + - : 4 : BOOST_CHECK(!HTTPRemoteClient::TryReadRequest(client));
+ - + - +
- + - ]
752 [ + - + - : 1 : BOOST_CHECK_EQUAL(client->GetRequest()->GetState(), Error);
+ - ]
753 : 1 : }
754 : 1 : }
755 : :
756 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(http_should_disconnect_tests)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
757 : : {
758 : 6 : struct Client : HTTPRemoteClient {
759 : 5 : Client(std::unique_ptr<Sock> socket = CreateSock(0, 0, 0))
760 [ + - ]: 5 : : HTTPRemoteClient{/*id=*/0, /*addr=*/CService(), /*socket=*/std::move(socket)} {}
761 : : using HTTPRemoteClient::MutateRecvBuffer;
762 : : };
763 : : // Prevent the clock from actually progressing during this scope.
764 : 1 : const FakeSteadyClock clock;
765 : 1 : constexpr auto timeout{30s};
766 : 1 : const auto now{MockableSteadyClock::now()};
767 : :
768 : 1 : {
769 : : // Nothing to disconnect for yet.
770 [ + - ]: 1 : auto idle{std::make_shared<Client>()};
771 [ + - + - : 2 : BOOST_CHECK(!idle->ShouldDisconnect(now, timeout, /*disconnect_all=*/false));
+ - + - ]
772 : : // A shutdown waits for a connection that is still busy, and it starts busy.
773 [ + - + - : 2 : BOOST_CHECK(!idle->ShouldDisconnect(now, timeout, /*disconnect_all=*/true));
+ - + - ]
774 : : // Past -rpcservertimeout, which a timeout of 0 disables.
775 [ + - + - : 2 : BOOST_CHECK( idle->ShouldDisconnect(now + timeout + 1s, timeout, /*disconnect_all=*/false));
+ - + - ]
776 : : // Timeout was disabled by user.
777 [ + - + - : 2 : BOOST_CHECK(!idle->ShouldDisconnect(now + timeout + 1s, /*rpcservertimeout=*/0s, /*disconnect_all=*/false));
+ - + - ]
778 : 0 : }
779 : :
780 : 1 : {
781 [ + - ]: 2 : struct SlowSocket : ZeroSock {
782 : 7 : ssize_t Send(const void*, size_t len, int) const override {
783 : 7 : return CeilDiv(len, 2U); // Only let through half per call
784 : : }
785 : : private:
786 : 0 : SlowSocket& operator=(Sock&&) override {
787 : 0 : AssertUnreachable(); // Move of Sock into SlowSocket not allowed.
788 : : }
789 : : };
790 : :
791 : : // A request handed to a worker holds the idle timeout off until the reply is sent.
792 [ + - ]: 2 : auto busy_slow{std::make_shared<Client>(std::make_unique<SlowSocket>())};
793 [ + - ]: 1 : busy_slow->MutateRecvBuffer().append("GET / HTTP/1.0\n\n");
794 : 1 : {
795 [ + - + - ]: 2 : std::unique_ptr request{HTTPRemoteClient::TryReadRequest(busy_slow)};
796 [ + - + - : 2 : BOOST_REQUIRE(request);
+ - ]
797 : : // Avoid disconnecting even if we are past the timeout, a worker is busy.
798 [ + - + - : 2 : BOOST_CHECK(!busy_slow->ShouldDisconnect(now + timeout + 1s, timeout, /*disconnect_all=*/false));
+ - + - ]
799 [ + - + - : 2 : BOOST_CHECK(!busy_slow->ShouldDisconnect(now + timeout + 1s, timeout, /*disconnect_all=*/true));
+ - + - ]
800 : : // Worker becomes finished with the request.
801 [ + - ]: 1 : request->WriteReply(HTTP_OK);
802 : 1 : }
803 : : // Don't disconnect here as WriteReply() was unable to complete the
804 : : // optimistic send of the full response due to the SlowSocket.
805 [ + - + - : 2 : BOOST_CHECK(!busy_slow->ShouldDisconnect(now + timeout - 1s, timeout, /*disconnect_all=*/false));
+ - + - ]
806 : : // Disconnect anyway if we are past the timeout.
807 [ + - + - : 2 : BOOST_CHECK( busy_slow->ShouldDisconnect(now + timeout + 1s, timeout, /*disconnect_all=*/false));
+ - ]
808 : :
809 : : // Finish sending response.
810 [ + - + + ]: 7 : while (busy_slow->ReadyToSend()) {
811 [ + - ]: 6 : busy_slow->MaybeSendBytesFromBuffer();
812 : : }
813 : : // Now we are done sending we are ready to disconnect despite being below the timeout.
814 [ + - + - : 2 : BOOST_CHECK( busy_slow->ShouldDisconnect(now + timeout - 1s, timeout, /*disconnect_all=*/false));
+ - + - ]
815 : 0 : }
816 : :
817 : 1 : {
818 : : // Allow disconnecting directly after WriteReply() when it is able to
819 : : // complete the optimistic send of the full response due to
820 : : // ZeroSock::Send() claiming its able to send everything.
821 [ + - ]: 2 : auto busy_fast{std::make_shared<Client>(std::make_unique<ZeroSock>())};
822 [ + - ]: 1 : busy_fast->MutateRecvBuffer().append("GET / HTTP/1.0\n\n");
823 : 1 : {
824 [ + - + - ]: 2 : std::unique_ptr request{HTTPRemoteClient::TryReadRequest(busy_fast)};
825 [ + - + - : 2 : BOOST_REQUIRE(request);
+ - ]
826 : : // Worker becomes finished with the request.
827 [ + - ]: 1 : request->WriteReply(HTTP_OK);
828 : 1 : }
829 [ + - + - : 2 : BOOST_CHECK( busy_fast->ShouldDisconnect(now + timeout - 1s, timeout, /*disconnect_all=*/false));
+ - + - ]
830 : :
831 [ + - ]: 3 : DebugLogHelper ban_idle_message{"HTTP client idle timeout", [](const std::string* s) {
832 [ - + - - ]: 1 : if (s) BOOST_ERROR("Should not get idle message when m_disconnect is already set.");
833 : 1 : return false;
834 [ + - ]: 1 : }};
835 [ + - + - : 2 : BOOST_CHECK( busy_fast->ShouldDisconnect(now + timeout + 1s, timeout, /*disconnect_all=*/false));
+ - ]
836 [ + - ]: 1 : }
837 : :
838 : 1 : {
839 : : // A keep-alive HTTP 1.1 client whose reply is out is neither flagged
840 : : // nor idle, so the shutdown branch is the only thing that can release it.
841 [ + - ]: 2 : auto keepalive{std::make_shared<Client>(std::make_unique<ZeroSock>())};
842 [ + - ]: 1 : keepalive->MutateRecvBuffer().append("GET / HTTP/1.1\nHost: 127.0.0.1\n\n");
843 : 1 : {
844 [ + - + - ]: 2 : std::unique_ptr request{HTTPRemoteClient::TryReadRequest(keepalive)};
845 [ + - + - : 2 : BOOST_REQUIRE(request);
+ - ]
846 [ + - ]: 1 : request->WriteReply(HTTP_OK);
847 : 1 : }
848 [ + - + - : 2 : BOOST_CHECK(!keepalive->ShouldDisconnect(now, timeout + 1s, /*disconnect_all=*/false));
+ - + - ]
849 [ + - + - : 2 : BOOST_CHECK( keepalive->ShouldDisconnect(now, timeout + 1s, /*disconnect_all=*/true));
+ - + - ]
850 : 0 : }
851 : :
852 : 1 : {
853 : : // A malformed request flags the client, and that outranks the rest.
854 [ + - ]: 1 : auto bad{std::make_shared<Client>()};
855 [ + - ]: 1 : bad->MutateRecvBuffer().append("GET / HTTP/1.0\nInvalid header with no colon\n\n");
856 [ + - + - : 4 : BOOST_CHECK(!HTTPRemoteClient::TryReadRequest(bad));
+ - + - +
- + - ]
857 [ + - + - : 2 : BOOST_CHECK(bad->ShouldDisconnect(now, /*rpcservertimeout=*/0s, /*disconnect_all=*/false));
+ - + - ]
858 : 1 : }
859 : 1 : }
860 : :
861 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(http_server_socket_tests)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
862 : : {
863 : : // Hard code the timestamp for the Date header in the HTTP response
864 : : // Wed Dec 11 00:47:09 2024 UTC
865 : 1 : FakeNodeClock clock{1733878029s};
866 : :
867 : : // Prepare a request handler that just stores received requests so we can examine them.
868 : : // Mutex is required to prevent a race between this test's main thread and the server's I/O loop.
869 : 1 : Mutex requests_mutex;
870 [ + - ]: 1 : std::deque<std::unique_ptr<HTTPRequest>> requests;
871 : 2 : auto StoreRequest = [&](std::unique_ptr<HTTPRequest>&& req) {
872 : 1 : LOCK(requests_mutex);
873 [ + - + - ]: 1 : requests.push_back(std::move(req));
874 : 2 : };
875 : :
876 [ + - ]: 1 : HTTPServer server{StoreRequest};
877 [ + - ]: 1 : server.InitHTTPAllowList();
878 : :
879 : 1 : {
880 : : // We can only bind to NET_IPV4 and NET_IPV6
881 [ + - + - : 2 : CService onion_address{Lookup("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaam2dqd.onion", /*portDefault=*/0, /*fAllowLookup=*/false).value()};
+ - ]
882 [ + - ]: 1 : auto result{server.BindAndStartListening(onion_address)};
883 [ + - + - : 2 : BOOST_REQUIRE(!result);
+ - ]
884 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(result.error(), "Bind address family for aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaam2dqd.onion:0 not supported");
885 : 1 : }
886 : :
887 : : // This VALID address won't actually get used because we stubbed CreateSock()
888 [ + - + - : 2 : CService addr_bind{Lookup("0.0.0.0", /*portDefault=*/0, /*fAllowLookup=*/false).value()};
+ - ]
889 : :
890 : : // Init state
891 [ + - - + : 1 : BOOST_REQUIRE_EQUAL(server.GetListeningSocketCount(), 0);
+ - ]
892 : : // Bind to mock Listening Socket
893 [ + - + - : 2 : BOOST_REQUIRE(server.BindAndStartListening(addr_bind));
+ - + - ]
894 : : // We are bound and listening
895 [ + - - + : 1 : BOOST_REQUIRE_EQUAL(server.GetListeningSocketCount(), 1);
+ - ]
896 : :
897 : : // Start the I/O loop
898 [ + - ]: 1 : server.StartSocketsThreads();
899 : :
900 : : // No connections yet
901 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(server.GetConnectionsCount(), 0);
902 : :
903 : : // Create a mock client with pre-loaded request data and add it to the local CreateSock queue.
904 : : // Keep a handle for the mock client's send and receive pipes so we can examine
905 : : // the data it "receives".
906 : : // No keep-alive, so the server closes once the reply is flushed, and says so.
907 [ + - + - ]: 2 : DebugLogHelper find_close{"Done sending to client without keep-alive"};
908 : :
909 [ + - ]: 1 : std::shared_ptr<DynSock::Pipes> mock_client_socket_pipes{ConnectClient(std::as_bytes(std::span(full_request)))};
910 : :
911 : : // Wait up to a minute to find and connect the client in the I/O loop
912 : : int attempts{6000};
913 : 2 : while (server.GetConnectionsCount() < 1) {
914 [ + - ]: 1 : std::this_thread::sleep_for(10ms);
915 [ + - + - : 3 : BOOST_REQUIRE(--attempts > 0);
+ + ]
916 : : }
917 : :
918 : : // Prepare a pointer to the client, we'll assign it from the request itself.
919 : 1 : std::shared_ptr<HTTPRemoteClient> client;
920 : :
921 : : // Wait up to a minute to read the request from the client.
922 : : // Given that the mock client is itself a mock socket
923 : : // with hard-coded data it should only take a fraction of that.
924 : 1 : attempts = 6000;
925 : 0 : while (true) {
926 : 1 : {
927 [ + - ]: 1 : LOCK(requests_mutex);
928 : : // Connected client should have one request already from the static content.
929 [ - + + - ]: 1 : if (requests.size() == 1) {
930 : : // Check the received request
931 [ + - - + : 2 : BOOST_CHECK_EQUAL(requests.front()->ReadBody(), R"({"method":"getblockcount","params":[],"id":1})""\n");
+ - ]
932 [ + - + - : 1 : BOOST_CHECK_EQUAL(requests.front()->GetPeer().ToStringAddrPort(), "5.5.5.5:6789");
+ - + - ]
933 : :
934 : : // Inspect the connection pointed to from the request
935 [ - + ]: 1 : client = requests.front()->GetClient();
936 [ + - + - : 2 : BOOST_REQUIRE(client);
+ - ]
937 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(client->GetOrigin(), "5.5.5.5:6789");
938 : :
939 : : // Respond to request
940 [ + - ]: 1 : requests.front()->WriteReply(HTTP_OK, "874140\n");
941 : :
942 [ + - ]: 1 : break;
943 : : }
944 : 0 : }
945 [ # # ]: 0 : std::this_thread::sleep_for(10ms);
946 [ # # # # ]: 0 : BOOST_REQUIRE(--attempts > 0);
947 : : }
948 : :
949 : : // Check the sent response from the mock client at the other end of the mock socket
950 : 1 : constexpr std::string_view expected_response{
951 : : "HTTP/1.1 200 OK\r\n"
952 : : "Date: Wed, 11 Dec 2024 00:47:09 GMT\r\n"
953 : : "Content-Length: 7\r\n"
954 : : "Content-Type: text/html; charset=ISO-8859-1\r\n"
955 : : "Connection: close\r\n"
956 : : "\r\n"
957 : : "874140\n"};
958 [ + - ]: 1 : std::string actual;
959 [ + - ]: 1 : actual.reserve(expected_response.length());
960 : : // Wait up to one minute for all the bytes to appear in the "send" pipe.
961 : 1 : char buf[0x10000] = {};
962 : 1 : attempts = 6000;
963 [ + - ]: 1 : while (attempts > 0)
964 : : {
965 [ + - ]: 1 : ssize_t bytes_read = mock_client_socket_pipes->send.GetBytes(buf, sizeof(buf), 0);
966 [ + - ]: 1 : if (bytes_read > 0) {
967 [ + - ]: 1 : actual.append(buf, bytes_read);
968 [ - + - + ]: 1 : if (actual.length() >= expected_response.length()) {
969 : : break;
970 : : }
971 : : }
972 [ # # ]: 0 : std::this_thread::sleep_for(10ms);
973 : 0 : --attempts;
974 : : }
975 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(actual, expected_response);
976 : :
977 : : // Wait up to one minute for connection to be automatically closed, because
978 : : // keep-alive was not set by the client and we are done responding to their request.
979 : 1 : attempts = 6000;
980 : 1 : while (server.GetConnectionsCount() != 0) {
981 [ + - ]: 5 : std::this_thread::sleep_for(10ms);
982 [ + - + - : 11 : BOOST_REQUIRE(--attempts > 0);
+ + ]
983 : : }
984 : :
985 : : // Stop the I/O loop and shutdown
986 [ + - ]: 1 : server.InterruptNet();
987 : : // Wait for I/O loop to finish, after all connected sockets are closed
988 [ + - ]: 1 : server.JoinSocketsThreads();
989 : : // Close all listening sockets
990 [ + - ]: 1 : server.StopListening();
991 [ + - + - ]: 3 : }
992 : :
993 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(http_socket_error_tests)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
994 : : {
995 : : // Create a tiny threadpool for the HTTPRequest handler
996 [ + - ]: 1 : ThreadPool workers("http");
997 [ + - ]: 1 : workers.Start(1);
998 : :
999 : : // Hard-code the server's request handler to respond to each request with
1000 : : // an incremented block count. Handle the replies in the worker thread.
1001 : 1 : std::atomic<int> height{0};
1002 [ + - ]: 4 : HTTPServer server{[&](std::shared_ptr<HTTPRequest> req) {
1003 [ + - - - ]: 3 : auto item = [req, &height]() {
1004 : 3 : const int h = height.fetch_add(1);
1005 [ - + + - ]: 3 : req->WriteReply(HTTP_OK, strprintf("height: %d\n", h));
1006 : 3 : };
1007 : : // Can't call BOOST_REQUIRE from worker thread
1008 [ + - - + ]: 6 : Assert(workers.Submit(std::move(item)));
1009 [ + - ]: 4 : }};
1010 [ + - ]: 1 : server.InitHTTPAllowList();
1011 : :
1012 : : // All replies will be the same size
1013 : 1 : static constexpr std::size_t reply_length = std::string_view{
1014 : : "HTTP/1.1 200 OK\r\n"
1015 : : "Date: Thu, 01 Jan 2026 00:00:00 GMT\r\n" // All RFC1123 dates are 29 characters
1016 : : "Content-Length: 10\r\n"
1017 : : "Content-Type: text/html; charset=ISO-8859-1\r\n"
1018 : : "\r\n"
1019 : : "height: 0\n"
1020 : : }.size();
1021 : :
1022 : : /**
1023 : : * A mocked Sock derived from DynSock whose Send() only succeeds when there is more than
1024 : : * one reply being sent (send buffer length > reply_length). Otherwise it returns
1025 : : * a recoverable error (WSAEAGAIN).
1026 : : *
1027 : : * After it sends successfully once, it continues to always succeed.
1028 : : *
1029 : : * Useful for testing "try again" logic around non-blocking socket Send() failures.
1030 : : */
1031 : 1 : class ErrorSock : public DynSock
1032 : : {
1033 : : public:
1034 [ + - ]: 2 : explicit ErrorSock(std::shared_ptr<Pipes> pipes) : DynSock{std::move(pipes)} {}
1035 : 0 : DynSock& operator=(Sock&&) override { AssertUnreachable(); }
1036 : :
1037 : 338 : ssize_t Send(const void* buf, size_t len, int flags) const override
1038 : : {
1039 [ + + + + ]: 338 : if (len <= reply_length && !m_have_sent) {
1040 : : #ifdef WIN32
1041 : : WSASetLastError(WSAEWOULDBLOCK);
1042 : : #else
1043 : 336 : errno = WSAEAGAIN;
1044 : : #endif
1045 : 336 : return -1;
1046 : : } else {
1047 : 2 : m_have_sent = true;
1048 : 2 : return DynSock::Send(buf, len, flags);
1049 : : }
1050 : : }
1051 : :
1052 : : mutable bool m_have_sent{false};
1053 : : };
1054 : :
1055 : : // Simpler server startup than the last test
1056 [ + - + - : 2 : CService addr_bind{Lookup("0.0.0.0", /*portDefault=*/0, /*fAllowLookup=*/false).value()};
+ - ]
1057 [ + - + - : 2 : BOOST_REQUIRE(server.BindAndStartListening(addr_bind));
+ - + - ]
1058 [ + - ]: 1 : server.StartSocketsThreads();
1059 : :
1060 : : // Prepare initial requests
1061 : 1 : int num_requests = 2;
1062 : : // Use keep-alive so the server holds the connection open for all requests.
1063 [ + - ]: 1 : std::string keepalive_request{full_request};
1064 [ + - ]: 1 : keepalive_request.replace(keepalive_request.find("Connection: close"), 17, "Connection: keep-alive");
1065 : : // Combine all requests so they are read from the socket on a single iteration of the I/O loop
1066 : 1 : std::string all_requests;
1067 [ + + ]: 3 : for (int i = 0; i < num_requests; i++) {
1068 [ - + ]: 4 : all_requests += keepalive_request;
1069 : : }
1070 : :
1071 : : // Watch the log messages to ensure that the first two replies were sent
1072 : : // together. This indicates the non-optimistic send path was used
1073 : : // because a reply was already sitting in the send buffer when a second reply
1074 : : // was added.
1075 [ + - ]: 1 : DebugLogHelper find_two_replies{strprintf("Sent %d bytes to client", reply_length * 2),
1076 : 1 : [&](const std::string* s) {
1077 : : return true;
1078 [ + - ]: 1 : }};
1079 : : // Last reply should be sent on its own by optimistic send path, because
1080 : : // the send buffer was empty when the reply was written.
1081 [ + - ]: 1 : DebugLogHelper find_one_reply{strprintf("Sent %d bytes to client", reply_length),
1082 : 1 : [&](const std::string* s) {
1083 : : return true;
1084 [ + - ]: 1 : }};
1085 : :
1086 : : // Connect the ErrorSock as mock client with the preloaded data and get a handle on the I/O pipes
1087 : 1 : std::shared_ptr<ErrorSock::Pipes> mock_client_socket_pipes{
1088 [ + - ]: 1 : ConnectClient<ErrorSock>(std::as_bytes(std::span(all_requests)))
1089 [ - + + - ]: 1 : };
1090 : :
1091 : : // Wait up to one minute for the last reply from the server
1092 : 1 : std::string actual;
1093 : 1 : char buf[0x10000] = {};
1094 : 1 : int attempts = 6000;
1095 [ + - ]: 7 : while (attempts > 0)
1096 : : {
1097 [ + - ]: 7 : ssize_t bytes_read = mock_client_socket_pipes->send.GetBytes(buf, sizeof(buf), 0);
1098 [ + + ]: 7 : if (bytes_read > 0) {
1099 [ + - ]: 1 : actual.append(buf, bytes_read);
1100 [ + - - + ]: 2 : if (actual.find(strprintf("height: %d", num_requests - 1)) != std::string::npos) {
1101 : : break;
1102 : : }
1103 : : }
1104 [ + - ]: 6 : std::this_thread::sleep_for(10ms);
1105 : 6 : --attempts;
1106 : : }
1107 : :
1108 : : // Send the third request.
1109 : : // If there was a race between WriteReply() in the worker thread setting m_send_ready=true
1110 : : // and SocketHandlerConnected() in the I/O thread flushing the send buffer,
1111 : : // then the socket would be stuck in write mode with nothing to write,
1112 : : // the server would never read from the socket, and this request would time out.
1113 : : // Wait a second to ensure both the worker thread and I/O thread are idle.
1114 : : // If we send the next request too soon it might get accepted by the server before
1115 : : // it gets wedged shut.
1116 [ + - ]: 1 : std::this_thread::sleep_for(1000ms);
1117 [ - + + - ]: 1 : mock_client_socket_pipes->recv.PushBytes(keepalive_request.data(), keepalive_request.size());
1118 : 2 : num_requests++;
1119 : :
1120 : : // Wait up to one minute for reply
1121 : : attempts = 6000;
1122 [ + - ]: 2 : while (attempts > 0)
1123 : : {
1124 [ + - ]: 2 : ssize_t bytes_read = mock_client_socket_pipes->send.GetBytes(buf, sizeof(buf), 0);
1125 [ + + ]: 2 : if (bytes_read > 0) {
1126 [ + - ]: 1 : actual.append(buf, bytes_read);
1127 [ + - - + ]: 2 : if (actual.find(strprintf("height: %d", num_requests - 1)) != std::string::npos) {
1128 : : break;
1129 : : }
1130 : : }
1131 [ + - ]: 1 : std::this_thread::sleep_for(10ms);
1132 : 1 : --attempts;
1133 : : }
1134 : :
1135 : : // All replies were received
1136 [ + + ]: 4 : for (int i = 0; i < num_requests; i++) {
1137 [ + - + - : 9 : BOOST_REQUIRE(actual.find(strprintf("height: %d", i)) != std::string::npos);
+ - ]
1138 : : }
1139 : :
1140 : : // Close the keep-alive connection
1141 [ + - ]: 1 : server.DisconnectAllClients();
1142 : :
1143 [ + - ]: 1 : workers.Stop();
1144 : :
1145 [ + - ]: 1 : server.InterruptNet();
1146 [ + - ]: 1 : server.JoinSocketsThreads();
1147 [ + - ]: 1 : server.StopListening();
1148 [ + - ]: 2 : }
1149 : :
1150 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(http_server_rejects_disallowed_client_before_read)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
1151 : : {
1152 : : // DynSock reports accepted connections as coming from 5.5.5.5.
1153 [ + - + - ]: 2 : gArgs.ForceSetArg("-rpcallowip", "4.4.4.4");
1154 : :
1155 : 1 : std::atomic_bool request_dispatched{false};
1156 [ + - ]: 1 : HTTPServer server{[&request_dispatched](std::unique_ptr<HTTPRequest>&&) {
1157 : 0 : request_dispatched = true;
1158 [ + - ]: 1 : }};
1159 [ + - + - : 2 : BOOST_REQUIRE(server.InitHTTPAllowList());
+ - + - ]
1160 : :
1161 [ + - + - : 2 : CService addr_bind{Lookup("0.0.0.0", /*portDefault=*/0, /*fAllowLookup=*/false).value()};
+ - ]
1162 [ + - + - : 2 : BOOST_REQUIRE(server.BindAndStartListening(addr_bind));
+ - + - ]
1163 [ + - ]: 1 : server.StartSocketsThreads();
1164 : :
1165 : : // Queue a complete request; the server should never read from it.
1166 : 1 : std::shared_ptr<DynSock::Pipes> client_pipes{
1167 [ + - ]: 1 : ConnectClient(std::as_bytes(std::span(full_request)))};
1168 : :
1169 : : // Wait for the socket to close with an EOF (bytes_read == 0)
1170 : : // 'bytes_read > 0' means the server replied to the prohibited client
1171 : : // 'bytes_read < 0' is an error, expected until the connection is fully processed by the I/O loop
1172 : 1 : ssize_t bytes_read{};
1173 : 1 : char buf[0x10000]{};
1174 [ + - ]: 2 : for (int attempts{0}; attempts != 1'000; ++attempts) {
1175 [ + - ]: 2 : bytes_read = client_pipes->send.GetBytes(&buf, sizeof(buf), MSG_PEEK);
1176 [ + + ]: 2 : if (bytes_read >= 0) break;
1177 [ + - ]: 1 : std::this_thread::sleep_for(10ms);
1178 : : }
1179 : :
1180 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(bytes_read, 0);
1181 [ + - + - : 2 : BOOST_CHECK(!request_dispatched);
+ - ]
1182 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(server.GetConnectionsCount(), 0);
1183 : :
1184 [ + - ]: 1 : server.InterruptNet();
1185 [ + - ]: 1 : server.JoinSocketsThreads();
1186 [ + - ]: 1 : server.StopListening();
1187 : :
1188 : : // 'recv' buffer still holds the client's request untouched which
1189 : : // proves the server never called Recv()
1190 [ + - ]: 1 : const ssize_t recv_bytes{client_pipes->recv.GetBytes(&buf, sizeof(buf))};
1191 [ + - + - ]: 1 : BOOST_REQUIRE_EQUAL(recv_bytes, static_cast<ssize_t>(full_request.size()));
1192 [ + - + - : 1 : BOOST_CHECK_EQUAL(std::string_view(buf, recv_bytes), full_request);
+ - ]
1193 : 1 : }
1194 : :
1195 : : BOOST_AUTO_TEST_SUITE_END()
|