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