Branch data Line data Source code
1 : : // Copyright (c) 2015-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 <bitcoin-build-config.h> // IWYU pragma: keep
6 : :
7 : : #include <httpserver.h>
8 : :
9 : : #include <chainparamsbase.h>
10 : : #include <common/args.h>
11 : : #include <common/messages.h>
12 : : #include <common/url.h>
13 : : #include <compat/compat.h>
14 : : #include <logging.h>
15 : : #include <netbase.h>
16 : : #include <node/interface_ui.h>
17 : : #include <rpc/protocol.h>
18 : : #include <span.h>
19 : : #include <sync.h>
20 : : #include <util/check.h>
21 : : #include <util/signalinterrupt.h>
22 : : #include <util/sock.h>
23 : : #include <util/strencodings.h>
24 : : #include <util/thread.h>
25 : : #include <util/threadnames.h>
26 : : #include <util/threadpool.h>
27 : : #include <util/time.h>
28 : : #include <util/translation.h>
29 : :
30 : : #include <condition_variable>
31 : : #include <cstdio>
32 : : #include <cstdlib>
33 : : #include <memory>
34 : : #include <optional>
35 : : #include <span>
36 : : #include <string>
37 : : #include <string_view>
38 : : #include <thread>
39 : : #include <unordered_map>
40 : : #include <vector>
41 : :
42 : : #include <sys/types.h>
43 : : #include <sys/stat.h>
44 : :
45 : : //! The set of sockets cannot be modified while waiting, so
46 : : //! the sleep time needs to be small to avoid new sockets stalling.
47 : : static constexpr auto SELECT_TIMEOUT{50ms};
48 : :
49 : : //! Explicit alias for setting socket option methods.
50 : : static constexpr int SOCKET_OPTION_TRUE{1};
51 : :
52 : : using common::InvalidPortErrMsg;
53 : : using util::LineReader;
54 : : using namespace bitcoin_http;
55 : :
56 : 3811 : struct HTTPPathHandler
57 : : {
58 : 2522 : HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler):
59 [ - + + - ]: 5044 : prefix(_prefix), exactMatch(_exactMatch), handler(_handler)
60 : : {
61 : 2522 : }
62 : : std::string prefix;
63 : : bool exactMatch;
64 : : HTTPRequestHandler handler;
65 : : };
66 : :
67 : : /** HTTP module state */
68 : :
69 : : static std::unique_ptr<HTTPServer> g_http_server{nullptr};
70 : : //! Handlers for (sub)paths
71 : : static GlobalMutex g_httppathhandlers_mutex;
72 : : static std::vector<HTTPPathHandler> pathHandlers GUARDED_BY(g_httppathhandlers_mutex);
73 : : /// \anchor http_pool
74 : : //! Http thread pool - future: encapsulate in HttpContext
75 : : static ThreadPool g_threadpool_http("http");
76 : : static int g_max_queue_depth{100};
77 : :
78 : : /** Check if a network address is allowed to access the HTTP server */
79 : 4861 : bool HTTPServer::ClientAllowed(const CNetAddr& netaddr) const
80 : : {
81 [ + - ]: 4861 : if (!netaddr.IsValid())
82 : : return false;
83 [ + + ]: 4881 : for(const CSubNet& subnet : m_allow_subnets)
84 [ + + ]: 4879 : if (subnet.Match(netaddr))
85 : : return true;
86 : : return false;
87 : : }
88 : :
89 : : /** Initialize ACL list for HTTP server */
90 : 1248 : bool HTTPServer::InitHTTPAllowList()
91 : : {
92 : : // Must be run before StartSocketThreads() because ThreadSocketHandler()
93 : : // will check m_allow_subnets from the I/O thread.
94 : 1248 : Assume(!m_thread_socket_handler.joinable());
95 : :
96 : 1248 : m_allow_subnets.clear();
97 [ + - + - : 3744 : m_allow_subnets.emplace_back(LookupHost("127.0.0.1", false).value(), 8); // always allow IPv4 local subnet
+ - ]
98 [ + - + - : 3744 : m_allow_subnets.emplace_back(LookupHost("::1", false).value()); // always allow IPv6 localhost
+ - ]
99 [ + - + + ]: 1258 : for (const std::string& strAllow : gArgs.GetArgs("-rpcallowip")) {
100 [ + - ]: 10 : const CSubNet subnet{LookupSubNet(strAllow)};
101 [ + - - + ]: 10 : if (!subnet.IsValid()) {
102 [ # # ]: 0 : uiInterface.ThreadSafeMessageBox(
103 [ # # ]: 0 : Untranslated(strprintf("Invalid -rpcallowip subnet specification: %s. Valid values are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0), a network/CIDR (e.g. 1.2.3.4/24), all ipv4 (0.0.0.0/0), or all ipv6 (::/0). RFC4193 is allowed only if -cjdnsreachable=0.", strAllow)),
104 [ # # ]: 0 : CClientUIInterface::MSG_ERROR);
105 : 0 : return false;
106 : : }
107 [ + - ]: 10 : m_allow_subnets.push_back(subnet);
108 : 1258 : }
109 : 1248 : std::string strAllowed;
110 [ + + ]: 3754 : for (const CSubNet& subnet : m_allow_subnets)
111 [ + - - + ]: 7518 : strAllowed += subnet.ToString() + " ";
112 [ + - + + : 1248 : LogDebug(BCLog::HTTP, "Allowing HTTP connections from: %s\n", strAllowed);
+ - ]
113 : 1248 : return true;
114 : 1248 : }
115 : :
116 : : /** HTTP request method as string - use for logging only */
117 : 228711 : std::string_view RequestMethodString(HTTPRequestMethod m)
118 : : {
119 [ + + - - : 228711 : switch (m) {
+ - ]
120 : 897 : using enum HTTPRequestMethod;
121 : 897 : case GET: return "GET";
122 : 227809 : case POST: return "POST";
123 : 0 : case HEAD: return "HEAD";
124 : 0 : case PUT: return "PUT";
125 : 5 : case UNKNOWN: return "unknown";
126 : : } // no default case, so the compiler can warn about missing cases
127 : 0 : assert(false);
128 : : }
129 : :
130 : 861 : static void WriteNoStoreErrorReply(HTTPRequest& req, HTTPStatusCode status, std::string_view reply = {})
131 : : {
132 [ + - + - ]: 1722 : req.WriteHeader("Cache-Control", "no-store");
133 : 861 : req.WriteReply(status, reply);
134 : 861 : }
135 : :
136 : 228712 : static void MaybeDispatchRequestToWorker(std::shared_ptr<HTTPRequest> hreq)
137 : : {
138 : : // Early reject unknown HTTP methods
139 [ + + ]: 228712 : if (hreq->GetRequestMethod() == HTTPRequestMethod::UNKNOWN) {
140 [ + - + - : 5 : LogDebug(BCLog::HTTP, "HTTP request from %s rejected: Unknown HTTP request method\n",
+ - ]
141 : : hreq->GetPeer().ToStringAddrPort());
142 : 5 : WriteNoStoreErrorReply(*hreq, HTTP_BAD_METHOD);
143 : 5 : return;
144 : : }
145 : :
146 : : // Find registered handler for prefix
147 [ - + ]: 228707 : std::string strURI = hreq->GetURI();
148 [ + - ]: 228707 : std::string path;
149 [ + - ]: 228707 : LOCK(g_httppathhandlers_mutex);
150 : 228707 : std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin();
151 : 228707 : std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end();
152 [ + + ]: 256326 : for (; i != iend; ++i) {
153 : 256314 : bool match = false;
154 [ + + ]: 256314 : if (i->exactMatch)
155 : 228707 : match = (strURI == i->prefix);
156 : : else
157 [ - + - + ]: 27607 : match = strURI.starts_with(i->prefix);
158 [ + + ]: 256314 : if (match) {
159 [ - + + - ]: 228695 : path = strURI.substr(i->prefix.size());
160 : 228695 : break;
161 : : }
162 : : }
163 : :
164 : : // Dispatch to worker thread
165 [ + + ]: 228707 : if (i != iend) {
166 [ + - + + ]: 228695 : if (static_cast<int>(g_threadpool_http.WorkQueueSize()) >= g_max_queue_depth) {
167 [ + - ]: 826 : LogWarning("Request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting");
168 [ + - ]: 826 : WriteNoStoreErrorReply(*hreq, HTTP_SERVICE_UNAVAILABLE, "Work queue depth exceeded");
169 : : return;
170 : : }
171 : :
172 [ + - ]: 227869 : auto item = [req = hreq, in_path = std::move(path), fn = i->handler]() {
173 [ + - ]: 227869 : std::string err_msg;
174 : 227869 : try {
175 [ + - ]: 227869 : fn(req.get(), in_path);
176 : 227869 : return;
177 [ - - ]: 0 : } catch (const std::exception& e) {
178 [ - - - - ]: 0 : LogWarning("Unexpected error while processing request for '%s'. Error msg: '%s'", req->GetURI(), e.what());
179 [ - - ]: 0 : err_msg = e.what();
180 : 0 : } catch (...) {
181 [ - - - - ]: 0 : LogWarning("Unknown error while processing request for '%s'", req->GetURI());
182 [ - - ]: 0 : err_msg = "unknown error";
183 [ - - ]: 0 : }
184 : : // Reply so the client doesn't hang waiting for the response.
185 [ - - - - : 0 : req->WriteHeader("Connection", "close");
- - ]
186 : : // TODO: Implement specific error formatting for the REST and JSON-RPC servers responses.
187 [ - - - - ]: 0 : WriteNoStoreErrorReply(*req, HTTP_INTERNAL_SERVER_ERROR, err_msg);
188 [ + - ]: 455738 : };
189 : :
190 [ - + ]: 227869 : if (auto res = g_threadpool_http.Submit(std::move(item)); !res.has_value()) {
191 : 0 : Assume(hreq.use_count() == 1); // ensure request will be deleted
192 : : // Both SubmitError::Inactive and SubmitError::Interrupted mean shutdown
193 [ # # ]: 0 : LogWarning("HTTP request rejected during server shutdown: '%s'", SubmitErrorString(res.error()));
194 [ # # ]: 0 : WriteNoStoreErrorReply(*hreq, HTTP_SERVICE_UNAVAILABLE, "Request rejected during server shutdown");
195 : 0 : return;
196 : 0 : }
197 : 227869 : } else {
198 [ + - ]: 12 : WriteNoStoreErrorReply(*hreq, HTTP_NOT_FOUND);
199 : : }
200 : 228707 : }
201 : :
202 : 0 : static void RejectRequest(std::unique_ptr<HTTPRequest> hreq)
203 : : {
204 [ # # ]: 0 : LogDebug(BCLog::HTTP, "Rejecting request while shutting down");
205 : 0 : WriteNoStoreErrorReply(*hreq, HTTP_SERVICE_UNAVAILABLE);
206 : 0 : }
207 : :
208 : 1245 : static std::vector<std::pair<std::string, uint16_t>> GetBindAddresses()
209 : : {
210 : 2490 : uint16_t http_port{static_cast<uint16_t>(gArgs.GetIntArg("-rpcport", BaseParams().RPCPort()))};
211 : 1245 : std::vector<std::pair<std::string, uint16_t>> endpoints;
212 : :
213 : : // Determine what addresses to bind to
214 : : // To prevent misconfiguration and accidental exposure of the RPC
215 : : // interface, require -rpcallowip and -rpcbind to both be specified
216 : : // together. If either is missing, ignore both values, bind to localhost
217 : : // instead, and log warnings.
218 [ + - + - : 2504 : if (gArgs.GetArgs("-rpcallowip").empty() || gArgs.GetArgs("-rpcbind").empty()) { // Default to loopback if not allowing external IPs
+ + + - +
- + - + +
+ + - - -
- - - ]
219 [ + - ]: 1238 : endpoints.emplace_back("::1", http_port);
220 [ + - ]: 1238 : endpoints.emplace_back("127.0.0.1", http_port);
221 [ + - + - : 1238 : if (!gArgs.GetArgs("-rpcallowip").empty()) {
- + ]
222 [ # # ]: 0 : LogWarning("Option -rpcallowip was specified without -rpcbind; this doesn't usually make sense");
223 : : }
224 [ + - + - : 1238 : if (!gArgs.GetArgs("-rpcbind").empty()) {
- + ]
225 [ # # ]: 0 : LogWarning("Option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect");
226 : : }
227 : : } else { // Specific bind addresses
228 [ + - + - : 25 : for (const std::string& strRPCBind : gArgs.GetArgs("-rpcbind")) {
+ + ]
229 : 11 : uint16_t port{http_port};
230 [ - + ]: 11 : std::string host;
231 [ - + + - : 11 : if (!SplitHostPort(strRPCBind, port, host)) {
- + ]
232 [ # # # # : 0 : LogError("%s\n", InvalidPortErrMsg("-rpcbind", strRPCBind).original);
# # ]
233 : 0 : return {}; // empty
234 : : }
235 [ + - ]: 11 : endpoints.emplace_back(host, port);
236 : 18 : }
237 : : }
238 : 1245 : return endpoints;
239 : 1245 : }
240 : :
241 : 2522 : void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
242 : : {
243 [ + + ]: 2522 : LogDebug(BCLog::HTTP, "Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
244 : 2522 : LOCK(g_httppathhandlers_mutex);
245 [ + - ]: 2522 : pathHandlers.emplace_back(prefix, exactMatch, handler);
246 : 2522 : }
247 : :
248 : 20704 : void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
249 : : {
250 : 20704 : LOCK(g_httppathhandlers_mutex);
251 : 20704 : std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
252 : 20704 : std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
253 [ + + ]: 20704 : for (; i != iend; ++i)
254 [ + - - + ]: 2522 : if (i->prefix == prefix && i->exactMatch == exactMatch)
255 : : break;
256 [ + + ]: 20704 : if (i != iend)
257 : : {
258 [ + - + + : 2522 : LogDebug(BCLog::HTTP, "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
+ - ]
259 : 2522 : pathHandlers.erase(i);
260 : : }
261 : 20704 : }
262 : :
263 : : using util::Split;
264 : :
265 : 1079847 : std::optional<std::string> HTTPHeaders::FindFirst(const std::string_view key) const
266 : : {
267 [ + + ]: 5723225 : for (const auto& item : m_headers) {
268 [ - + + + ]: 5099828 : if (CaseInsensitiveEqual(key, item.first)) {
269 [ - + ]: 912900 : return item.second;
270 : : }
271 : : }
272 : 623397 : return std::nullopt;
273 : : }
274 : :
275 : 394745 : std::vector<std::string_view> HTTPHeaders::FindAll(const std::string_view key) const
276 : : {
277 : 394745 : std::vector<std::string_view> ret;
278 [ + + ]: 2757411 : for (const auto& item : m_headers) {
279 [ - + + - : 2362666 : if (CaseInsensitiveEqual(key, item.first)) {
+ + ]
280 [ - + + - ]: 2362666 : ret.push_back(item.second);
281 : : }
282 : : }
283 : 394745 : return ret;
284 : 0 : }
285 : :
286 : 2059716 : void HTTPHeaders::Write(std::string&& key, std::string&& value)
287 : : {
288 : 2059716 : m_headers.emplace_back(std::move(key), std::move(value));
289 : 2059716 : }
290 : :
291 : 1016 : void HTTPHeaders::RemoveAll(std::string_view key)
292 : : {
293 : 1016 : auto moved = std::ranges::remove_if(m_headers, [key] (auto& pair) {
294 [ - + ]: 3056 : return CaseInsensitiveEqual(key, pair.first);
295 : : });
296 : 1016 : m_headers.erase(moved.begin(), moved.end());
297 : 1016 : }
298 : :
299 : 228782 : bool HTTPHeaders::Read(util::LineReader& reader, bool write)
300 : : {
301 : : // Headers https://httpwg.org/specs/rfc9110.html#rfc.section.6.3
302 : : // A sequence of Field Lines https://httpwg.org/specs/rfc9110.html#rfc.section.5.2
303 : 228782 : size_t start{reader.Consumed()};
304 [ + + ]: 1599600 : while (auto maybe_line = reader.ReadLine()) {
305 [ + + + - ]: 1599586 : if (reader.Consumed() - start + m_consumed > MAX_HEADERS_SIZE) throw std::runtime_error("HTTP headers exceed size limit");
306 : :
307 [ + + ]: 1599582 : const std::string_view& line = *maybe_line;
308 : :
309 : : // An empty line indicates end of the headers section https://www.rfc-editor.org/rfc/rfc2616#section-4
310 [ + + ]: 1599582 : if (line.empty()) {
311 : : // Ensure all headers are accounted for in case there is a chunked trailer
312 : 228753 : m_consumed += reader.Consumed() - start;
313 : 228753 : return true;
314 : : }
315 : :
316 : : // "Field values containing CR, LF, or NUL characters are invalid and dangerous"
317 : : // https://httpwg.org/specs/rfc9110.html#rfc.section.5.5
318 : : // A sender MUST NOT generate a bare CR (a CR character not immediately followed by LF)
319 : : // within any protocol elements other than the content.
320 : : // A recipient of such a bare CR MUST consider that element to be invalid...
321 : : // https://httpwg.org/specs/rfc9112.html#rfc.section.2.2
322 [ + + + - ]: 1370829 : if (line.find_first_of("\r\n\0", 0, 3) != std::string_view::npos) throw std::runtime_error("Header contains invalid character");
323 : :
324 : : // Header line must have at least one ":"
325 : : // keys are not allowed to have delimiters like ":" but values are
326 : : // https://httpwg.org/specs/rfc9110.html#rfc.section.5.6.2
327 : 1370826 : const size_t pos{line.find(':')};
328 [ + + + - ]: 1370826 : if (pos == std::string_view::npos) throw std::runtime_error("HTTP header missing colon (:)");
329 : :
330 : : // Whitespace is strictly not allowed in the field-name (key)
331 : : // https://www.rfc-editor.org/rfc/rfc9110.html#section-5.6.2
332 : 1370821 : std::string_view key = line.substr(0, pos);
333 [ + + + - ]: 1370821 : if (key.find_first_of(" \t\n\r\f\v") != std::string_view::npos) throw std::runtime_error("Invalid header field-name contains whitespace");
334 : : // Whitespace is optional in the value and can be trimmed
335 : 1370819 : std::string value = util::TrimString(std::string_view(line).substr(pos + 1));
336 : :
337 : : // Header keys are Field Names: https://httpwg.org/specs/rfc9110.html#fields.names
338 : : // which consist of "tokens": https://httpwg.org/specs/rfc9110.html#rfc.section.5.6.2
339 : : // that can not be empty.
340 [ + + + - ]: 1370819 : if (key.empty()) throw std::runtime_error("Empty HTTP header name");
341 : :
342 [ + + ]: 1370818 : if (write) {
343 [ + - + - ]: 2741630 : Write(std::string(key), std::move(value));
344 : : }
345 : 1370818 : }
346 : :
347 : : // We have not received all the request headers yet.
348 : : // Keep track of how much data we have already consumed to enforce
349 : : // the total limit over multiple read operations.
350 : 14 : m_consumed += reader.Consumed() - start;
351 : :
352 : 14 : return false;
353 : : }
354 : :
355 : 228737 : std::string HTTPHeaders::Stringify() const
356 : : {
357 : 228737 : std::string out;
358 [ + - + + ]: 917627 : for (const auto& [key, value] : m_headers) {
359 [ + - + - : 2066670 : out += key + ": " + value + "\r\n";
- + ]
360 : : }
361 : :
362 : : // Headers are terminated by an empty line
363 [ + - ]: 228737 : out += "\r\n";
364 : :
365 : 228737 : return out;
366 : 0 : }
367 : :
368 : 228736 : std::string HTTPResponse::StringifyHeaders() const
369 : : {
370 : 228736 : return strprintf("HTTP/%d.%d %d %s\r\n%s",
371 : 228736 : version.major,
372 : 228736 : version.minor,
373 : 228736 : status,
374 : 228736 : HTTPStatusReasonString(status),
375 [ + - ]: 457472 : headers.Stringify());
376 : : }
377 : :
378 : 228773 : bool HTTPRequest::LoadControlData(LineReader& reader)
379 : : {
380 : 228773 : auto maybe_line = reader.ReadLine();
381 [ + - ]: 228771 : if (!maybe_line) return false;
382 [ + + ]: 228771 : const std::string_view& request_line = *maybe_line;
383 : :
384 : : // Request Line aka Control Data https://httpwg.org/specs/rfc9110.html#rfc.section.6.2
385 : : // Three words separated by spaces, terminated by \n or \r\n
386 [ + + + - ]: 228771 : if (request_line.length() < MIN_REQUEST_LINE_LENGTH) throw std::runtime_error("HTTP request line too short");
387 : :
388 : : // NUL is not a valid tchar and would silently truncate
389 : : // C-string-based parsers rather than being rejected as malformed.
390 : : // tchar: https://www.rfc-editor.org/info/rfc7230/#section-3.2.6
391 [ + + + - ]: 228767 : if (request_line.find('\0') != std::string_view::npos) throw std::runtime_error("Invalid request line contains NUL");
392 : :
393 : 228765 : const std::vector<std::string_view> parts{Split<std::string_view>(request_line, " ")};
394 [ - + + + : 228765 : if (parts.size() != 3) throw std::runtime_error("HTTP request line malformed");
+ - ]
395 : :
396 [ + + ]: 228764 : if (parts[0] == "GET") {
397 : 924 : m_method = HTTPRequestMethod::GET;
398 [ + + ]: 227840 : } else if (parts[0] == "POST") {
399 : 227835 : m_method = HTTPRequestMethod::POST;
400 [ - + ]: 5 : } else if (parts[0] == "HEAD") {
401 : 0 : m_method = HTTPRequestMethod::HEAD;
402 [ - + ]: 5 : } else if (parts[0] == "PUT") {
403 : 0 : m_method = HTTPRequestMethod::PUT;
404 : : } else {
405 : 5 : m_method = HTTPRequestMethod::UNKNOWN;
406 : : }
407 : :
408 [ + - ]: 228764 : m_target = parts[1];
409 : :
410 [ + + + - ]: 228764 : if (parts[2].rfind("HTTP/") != 0) throw std::runtime_error("HTTP request line malformed");
411 : :
412 : : // Version is exactly two decimal digits separated by a decimal point
413 : : // https://httpwg.org/specs/rfc9110.html#rfc.section.2.5
414 [ + - + - ]: 228763 : const std::vector<std::string_view> version_parts{Split<std::string_view>(parts[2].substr(5), ".")};
415 [ - + + + : 228763 : if (version_parts.size() != 2) throw std::runtime_error("HTTP request line malformed");
+ - ]
416 [ + + + + : 228762 : if (version_parts[0].size() != 1 || version_parts[1].size() != 1) throw std::runtime_error("HTTP bad version");
+ - ]
417 : 228760 : auto major = ToIntegral<uint8_t>(version_parts[0]);
418 : 228760 : auto minor = ToIntegral<uint8_t>(version_parts[1]);
419 [ + - + + : 228760 : if (!major || !minor || major != 1 || minor > 9) throw std::runtime_error("HTTP bad version");
+ + + - +
- ]
420 : 228756 : m_version.major = major.value();
421 : 228756 : m_version.minor = minor.value();
422 : :
423 : 228756 : return true;
424 : 228763 : }
425 : :
426 : 228762 : bool HTTPRequest::LoadHeaders(LineReader& reader)
427 : : {
428 : 228762 : return m_headers.Read(reader);
429 : : }
430 : :
431 : 395361 : bool HTTPRequest::LoadBody(LineReader& reader)
432 : : {
433 : : // https://httpwg.org/specs/rfc9112.html#message.body
434 : 395361 : auto transfer_encoding_header = m_headers.FindFirst("Transfer-Encoding");
435 [ + + - + : 395978 : if (transfer_encoding_header && ToLower(transfer_encoding_header.value()) == "chunked") {
+ - + - +
+ ]
436 : : // Transfer-Encoding: https://datatracker.ietf.org/doc/html/rfc7230.html#section-3.3.1
437 : : // Chunked Transfer Coding: https://datatracker.ietf.org/doc/html/rfc7230.html#section-4.1
438 : : // see evhttp_handle_chunked_read() in libevent http.c
439 [ + - + + ]: 1230 : while (reader.Remaining() > 0) {
440 [ + + ]: 630 : if (!m_chunk_size) {
441 [ + - ]: 33 : auto maybe_chunk_size = reader.ReadLine();
442 [ + - ]: 33 : if (!maybe_chunk_size) return false;
443 : :
444 : : // Allow (but ignore) Chunk Extensions
445 : : // See https://www.rfc-editor.org/rfc/rfc9112.html#name-chunk-extensions
446 [ + + ]: 33 : std::string_view chunk_size_noext{maybe_chunk_size.value()};
447 : 33 : const auto semicolon_pos = chunk_size_noext.find(';');
448 [ + + ]: 33 : if (semicolon_pos != chunk_size_noext.npos) {
449 : 3 : chunk_size_noext.remove_suffix(chunk_size_noext.size() - semicolon_pos);
450 : : }
451 : :
452 [ + - ]: 33 : m_chunk_size = ToIntegral<uint64_t>(util::TrimStringView(chunk_size_noext), /*base=*/16);
453 [ + + + - ]: 33 : if (!m_chunk_size) throw std::runtime_error("Cannot parse chunk length value");
454 : :
455 [ - + + - : 32 : if ((m_body.size() > MAX_BODY_SIZE) ||
+ + ]
456 [ + + ]: 32 : (*m_chunk_size > MAX_BODY_SIZE - m_body.size()))
457 [ + - ]: 3 : throw ContentTooLargeError("Chunk will exceed max body size");
458 : : }
459 : :
460 : : // We either just read the chunk size, or we have it saved
461 : : // from a prior I/O loop iteration
462 [ + + ]: 626 : Assume(m_chunk_size);
463 : :
464 : : // Last chunk has size 0
465 [ + + ]: 626 : if (*m_chunk_size == 0) {
466 : : // Validate Chunked Trailer section, which is used for
467 : : // additional headers sent at the end of the message.
468 : : // Data consumed here is counted towards MAX_HEADERS_SIZE
469 : : // along with the headers we read in the beginning of the request.
470 : : // At this time we ignore and drop these data after validating.
471 : : // See https://httpwg.org/specs/rfc9112.html#rfc.section.7.1.2
472 [ + + ]: 11 : return m_headers.Read(reader, /*write=*/false);
473 : : }
474 : :
475 : : // We have not read the entire chunk from the buffer yet
476 [ + + ]: 615 : if (m_chunk_read < *m_chunk_size) {
477 : : // Get what we can from the buffer
478 [ + - ]: 614 : const uint64_t chunk_need{*m_chunk_size - m_chunk_read};
479 [ + - + + ]: 614 : const uint64_t buffer_has{std::min(chunk_need, static_cast<uint64_t>(reader.Remaining()))};
480 : :
481 : : // Pack [partial] chunk onto body and update state
482 [ + - + - ]: 614 : m_body += reader.ReadLength(buffer_has);
483 : 614 : m_chunk_read += buffer_has;
484 : : }
485 : :
486 : : // Even though every chunk size is explicitly declared,
487 : : // they are still terminated by a CRLF we don't need,
488 : : // just consume it here.
489 [ + + ]: 615 : if (m_chunk_read == *m_chunk_size) {
490 [ + - ]: 23 : auto crlf = reader.ReadLine();
491 [ + + ]: 23 : if (!crlf) {
492 : : // CRLF not found before end of buffer: it has not been received by our socket yet.
493 : : return false;
494 : : }
495 : : // CRLF was found but there was unexpected data after the chunk_sized chunk
496 [ + + + - ]: 22 : if (!crlf.value().empty()) throw std::runtime_error("Improperly terminated chunk");
497 : :
498 : : // Clear state for next chunk
499 [ + - ]: 21 : m_chunk_size.reset();
500 : 21 : m_chunk_read = 0;
501 : : }
502 : : }
503 : :
504 : : // We read all the chunks but never got the last chunk, wait for client to send more
505 : : return false;
506 : : } else {
507 : : // No Content-length or Transfer-Encoding header means no body, see libevent evhttp_get_body()
508 [ + - ]: 394744 : auto content_length_values{m_headers.FindAll("Content-Length")};
509 [ + + ]: 394744 : if (content_length_values.empty()) return true;
510 : :
511 : : // Duplicate Content-Length headers are allowed only if they all have the same value
512 : : // https://www.rfc-editor.org/rfc/rfc7230#section-3.3.3
513 : 393854 : const auto& first_content_length_value{content_length_values[0]};
514 [ - + + + ]: 393855 : for (size_t i = 1; i < content_length_values.size(); ++i) {
515 [ + + + - ]: 3 : if (content_length_values[i] != first_content_length_value) throw std::runtime_error("Differing Content-Length values");
516 : : }
517 : :
518 : 393852 : const auto content_length{ToIntegral<uint64_t>(first_content_length_value)};
519 [ + + + - ]: 393852 : if (!content_length) throw std::runtime_error("Cannot parse Content-Length value");
520 : :
521 [ + + + - ]: 393850 : if (*content_length > MAX_BODY_SIZE) throw ContentTooLargeError("Max body size exceeded");
522 : :
523 : : // A large body may arrive over multiple I/O loop iterations. Copy
524 : : // whatever the buffer has now; m_body's size tracks our progress.
525 [ - + ]: 393848 : const uint64_t body_need{*content_length - m_body.size()};
526 [ + - + + ]: 393848 : const uint64_t buffer_has{std::min(body_need, static_cast<uint64_t>(reader.Remaining()))};
527 : :
528 : : // Pack [partial] body on and update state
529 [ + - + - ]: 393848 : m_body += reader.ReadLength(buffer_has);
530 : :
531 [ - + ]: 393848 : return m_body.size() == *content_length;
532 : 394744 : }
533 : 395349 : }
534 : :
535 : 228738 : void HTTPRequest::WriteReply(HTTPStatusCode status, std::span<const std::byte> reply_body)
536 : : {
537 : 228738 : HTTPResponse res;
538 : :
539 : : // Some response headers are determined in advance and stored in the request
540 : 228738 : res.headers = std::move(m_response_headers);
541 : :
542 : : // Response version matches request version
543 : 228738 : res.version = m_version;
544 : :
545 : : // Add response code
546 : 228738 : res.status = status;
547 : :
548 : : // See libevent evhttp_response_needs_body()
549 : : // Response headers are different if no body is needed
550 : 228738 : bool needs_body{status != HTTP_NO_CONTENT && (status < 100 || status >= 200)};
551 : 228738 : bool needs_content_length{false};
552 : :
553 : 228738 : bool keep_alive{false};
554 : :
555 : : // See libevent evhttp_make_header_response()
556 : : // Expected response headers depend on protocol version
557 [ + - ]: 228738 : if (m_version.major == 1) {
558 : : // HTTP/1.0
559 [ + + ]: 228738 : if (m_version.minor == 0) {
560 [ + - ]: 8 : auto connection_header{m_headers.FindFirst("Connection")};
561 [ - + - - : 8 : if (connection_header && ToLower(connection_header.value()) == "keep-alive") {
- - - - -
+ ]
562 [ # # # # : 0 : res.headers.Write("Connection", "keep-alive");
# # ]
563 : 0 : keep_alive = true;
564 : : // HTTP/1.0 connections are closed by default so EOF is sufficient
565 : : // to indicate end of the body. Adding Content-Length a special case.
566 [ # # ]: 0 : if (needs_body) needs_content_length = true;
567 : : }
568 : 8 : }
569 : :
570 : : // HTTP/1.1
571 [ + + ]: 228738 : if (m_version.minor >= 1) {
572 : 228730 : const int64_t now_seconds{TicksSinceEpoch<std::chrono::seconds>(NodeClock::now())};
573 [ + - + - : 457460 : res.headers.Write("Date", FormatRFC1123DateTime(now_seconds));
+ - ]
574 : :
575 : : // HTTP/1.1 connections are kept alive by default and always require Content-Length.
576 [ + + ]: 228730 : if (needs_body) needs_content_length = true;
577 : :
578 : : // Default for HTTP/1.1
579 : : keep_alive = true;
580 : : }
581 : : }
582 : :
583 [ - + ]: 11 : if (needs_content_length) {
584 [ + - + - : 457454 : res.headers.Write("Content-Length", util::ToString(reply_body.size()));
+ - ]
585 : : }
586 : :
587 [ + + + - : 457473 : if (needs_body && !res.headers.FindFirst("Content-Type")) {
+ + + + ]
588 : : // Default type from libevent evhttp_new_object()
589 [ + - + - : 2008 : res.headers.Write("Content-Type", "text/html; charset=ISO-8859-1");
+ - ]
590 : : }
591 : :
592 [ + - ]: 228738 : auto connection_header{m_headers.FindFirst("Connection")};
593 [ + + - + : 229840 : if (connection_header && ToLower(connection_header.value()) == "close") {
+ - + + +
+ ]
594 : : // Might not exist already but we need to replace it, not append to it
595 [ + - ]: 1015 : res.headers.RemoveAll("Connection");
596 : :
597 [ + - + - : 2030 : res.headers.Write("Connection", "close");
+ - ]
598 : 1015 : keep_alive = false;
599 : : }
600 : :
601 [ + + ]: 228738 : if (std::shared_ptr client{m_client.lock()}) {
602 [ + - ]: 228735 : client->Send(res, reply_body, keep_alive);
603 : 228738 : }
604 : 228738 : }
605 : :
606 : 228735 : void HTTPRemoteClient::Send(const HTTPResponse& res, std::span<const std::byte> reply_body, bool keep_alive)
607 : : {
608 : 228735 : m_keep_alive = keep_alive;
609 : :
610 : : // Serialize the response headers
611 : 228735 : const std::string headers{res.StringifyHeaders()};
612 [ - + + - ]: 228735 : const auto headers_bytes{std::as_bytes(std::span{headers})};
613 : :
614 : 228735 : bool send_buffer_was_empty{false};
615 : : // Fill the send buffer with the complete serialized response headers + body
616 : 228735 : {
617 [ + - ]: 228735 : LOCK(m_send_mutex);
618 : 228735 : send_buffer_was_empty = m_send_buffer.empty();
619 [ + - ]: 228735 : m_send_buffer.insert(m_send_buffer.end(), headers_bytes.begin(), headers_bytes.end());
620 : :
621 : : // We've been using std::span up until now but it is finally time to copy
622 : : // data. The original data will go out of scope when WriteReply() returns.
623 : : // This is analogous to the memcpy() in libevent's evbuffer_add()
624 [ + - ]: 228735 : m_send_buffer.insert(m_send_buffer.end(), reply_body.begin(), reply_body.end());
625 : :
626 : : // If the buffer already held data, the I/O thread is (or soon will be)
627 : : // draining it, so flag that there is more data to send. This must happen
628 : : // while holding m_send_mutex and while the buffer is known non-empty:
629 : : // setting m_send_ready after releasing the lock would race with the I/O
630 : : // thread draining the buffer to empty and clearing m_send_ready in
631 : : // between, leaving m_send_ready set on an empty buffer. The I/O loop would
632 : : // then only ever poll the socket for writeability, never read the client's
633 : : // next request, and wedge the connection.
634 [ + + ]: 228735 : if (!send_buffer_was_empty) m_send_ready = true;
635 : 0 : }
636 : :
637 [ + - + + : 228735 : LogDebug(
+ - ]
638 : : BCLog::HTTP,
639 : : "HTTPResponse (status code: %d size: %lld) added to send buffer for client %s (id=%llu)",
640 : : res.status,
641 : : headers_bytes.size() + reply_body.size(),
642 : : m_origin,
643 : : m_id);
644 : :
645 : : // If the send buffer was empty before we wrote this reply, we can try an
646 : : // optimistic send akin to CConnman::PushMessage() in which we
647 : : // push the data directly out the socket to client right now, instead
648 : : // of waiting for the next iteration of the I/O loop.
649 [ + + ]: 228735 : if (send_buffer_was_empty) {
650 [ + - ]: 228730 : MaybeSendBytesFromBuffer();
651 : : }
652 : :
653 : : // Signal to the I/O loop that we are ready to handle the next request.
654 : 228735 : m_req_busy = false;
655 : 228735 : }
656 : :
657 : 226989 : CService HTTPRequest::GetPeer() const
658 : : {
659 [ + + ]: 226989 : if (std::shared_ptr c{m_client.lock()}) {
660 : 226987 : return c->GetPeer();
661 : : } else {
662 [ + - ]: 2 : return {};
663 : 226989 : }
664 : : }
665 : :
666 : 93 : std::optional<std::string> HTTPRequest::GetQueryParameter(const std::string_view key) const
667 : : {
668 [ - + ]: 93 : return GetQueryParameterFromUri(m_target, key);
669 : : }
670 : :
671 : : // See libevent http.c evhttp_parse_query_impl()
672 : : // and https://www.rfc-editor.org/rfc/rfc3986#section-3.4
673 : 107 : std::optional<std::string> GetQueryParameterFromUri(const std::string_view uri, const std::string_view key)
674 : : {
675 : : // find query in URI
676 : 107 : size_t start = uri.find('?');
677 [ + + ]: 107 : if (start == std::string::npos) return std::nullopt;
678 : 97 : size_t end = uri.find('#', start);
679 [ + - ]: 97 : if (end == std::string::npos) {
680 : 97 : end = uri.length();
681 : : }
682 : 97 : const std::string_view query{uri.data() + start + 1, end - start - 1};
683 : : // find requested parameter in query
684 : 97 : const std::vector<std::string_view> params{Split<std::string_view>(query, "&")};
685 [ + + ]: 136 : for (const std::string_view& param : params) {
686 : 124 : size_t delim = param.find('=');
687 [ + - + - : 248 : if (key == UrlDecode(param.substr(0, delim))) {
+ + ]
688 [ - + ]: 85 : if (delim == std::string::npos) {
689 [ # # ]: 0 : return "";
690 : : } else {
691 [ + - + - ]: 170 : return std::string(UrlDecode(param.substr(delim + 1)));
692 : : }
693 : : }
694 : : }
695 : 12 : return std::nullopt;
696 : 97 : }
697 : :
698 : 226992 : std::optional<std::string> HTTPRequest::GetHeader(const std::string_view hdr) const
699 : : {
700 : 226992 : return m_headers.FindFirst(hdr);
701 : : }
702 : :
703 : 229419 : void HTTPRequest::WriteHeader(std::string&& hdr, std::string&& value)
704 : : {
705 : 229419 : m_response_headers.Write(std::move(hdr), std::move(value));
706 : 229419 : }
707 : :
708 : 2491 : util::Expected<void, std::string> HTTPServer::BindAndStartListening(const CService& to)
709 : : {
710 : : // Create socket for listening for incoming connections
711 : 2491 : sockaddr_storage storage;
712 : 2491 : auto sa = reinterpret_cast<sockaddr*>(&storage);
713 : 2491 : socklen_t len{sizeof(storage)};
714 [ + + ]: 2491 : if (!to.GetSockAddr(sa, &len)) {
715 [ + - ]: 2 : return util::Unexpected{strprintf("Bind address family for %s not supported", to.ToStringAddrPort())};
716 : : }
717 : :
718 : 2490 : std::unique_ptr<Sock> sock{CreateSock(to.GetSAFamily(), SOCK_STREAM, IPPROTO_TCP)};
719 [ - + ]: 2490 : if (!sock) {
720 [ # # ]: 0 : return util::Unexpected{strprintf("Cannot create %s listen socket: %s",
721 [ # # ]: 0 : to.ToStringAddrPort(),
722 [ # # ]: 0 : NetworkErrorString(WSAGetLastError()))};
723 : : }
724 : :
725 : : #ifdef WIN32
726 : : // Prevent another application from binding to the same address and port and
727 : : // intercepting RPC credentials.
728 : : // SO_REUSEADDR on Windows is non-exclusive so another process could bind to
729 : : // the same port.
730 : : if (sock->SetSockOpt(SOL_SOCKET, SO_EXCLUSIVEADDRUSE, &SOCKET_OPTION_TRUE, sizeof(SOCKET_OPTION_TRUE)) == SOCKET_ERROR) {
731 : : return util::Unexpected{strprintf("Cannot set SO_EXCLUSIVEADDRUSE on %s listen socket: %s",
732 : : to.ToStringAddrPort(),
733 : : NetworkErrorString(WSAGetLastError()))};
734 : : }
735 : : #else
736 : : // Allow binding if the port is still in TIME_WAIT state after
737 : : // the program was closed and restarted.
738 [ + - - + ]: 2490 : if (sock->SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &SOCKET_OPTION_TRUE, sizeof(SOCKET_OPTION_TRUE)) == SOCKET_ERROR) {
739 [ # # # # : 0 : LogDebug(BCLog::HTTP,
# # # # #
# ]
740 : : "Cannot set SO_REUSEADDR on %s listen socket: %s, continuing anyway",
741 : : to.ToStringAddrPort(),
742 : : NetworkErrorString(WSAGetLastError()));
743 : : }
744 : : #endif
745 : :
746 : : // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
747 : : // and enable it by default or not. Try to enable it, if possible.
748 [ + + ]: 2490 : if (to.IsIPv6()) {
749 : : #ifdef IPV6_V6ONLY
750 [ + - - + ]: 1238 : if (sock->SetSockOpt(IPPROTO_IPV6, IPV6_V6ONLY, &SOCKET_OPTION_TRUE, sizeof(SOCKET_OPTION_TRUE)) == SOCKET_ERROR) {
751 [ # # # # : 0 : LogDebug(BCLog::HTTP,
# # # # #
# ]
752 : : "Cannot set IPV6_V6ONLY on %s listen socket: %s, continuing anyway",
753 : : to.ToStringAddrPort(),
754 : : NetworkErrorString(WSAGetLastError()));
755 : : }
756 : : #endif
757 : : #ifdef WIN32
758 : : int prot_level{PROTECTION_LEVEL_UNRESTRICTED};
759 : : if (sock->SetSockOpt(IPPROTO_IPV6,
760 : : IPV6_PROTECTION_LEVEL,
761 : : &prot_level,
762 : : sizeof(prot_level)) == SOCKET_ERROR) {
763 : : LogDebug(BCLog::HTTP,
764 : : "Cannot set IPV6_PROTECTION_LEVEL on %s listen socket: %s, continuing anyway",
765 : : to.ToStringAddrPort(),
766 : : NetworkErrorString(WSAGetLastError()));
767 : : }
768 : : #endif
769 : : }
770 : :
771 [ + - - + ]: 2490 : if (sock->Bind(sa, len) == SOCKET_ERROR) {
772 : 0 : const int err{WSAGetLastError()};
773 [ # # ]: 0 : if (err == WSAEADDRINUSE) {
774 [ # # ]: 0 : return util::Unexpected{strprintf("Unable to bind to %s on this computer. %s is probably already running.",
775 [ # # ]: 0 : to.ToStringAddrPort(),
776 : 0 : CLIENT_NAME)};
777 : : } else {
778 [ # # ]: 0 : return util::Unexpected{strprintf("Unable to bind to %s on this computer (bind returned error %s)",
779 [ # # ]: 0 : to.ToStringAddrPort(),
780 [ # # ]: 0 : NetworkErrorString(err))};
781 : : }
782 : : }
783 : :
784 : : // Listen for incoming connections
785 [ + - - + ]: 2490 : if (sock->Listen(SOMAXCONN) == SOCKET_ERROR) {
786 [ # # ]: 0 : return util::Unexpected{strprintf("Cannot listen on %s: %s",
787 [ # # ]: 0 : to.ToStringAddrPort(),
788 [ # # ]: 0 : NetworkErrorString(WSAGetLastError()))};
789 : : }
790 : :
791 [ + - ]: 2490 : m_listen.emplace_back(std::move(sock));
792 : :
793 : 2490 : return {};
794 : 2490 : }
795 : :
796 : 1248 : void HTTPServer::StopListening()
797 : : {
798 : 1248 : m_listen.clear();
799 : 1248 : }
800 : :
801 : 1236 : void HTTPServer::StartSocketsThreads()
802 : : {
803 : : // The socket handler reads m_allow_subnets in ClientAllowed(). InitHTTPAllowList()
804 : : // must have populated it first; localhost entries are always added, so an empty
805 : : // list means it was never called and every connection is rejected.
806 : 1236 : Assume(!m_allow_subnets.empty());
807 : :
808 : 1236 : m_thread_socket_handler = std::thread(&util::TraceThread,
809 : : "http",
810 : 2472 : [this] { ThreadSocketHandler(); });
811 : 1236 : }
812 : :
813 : 1248 : void HTTPServer::JoinSocketsThreads()
814 : : {
815 [ + + ]: 1248 : if (m_thread_socket_handler.joinable()) {
816 : 1236 : m_thread_socket_handler.join();
817 : : }
818 : 1248 : }
819 : :
820 : 9672 : std::unique_ptr<Sock> HTTPServer::AcceptConnection(const Sock& listen_sock, CService& addr)
821 : : {
822 : : // Make sure we only operate on our own listening sockets
823 [ + + ]: 28985 : Assume(std::ranges::any_of(m_listen, [&](const auto& sock) { return sock.get() == &listen_sock; }));
824 : :
825 : 9672 : sockaddr_storage storage;
826 : 9672 : socklen_t len{sizeof(storage)};
827 : 9672 : auto sa = reinterpret_cast<sockaddr*>(&storage);
828 : :
829 : 9672 : auto sock{listen_sock.Accept(sa, &len)};
830 : :
831 [ + + ]: 9672 : if (!sock) {
832 : 4811 : const int err{WSAGetLastError()};
833 [ - + ]: 4811 : if (err != WSAEWOULDBLOCK) {
834 [ # # # # : 0 : LogDebug(BCLog::HTTP,
# # # # ]
835 : : "Cannot accept new connection: %s",
836 : : NetworkErrorString(err));
837 : : }
838 : 4811 : return {};
839 : : }
840 : :
841 : : // The OS handed us a valid socket but we can't determine its source address.
842 [ + - - + ]: 4861 : if (!addr.SetSockAddr(sa, len)) {
843 [ # # # # : 0 : LogDebug(BCLog::HTTP,
# # ]
844 : : "Unknown socket family");
845 : : }
846 : :
847 : : // Early address-based allow check
848 [ + - + + ]: 4861 : if (!ClientAllowed(addr)) {
849 [ + - + - : 2 : LogDebug(BCLog::HTTP, "Connection from %s rejected: Client network is not allowed HTTP access\n",
+ - + - ]
850 : : addr.ToStringAddrPort());
851 : : // Socket destroyed, connection aborted
852 : 2 : return {};
853 : : }
854 : :
855 : 4859 : return sock;
856 : 9672 : }
857 : :
858 : 4859 : HTTPServer::Id HTTPServer::GetNewId()
859 : : {
860 : 4859 : return m_next_id.fetch_add(1, std::memory_order_relaxed);
861 : : }
862 : :
863 : 4859 : void HTTPServer::NewSockAccepted(std::unique_ptr<Sock>&& sock, const CService& addr)
864 : : {
865 [ - + ]: 4859 : if (!sock->IsSelectable()) {
866 [ # # # # ]: 0 : LogDebug(BCLog::HTTP,
867 : : "connection from %s dropped: non-selectable socket",
868 : : addr.ToStringAddrPort());
869 : 0 : return;
870 : : }
871 : :
872 : : // According to the internet TCP_NODELAY is not carried into accepted sockets
873 : : // on all platforms. Set it again here just to be sure.
874 [ - + ]: 4859 : if (sock->SetSockOpt(IPPROTO_TCP, TCP_NODELAY, &SOCKET_OPTION_TRUE, sizeof(SOCKET_OPTION_TRUE)) == SOCKET_ERROR) {
875 [ # # # # ]: 0 : LogDebug(BCLog::HTTP, "connection from %s: unable to set TCP_NODELAY, continuing anyway",
876 : : addr.ToStringAddrPort());
877 : : }
878 : :
879 : 4859 : const Id id{GetNewId()};
880 : :
881 [ + - - + ]: 4859 : m_connected.push_back(std::make_shared<HTTPRemoteClient>(id, addr, std::move(sock)));
882 : : // Report back to the main thread
883 : 4859 : m_connected_size.fetch_add(1, std::memory_order_relaxed);
884 : :
885 [ + + + - ]: 4859 : LogDebug(BCLog::HTTP,
886 : : "HTTP Connection accepted from %s (id=%llu)",
887 : : addr.ToStringAddrPort(), id);
888 : : }
889 : :
890 : 623424 : void HTTPServer::SocketHandlerConnected(const IOReadiness& io_readiness) const
891 : : {
892 [ + + ]: 2720547 : for (const auto& [sock, events] : io_readiness.events_per_sock) {
893 [ + + ]: 2097123 : if (m_interrupt_net) {
894 : : return;
895 : : }
896 : :
897 : 2095890 : auto it{io_readiness.httpclients_per_sock.find(sock)};
898 [ + + ]: 2095890 : if (it == io_readiness.httpclients_per_sock.end()) {
899 : 1242520 : continue;
900 : : }
901 [ + + ]: 853370 : const std::shared_ptr<HTTPRemoteClient>& client{it->second};
902 : :
903 : 853370 : bool send_ready = events.occurred & Sock::SendEvent;
904 : 853370 : bool recv_ready = events.occurred & Sock::RecvEvent;
905 : 853370 : bool err_ready = events.occurred & Sock::ErrorEvent;
906 : :
907 [ + + ]: 853370 : if (send_ready) {
908 : : // Try to send as much data as is ready for this client.
909 : : // If there's an error we can skip the receive phase for this client
910 : : // because we need to disconnect.
911 [ + + ]: 1256 : if (!client->MaybeSendBytesFromBuffer()) {
912 : 1 : recv_ready = false;
913 : : }
914 : : }
915 : :
916 [ + + ]: 853370 : if (recv_ready || err_ready) {
917 : 398874 : client->Receive();
918 : : }
919 : : // Process as much received data as we can.
920 : : // This executes for every client whether or not reading or writing
921 : : // took place because it also (might) parse a request we have already
922 : : // received and pass it to a worker thread.
923 [ + + ]: 853370 : if (std::unique_ptr<HTTPRequest> request{HTTPRemoteClient::TryReadRequest(client)})
924 : : {
925 [ + - ]: 228716 : LOCK(m_request_dispatcher_mutex);
926 [ + - ]: 228716 : m_request_dispatcher(std::move(request));
927 : 853370 : }
928 : : }
929 : : }
930 : :
931 : 398874 : void HTTPRemoteClient::Receive()
932 : : {
933 : 398874 : char buf[0x10000]; // typical socket buffer is 8K-64K
934 : :
935 [ + - + - ]: 1196622 : const ssize_t nrecv{WITH_LOCK(
936 : : m_sock_mutex,
937 : 398874 : return m_sock->Recv(buf, sizeof(buf), MSG_DONTWAIT);)};
938 : :
939 [ - + ]: 398874 : if (nrecv < 0) {
940 : 0 : const int err = WSAGetLastError();
941 [ # # ]: 0 : if (IOErrorIsPermanent(err)) {
942 [ # # # # ]: 0 : LogDebug(
943 : : BCLog::HTTP,
944 : : "Permanent read error from %s (id=%llu): %s",
945 : : m_origin,
946 : : m_id,
947 : : NetworkErrorString(err));
948 : 0 : m_disconnect = true;
949 : : }
950 [ + + ]: 398874 : } else if (nrecv == 0) {
951 [ + + ]: 3550 : LogDebug(
952 : : BCLog::HTTP,
953 : : "Received EOF from %s (id=%llu)",
954 : : m_origin,
955 : : m_id);
956 : 3550 : m_disconnect = true;
957 : : } else {
958 : : // Reset idle timeout
959 : 395324 : m_idle_since = MockableSteadyClock::now();
960 : :
961 : : // Prevent disconnect until all requests are completely handled.
962 [ - + ]: 395324 : m_connection_busy = true;
963 : :
964 : : // Copy data from socket buffer to client receive buffer
965 : 395324 : m_recv_buffer.insert(
966 : 395324 : m_recv_buffer.end(),
967 : : buf,
968 [ - + ]: 395324 : buf + nrecv);
969 : :
970 : 395324 : m_total_bytes_received += static_cast<uint64_t>(nrecv);
971 [ + + - + ]: 395324 : LogDebug(
972 : : BCLog::HTTP,
973 : : "Received %d bytes from %s (id=%llu): total=%llu buffered=%zu",
974 : : nrecv,
975 : : m_origin,
976 : : m_id,
977 : : m_total_bytes_received,
978 : : m_recv_buffer.size());
979 : : }
980 : 398874 : }
981 : :
982 : 623424 : void HTTPServer::SocketHandlerListening(const Sock::EventsPerSock& events_per_sock)
983 : : {
984 [ + + ]: 623424 : if (m_stop_accepting) return;
985 [ + + ]: 1861971 : for (const auto& sock : m_listen) {
986 [ + + ]: 1240888 : if (m_interrupt_net) {
987 : : return;
988 : : }
989 [ + - + - ]: 2481770 : const auto it = events_per_sock.find(sock);
990 [ + + + + ]: 1245704 : if (it != events_per_sock.end() && it->second.occurred & Sock::RecvEvent) {
991 : : // Drain all pending connections from this socket up to the limit.
992 : : // Stop early if the kernel queue is empty (AcceptConnection returns null)
993 : : // or if accepting the last connection brought us to the limit.
994 [ + + ]: 9678 : while (GetConnectionsCount() < static_cast<size_t>(m_rpcmaxconnections)) {
995 : 9672 : CService addr_accepted;
996 [ + - ]: 9672 : auto sock_accepted{AcceptConnection(*sock, addr_accepted)};
997 [ + + ]: 9672 : if (!sock_accepted) break;
998 [ + - ]: 4859 : NewSockAccepted(std::move(sock_accepted), addr_accepted);
999 : 9672 : }
1000 : : }
1001 : : }
1002 : : }
1003 : :
1004 : 623424 : HTTPServer::IOReadiness HTTPServer::GenerateWaitSockets() const
1005 : : {
1006 [ + + ]: 623424 : IOReadiness io_readiness;
1007 : :
1008 : : // If the server is already handling its max connected clients count,
1009 : : // don't bother checking the listening sockets for new inbound connections.
1010 : : // Leave them in the kernel's queue until space in the application opens
1011 : : // up (or the client times out on its own).
1012 [ + + ]: 623424 : if (GetConnectionsCount() < static_cast<size_t>(m_rpcmaxconnections)) {
1013 [ + + ]: 1868115 : for (const auto& sock : m_listen) {
1014 [ + - ]: 1244980 : io_readiness.events_per_sock.emplace(sock, Sock::Events{Sock::RecvEvent});
1015 : : }
1016 : : }
1017 : :
1018 [ + + ]: 1476795 : for (const auto& http_client : m_connected) {
1019 : : // Safely copy the shared pointer to the socket
1020 [ + - ]: 853371 : std::shared_ptr<Sock> sock{http_client->GetSock()};
1021 : :
1022 : : // Event choice:
1023 : : // 1. ReadyToSend() (m_send_ready set) -> Send
1024 : : // m_send_ready stays set while the send buffer still has data to
1025 : : // drain, so we keep sending and do not Recv. This is also how the
1026 : : // send-throttle applies backpressure: while the send buffer is
1027 : : // full, TryReadRequest() holds a completed request back from a
1028 : : // worker, so nothing new is read until send has drained.
1029 : : // 2. Else, m_req is incomplete and needs more data, or there is no
1030 : : // m_req at all and the recv buffer is empty -> Recv
1031 : : // 3. Else (no parse in progress, leftover bytes in m_recv_buffer) -> 0
1032 : : // Stay in the I/O map so TryReadRequest() drains the buffer first.
1033 : : // Extra pipelined data waits in the kernel socket buffer
1034 : : // (TCP backpressure), not in m_recv_buffer.
1035 : : //
1036 : : // Lock-order safety: the convention established by
1037 : : // MaybeSendBytesFromBuffer() is to take m_send_mutex before m_sock_mutex.
1038 : : // In this loop GetSock() (above) takes m_sock_mutex and ReadyToSend()
1039 : : // (below) takes m_send_mutex; both are scoped, so each lock is released
1040 : : // before the next is taken and they stay separate critical sections.
1041 : : // Holding m_sock_mutex while acquiring m_send_mutex would invert that
1042 : : // order and risk a lock-order-inversion deadlock.
1043 : 853371 : Sock::Event event{0};
1044 [ + - + + ]: 853371 : if (http_client->ReadyToSend()) {
1045 : : event = Sock::SendEvent;
1046 [ + + + + ]: 851921 : } else if (http_client->GetRequest() != nullptr || http_client->ReceiveBufferEmpty()) {
1047 : : // Mid-parse (need more bytes) or buffer empty.
1048 : : event = Sock::RecvEvent;
1049 : : }
1050 : :
1051 [ + - ]: 853371 : io_readiness.events_per_sock.emplace(sock, Sock::Events{event});
1052 [ + - + - ]: 853371 : io_readiness.httpclients_per_sock.emplace(sock, http_client);
1053 : 853371 : }
1054 : :
1055 : 623424 : return io_readiness;
1056 : 0 : }
1057 : :
1058 : : /// \anchor http
1059 : 1236 : void HTTPServer::ThreadSocketHandler()
1060 : : {
1061 [ + + ]: 624660 : while (!m_interrupt_net) {
1062 : : // Check for the readiness of the already connected sockets and the
1063 : : // listening sockets in one call ("readiness" as in poll(2) or
1064 : : // select(2)). If none are ready, wait for a short while and return
1065 : : // empty sets.
1066 : 623424 : auto io_readiness{GenerateWaitSockets()};
1067 [ + - - + ]: 1246848 : if (io_readiness.events_per_sock.empty() ||
1068 : : // WaitMany() may as well be a static method, the context of the first Sock in the vector is not relevant.
1069 [ + - ]: 623424 : !io_readiness.events_per_sock.begin()->first->WaitMany(SELECT_TIMEOUT,
1070 : : io_readiness.events_per_sock)) {
1071 [ # # ]: 0 : m_interrupt_net.sleep_for(SELECT_TIMEOUT);
1072 : : }
1073 : :
1074 : : // Service (send/receive) each of the already connected sockets.
1075 [ + - ]: 623424 : SocketHandlerConnected(io_readiness);
1076 : :
1077 : : // Accept new connections from listening sockets.
1078 [ + - ]: 623424 : SocketHandlerListening(io_readiness.events_per_sock);
1079 : :
1080 : : // Disconnect any clients that have been flagged.
1081 [ + - ]: 623424 : DisconnectClients();
1082 : 623424 : }
1083 : 1236 : }
1084 : :
1085 : 853408 : std::unique_ptr<HTTPRequest> HTTPRemoteClient::TryReadRequest(const std::shared_ptr<HTTPRemoteClient>& client)
1086 : : {
1087 : : // If we are already handling a request from
1088 : : // this client, do nothing. We'll check again on the next I/O
1089 : : // loop iteration.
1090 [ + + ]: 853408 : if (client->m_req_busy) return nullptr;
1091 : :
1092 [ + + ]: 681361 : if (!client->m_req) {
1093 : 233473 : client->m_req = std::make_unique<HTTPRequest>(client);
1094 : : }
1095 : :
1096 : 681361 : try {
1097 : : // Read data from the buffer into the current request
1098 [ + + ]: 681361 : client->ReadRequest(*client->m_req);
1099 [ - + + ]: 18 : } catch (const ContentTooLargeError& e) {
1100 [ + - + - : 3 : LogDebug(
+ - ]
1101 : : BCLog::HTTP,
1102 : : "HTTP request body too large from client %s (id=%llu): %s",
1103 : : client->m_origin,
1104 : : client->m_id,
1105 : : e.what());
1106 : :
1107 [ + - ]: 3 : WriteNoStoreErrorReply(*client->m_req, HTTP_CONTENT_TOO_LARGE);
1108 : 3 : client->m_disconnect = true;
1109 : 3 : return nullptr;
1110 : 18 : } catch (const std::runtime_error& e) {
1111 [ + - + - : 15 : LogDebug(
+ - ]
1112 : : BCLog::HTTP,
1113 : : "Error reading HTTP request from client %s (id=%llu): %s",
1114 : : client->m_origin,
1115 : : client->m_id,
1116 : : e.what());
1117 : :
1118 : : // We failed to read a complete request from the buffer
1119 [ + - ]: 15 : WriteNoStoreErrorReply(*client->m_req, HTTP_BAD_REQUEST);
1120 : 15 : client->m_disconnect = true;
1121 : 15 : return nullptr;
1122 : 15 : }
1123 : :
1124 : : // If the request is ready, hand it to a worker.
1125 [ + + ]: 681343 : if (client->m_req->GetState() == HTTPRequest::State::Complete) {
1126 : : // Unless this client's send buffer is full: in that case hold the
1127 : : // parsed request here instead of moving it to a worker. This prevents
1128 : : // the server from reading any more data from this client until they
1129 : : // drain their end of the socket, and prevents the server from packing
1130 : : // more responses into the send buffer.
1131 [ - + + - ]: 457668 : const size_t buffer_used{WITH_LOCK(
1132 : : client->m_send_mutex,
1133 : : return client->m_send_buffer.size();)};
1134 [ + + ]: 228834 : if (buffer_used > MAX_BODY_SIZE) return nullptr;
1135 [ + + - + : 457437 : LogDebug(
+ - + - ]
1136 : : BCLog::HTTP,
1137 : : "Received a %s request for %s from %s (id=%llu)",
1138 : : RequestMethodString(client->m_req->GetRequestMethod()),
1139 : : client->m_req->GetURI(),
1140 : : client->m_origin,
1141 : : client->m_id);
1142 : :
1143 : 228726 : client->m_req_busy = true;
1144 : 228726 : return std::move(client->m_req);
1145 : : }
1146 : :
1147 : 452509 : return nullptr;
1148 : : }
1149 : :
1150 : 623424 : void HTTPServer::DisconnectClients()
1151 : : {
1152 : 623424 : const auto now{MockableSteadyClock::now()};
1153 : 1481654 : size_t erased = std::erase_if(m_connected, [&](auto& client) {
1154 : 1716460 : bool disconnect{client->ShouldDisconnect(now,
1155 : : m_rpcservertimeout,
1156 : 858230 : /*disconnect_all=*/m_disconnect_all_clients)};
1157 [ + + ]: 858230 : if (disconnect) {
1158 [ + + ]: 4859 : LogDebug(BCLog::HTTP,
1159 : : "Disconnecting HTTP client %s (id=%llu)",
1160 : : client->GetOrigin(),
1161 : : client->GetId());
1162 : : }
1163 : 858230 : return disconnect;
1164 : : });
1165 [ + + ]: 623424 : if (erased > 0) {
1166 : : // Report back to the main thread
1167 : 4679 : m_connected_size.fetch_sub(erased, std::memory_order_relaxed);
1168 : : }
1169 : 623424 : }
1170 : :
1171 : 858244 : bool HTTPRemoteClient::ShouldDisconnect(MockableSteadyClock::time_point now, std::chrono::seconds rpcservertimeout, bool disconnect_all) const
1172 : : {
1173 : : // Disconnect this client due to error or end of communication
1174 : : // May drop unsent data if we are closing due to error.
1175 [ + + ]: 858244 : if (m_disconnect) {
1176 : : // We should already have logged the reason when we set m_disconnect.
1177 : : return true;
1178 : : // Check for idle timeout. We reset the timer when we send and receive data,
1179 : : // but if the server is busy handling a request we should ignore the timeout until
1180 : : // the reply is sent. If we did erase the shared_ptr<HTTPRemoteClient> reference in m_connected
1181 : : // while the server is busy with a request, it might be prematurely dropped before
1182 : : // the response has been sent, or if the HTTPRequest was holding a temporary shared_ptr
1183 : : // client on a worker thread - it would keep the socket open even after "disconnecting".
1184 [ + + + + ]: 1691315 : } else if (rpcservertimeout.count() > 0 &&
1185 [ + + + + ]: 854515 : now - m_idle_since.load() > rpcservertimeout &&
1186 [ + + ]: 32 : !m_req_busy) {
1187 [ + - ]: 7 : LogDebug(BCLog::HTTP,
1188 : : "HTTP client idle timeout %s (id=%llu)",
1189 : : m_origin,
1190 : : m_id);
1191 : 7 : return true;
1192 : : // Disconnect this client because the server is shutting down and we need to
1193 : : // disconnect all clients... Unless the client is still being handled by a
1194 : : // worker thread, in which case we'd rather continue the I/O loop (but might
1195 : : // not complete sending back the full response).
1196 [ + + + + ]: 854476 : } else if (disconnect_all && !m_connection_busy) {
1197 : : return true;
1198 : : } else {
1199 : : // No reason to disconnect.
1200 : 853378 : return false;
1201 : : }
1202 : : }
1203 : :
1204 : 1245 : void HTTPServer::ClearConnectedClients()
1205 : : {
1206 [ - + ]: 1245 : Assume(!m_thread_socket_handler.joinable()); // must be called after JoinSocketsThreads()
1207 [ - + ]: 1245 : if (m_connected.empty()) return;
1208 [ # # ]: 0 : LogWarning("Force-disconnecting %d HTTP client(s) that did not disconnect gracefully", m_connected.size());
1209 [ # # ]: 0 : m_connected_size.fetch_sub(m_connected.size(), std::memory_order_relaxed);
1210 : 0 : m_connected.clear();
1211 : : }
1212 : :
1213 : 681361 : void HTTPRemoteClient::ReadRequest(HTTPRequest& req)
1214 : : {
1215 [ + + ]: 681361 : if (m_recv_buffer.empty()) return;
1216 : :
1217 [ - + ]: 395475 : LineReader reader(m_recv_buffer, MAX_HEADERS_SIZE);
1218 : :
1219 : 395475 : try {
1220 [ + + + + ]: 395475 : switch (req.GetState()) {
1221 : 228746 : case HTTPRequest::State::Init:
1222 [ + + + - ]: 228746 : if (!req.LoadControlData(reader)) break;
1223 : 228739 : req.SetState(HTTPRequest::State::NeedsHeaders);
1224 : 228745 : [[fallthrough]];
1225 : :
1226 : 228745 : case HTTPRequest::State::NeedsHeaders:
1227 [ + + + + ]: 228745 : if (!req.LoadHeaders(reader)) break;
1228 : 228732 : req.SetState(HTTPRequest::State::NeedsBody);
1229 : 395346 : [[fallthrough]];
1230 : :
1231 : 395346 : case HTTPRequest::State::NeedsBody:
1232 [ + + + + ]: 395346 : if (!req.LoadBody(reader)) break;
1233 : 228726 : req.SetState(HTTPRequest::State::Complete);
1234 : : [[fallthrough]];
1235 : :
1236 : : case HTTPRequest::State::Complete:
1237 : : break;
1238 : :
1239 : : case HTTPRequest::State::Error:
1240 : : break;
1241 : : }
1242 : 18 : } catch (...) {
1243 : : // Don't try to read any more data for this request
1244 : 18 : req.SetState(HTTPRequest::State::Error);
1245 : : // Clear the memory allocated to this client, caller must disconnect
1246 : 18 : m_recv_buffer.clear();
1247 : 18 : throw;
1248 : 18 : }
1249 : :
1250 : : // Remove the bytes read out of the buffer.
1251 : 790914 : m_recv_buffer.erase(
1252 : 395457 : m_recv_buffer.begin(),
1253 : 395457 : m_recv_buffer.begin() + reader.Consumed());
1254 : : }
1255 : :
1256 : 229992 : bool HTTPRemoteClient::MaybeSendBytesFromBuffer()
1257 : : {
1258 : : // Send as much data from this client's buffer as we can
1259 : 229992 : LOCK(m_send_mutex);
1260 [ + - ]: 229992 : if (!m_send_buffer.empty()) {
1261 : : // Socket flags (See kernel docs for send(2) and tcp(7) for more details).
1262 : : // MSG_NOSIGNAL: If the remote end of the connection is closed,
1263 : : // fail with EPIPE (an error) as opposed to triggering
1264 : : // SIGPIPE which terminates the process.
1265 : : // MSG_DONTWAIT: Makes the send operation non-blocking regardless of socket blocking mode.
1266 : : // MSG_MORE: We do not set this flag here because http responses are usually
1267 : : // small and we want the kernel to send them right away. Setting MSG_MORE
1268 : : // would "cork" the socket to prevent sending out partial frames.
1269 : 229992 : int flags{MSG_NOSIGNAL | MSG_DONTWAIT};
1270 : :
1271 : : // Try to send bytes through socket
1272 : 229992 : ssize_t bytes_sent;
1273 : 229992 : {
1274 [ + - ]: 229992 : LOCK(m_sock_mutex);
1275 [ - + + - : 229992 : bytes_sent = m_sock->Send(m_send_buffer.data(),
+ - ]
1276 : : m_send_buffer.size(),
1277 : : flags);
1278 : 0 : }
1279 : :
1280 [ + + ]: 229992 : if (bytes_sent < 0) {
1281 : : // Something went wrong
1282 : 1226 : const int err{WSAGetLastError()};
1283 [ + + ]: 1226 : if (!IOErrorIsPermanent(err)) {
1284 : : // The error can be safely ignored, try the send again on the next I/O loop.
1285 : 1225 : m_send_ready = true;
1286 : 1225 : m_connection_busy = true;
1287 : 1225 : return true;
1288 : : } else {
1289 : : // Unrecoverable error, log and disconnect client.
1290 [ + - + - : 1 : LogDebug(
+ - + - ]
1291 : : BCLog::HTTP,
1292 : : "Error sending HTTP response data to client %s (id=%llu): %s",
1293 : : m_origin,
1294 : : m_id,
1295 : : NetworkErrorString(err));
1296 : 1 : m_send_ready = false;
1297 : 1 : m_disconnect = true;
1298 : :
1299 : : // Do not attempt to read from this client.
1300 : 1 : return false;
1301 : : }
1302 : : }
1303 : :
1304 : : // Successful send, remove sent bytes from our local buffer.
1305 [ - + ]: 228766 : Assume(static_cast<size_t>(bytes_sent) <= m_send_buffer.size());
1306 : 228766 : m_send_buffer.erase(m_send_buffer.begin(),
1307 : 228766 : m_send_buffer.begin() + bytes_sent);
1308 : :
1309 [ + - + + : 228766 : LogDebug(
+ - ]
1310 : : BCLog::HTTP,
1311 : : "Sent %d bytes to client %s (id=%llu)",
1312 : : bytes_sent,
1313 : : m_origin,
1314 : : m_id);
1315 : :
1316 : : // This check is inside the if(!empty) block meaning "there was data but now its gone".
1317 : : // We wouldn't want to change the flags if MaybeSendBytesFromBuffer() was called
1318 : : // on an already-empty m_send_buffer because the connection might have just been opened.
1319 [ + + ]: 228766 : if (m_send_buffer.empty()) {
1320 : 228729 : m_send_ready = false;
1321 [ + + ]: 228729 : m_connection_busy = false;
1322 : :
1323 : : // Our work is done here
1324 [ + + ]: 228729 : if (!m_keep_alive) {
1325 [ + - + - : 1023 : LogDebug(
+ - ]
1326 : : BCLog::HTTP,
1327 : : "Done sending to client without keep-alive %s (id=%llu)",
1328 : : m_origin,
1329 : : m_id);
1330 : 1023 : m_disconnect = true;
1331 : : // Do not attempt to read from this client.
1332 : 1023 : return false;
1333 : : }
1334 : : } else {
1335 : : // The send buffer isn't flushed yet, try to push more on the next loop.
1336 : 37 : m_send_ready = true;
1337 : 37 : m_connection_busy = true;
1338 : : }
1339 : :
1340 : : // Finally, reset idle timeout
1341 : 227743 : m_idle_since = MockableSteadyClock::now();
1342 : : }
1343 : :
1344 : : return true;
1345 : 229992 : }
1346 : :
1347 : 1245 : bool InitHTTPServer()
1348 : : {
1349 : : // Create HTTPServer
1350 : 1245 : g_http_server = std::make_unique<HTTPServer>(MaybeDispatchRequestToWorker);
1351 : :
1352 [ + - ]: 1245 : if (!g_http_server->InitHTTPAllowList()) {
1353 : : return false;
1354 : : }
1355 : :
1356 : 2490 : g_http_server->SetServerTimeout(std::chrono::seconds(gArgs.GetIntArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT)));
1357 [ + - + - ]: 2490 : g_http_server->SetMaxConnections(std::max(gArgs.GetArg<int>("-rpcmaxconnections", DEFAULT_MAX_HTTP_CONNECTIONS), 1));
1358 : :
1359 : : // Bind HTTP server to specified addresses
1360 : 1245 : std::vector<std::pair<std::string, uint16_t>> endpoints{GetBindAddresses()};
1361 : 1245 : bool bind_success{false};
1362 [ + - + + ]: 3732 : for (const auto& [address_string, port] : endpoints) {
1363 [ + - ]: 2487 : LogInfo("Binding RPC on address %s port %i", address_string, port);
1364 [ + - + - ]: 2487 : const std::optional<CService> addr{Lookup(address_string, port, false)};
1365 [ + - ]: 2487 : if (addr) {
1366 [ + - - + ]: 2487 : if (addr->IsBindAny()) {
1367 [ # # ]: 0 : LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet");
1368 : : }
1369 [ + - + - ]: 2487 : auto result{g_http_server->BindAndStartListening(addr.value())};
1370 [ - + ]: 2487 : if (!result) {
1371 [ # # # # ]: 0 : LogWarning("Binding RPC on address %s failed: %s", addr->ToStringAddrPort(), result.error());
1372 : : } else {
1373 : : bind_success = true;
1374 : : }
1375 : 2487 : } else {
1376 [ - - ]: 2487 : LogWarning("Could not bind RPC on address %s port %i: Address lookup failed.", address_string, port);
1377 : : }
1378 : 2487 : }
1379 : :
1380 [ - + ]: 1245 : if (!bind_success) {
1381 [ # # ]: 0 : LogError("Unable to bind any endpoint for RPC server");
1382 : : return false;
1383 : : }
1384 : :
1385 [ + - + + : 1245 : LogDebug(BCLog::HTTP, "Initialized HTTP server");
+ - ]
1386 : :
1387 [ + - + - : 2490 : g_max_queue_depth = std::max(gArgs.GetArg<int>("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1);
+ - ]
1388 [ + - + + : 1245 : LogDebug(BCLog::HTTP, "set work queue of depth %d\n", g_max_queue_depth);
+ - ]
1389 : :
1390 : : return true;
1391 : 1245 : }
1392 : :
1393 : 1233 : void StartHTTPServer()
1394 : : {
1395 [ + - + - ]: 2466 : auto rpcThreads{std::max(gArgs.GetArg<int>("-rpcthreads", DEFAULT_HTTP_THREADS), 1)};
1396 : 1233 : LogInfo("Starting HTTP server with %d worker threads", rpcThreads);
1397 : 1233 : g_threadpool_http.Start(rpcThreads);
1398 : 1233 : g_http_server->StartSocketsThreads();
1399 : 1233 : }
1400 : :
1401 : 1294 : void InterruptHTTPServer()
1402 : : {
1403 [ + + ]: 1294 : LogDebug(BCLog::HTTP, "Interrupting HTTP server");
1404 [ + + ]: 1294 : if (g_http_server) {
1405 : : // Reject all new requests
1406 [ + - ]: 2490 : g_http_server->SetRequestHandler(RejectRequest);
1407 : : }
1408 : :
1409 : : // Interrupt pool after disabling requests
1410 : 1294 : g_threadpool_http.Interrupt();
1411 : 1294 : }
1412 : :
1413 : 1294 : void StopHTTPServer()
1414 : : {
1415 [ + + ]: 1294 : LogDebug(BCLog::HTTP, "Stopping HTTP server");
1416 : :
1417 [ + + ]: 1294 : LogDebug(BCLog::HTTP, "Waiting for HTTP worker threads to exit\n");
1418 : 1294 : g_threadpool_http.Stop();
1419 : :
1420 [ + + ]: 1294 : if (g_http_server) {
1421 : : // Must precede DisconnectAllClients(): a connection accepted after
1422 : : // GetConnectionsCount() returns 0 would survive into the destructor.
1423 : 1245 : g_http_server->StopAccepting();
1424 : : // Disconnect clients as their remaining responses are flushed
1425 : 1245 : g_http_server->DisconnectAllClients();
1426 : : // Wait 30 seconds for all disconnections
1427 [ + + ]: 1245 : LogDebug(BCLog::HTTP, "Waiting for HTTP clients to disconnect gracefully");
1428 : 1245 : const auto deadline{NodeClock::now() + 30s};
1429 [ + + ]: 3661 : while (g_http_server->GetConnectionsCount() != 0) {
1430 [ - + ]: 1171 : if (NodeClock::now() > deadline) {
1431 : 0 : LogWarning("Timeout waiting for HTTP clients to disconnect gracefully, continuing shutdown");
1432 : 0 : break;
1433 : : }
1434 : 1171 : std::this_thread::sleep_for(50ms);
1435 : : }
1436 : : // Break HTTPServer I/O loop: stop accepting connections, sending and receiving data
1437 : 1245 : g_http_server->InterruptNet();
1438 : : // Wait for HTTPServer I/O thread to exit
1439 : 1245 : g_http_server->JoinSocketsThreads();
1440 : : // Force-remove any clients that survived the graceful wait
1441 : 1245 : g_http_server->ClearConnectedClients();
1442 : : // Close all listening sockets
1443 : 1245 : g_http_server->StopListening();
1444 : : }
1445 [ + + ]: 1294 : LogDebug(BCLog::HTTP, "Stopped HTTP server");
1446 : 1294 : }
|