/tmp/bitcoin/src/httpserver.cpp
Line | Count | Source |
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 <httpserver.h> |
6 | | |
7 | | #include <chainparamsbase.h> |
8 | | #include <common/args.h> |
9 | | #include <common/messages.h> |
10 | | #include <compat/compat.h> |
11 | | #include <logging.h> |
12 | | #include <netbase.h> |
13 | | #include <node/interface_ui.h> |
14 | | #include <rpc/protocol.h> |
15 | | #include <sync.h> |
16 | | #include <util/check.h> |
17 | | #include <util/signalinterrupt.h> |
18 | | #include <util/strencodings.h> |
19 | | #include <util/threadnames.h> |
20 | | #include <util/threadpool.h> |
21 | | #include <util/translation.h> |
22 | | |
23 | | #include <condition_variable> |
24 | | #include <cstdio> |
25 | | #include <cstdlib> |
26 | | #include <deque> |
27 | | #include <memory> |
28 | | #include <optional> |
29 | | #include <span> |
30 | | #include <string> |
31 | | #include <thread> |
32 | | #include <unordered_map> |
33 | | #include <vector> |
34 | | |
35 | | #include <sys/types.h> |
36 | | #include <sys/stat.h> |
37 | | |
38 | | #include <event2/buffer.h> |
39 | | #include <event2/bufferevent.h> |
40 | | #include <event2/http.h> |
41 | | #include <event2/http_struct.h> |
42 | | #include <event2/keyvalq_struct.h> |
43 | | #include <event2/thread.h> |
44 | | #include <event2/util.h> |
45 | | |
46 | | #include <support/events.h> |
47 | | |
48 | | using common::InvalidPortErrMsg; |
49 | | |
50 | | /** Maximum size of http request (request line + headers) */ |
51 | | static const size_t MAX_HEADERS_SIZE = 8192; |
52 | | |
53 | | struct HTTPPathHandler |
54 | | { |
55 | | HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler): |
56 | 2.21k | prefix(_prefix), exactMatch(_exactMatch), handler(_handler) |
57 | 2.21k | { |
58 | 2.21k | } |
59 | | std::string prefix; |
60 | | bool exactMatch; |
61 | | HTTPRequestHandler handler; |
62 | | }; |
63 | | |
64 | | /** HTTP module state */ |
65 | | |
66 | | //! libevent event loop |
67 | | static struct event_base* eventBase = nullptr; |
68 | | //! HTTP server |
69 | | static struct evhttp* eventHTTP = nullptr; |
70 | | //! List of subnets to allow RPC connections from |
71 | | static std::vector<CSubNet> rpc_allow_subnets; |
72 | | //! Handlers for (sub)paths |
73 | | static GlobalMutex g_httppathhandlers_mutex; |
74 | | static std::vector<HTTPPathHandler> pathHandlers GUARDED_BY(g_httppathhandlers_mutex); |
75 | | //! Bound listening sockets |
76 | | static std::vector<evhttp_bound_socket *> boundSockets; |
77 | | /// \anchor http_pool |
78 | | //! Http thread pool - future: encapsulate in HttpContext |
79 | | static ThreadPool g_threadpool_http("http"); |
80 | | static int g_max_queue_depth{100}; |
81 | | |
82 | | /** |
83 | | * @brief Helps keep track of open `evhttp_connection`s with active `evhttp_requests` |
84 | | * |
85 | | */ |
86 | | class HTTPRequestTracker |
87 | | { |
88 | | private: |
89 | | mutable Mutex m_mutex; |
90 | | mutable std::condition_variable m_cv; |
91 | | //! For each connection, keep a counter of how many requests are open |
92 | | std::unordered_map<const evhttp_connection*, size_t> m_tracker GUARDED_BY(m_mutex); |
93 | | |
94 | | void RemoveConnectionInternal(const decltype(m_tracker)::iterator it) EXCLUSIVE_LOCKS_REQUIRED(m_mutex) |
95 | 171k | { |
96 | 171k | m_tracker.erase(it); |
97 | 171k | if (m_tracker.empty()) m_cv.notify_all(); |
98 | 171k | } |
99 | | public: |
100 | | //! Increase request counter for the associated connection by 1 |
101 | | void AddRequest(evhttp_request* req) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex) |
102 | 171k | { |
103 | 171k | const evhttp_connection* conn{Assert(evhttp_request_get_connection(Assert(req)))}; |
104 | 171k | WITH_LOCK(m_mutex, ++m_tracker[conn]); |
105 | 171k | } |
106 | | //! Decrease request counter for the associated connection by 1, remove connection if counter is 0 |
107 | | void RemoveRequest(evhttp_request* req) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex) |
108 | 171k | { |
109 | 171k | const evhttp_connection* conn{Assert(evhttp_request_get_connection(Assert(req)))}; |
110 | 171k | LOCK(m_mutex); |
111 | 171k | auto it{m_tracker.find(conn)}; |
112 | 171k | if (it != m_tracker.end() && it->second > 0) { |
113 | 171k | if (--(it->second) == 0) RemoveConnectionInternal(it); |
114 | 171k | } |
115 | 171k | } |
116 | | //! Remove a connection entirely |
117 | | void RemoveConnection(const evhttp_connection* conn) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex) |
118 | 3.07k | { |
119 | 3.07k | LOCK(m_mutex); |
120 | 3.07k | auto it{m_tracker.find(Assert(conn))}; |
121 | 3.07k | if (it != m_tracker.end()) RemoveConnectionInternal(it); |
122 | 3.07k | } |
123 | | size_t CountActiveConnections() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex) |
124 | 1.15k | { |
125 | 1.15k | return WITH_LOCK(m_mutex, return m_tracker.size()); |
126 | 1.15k | } |
127 | | //! Wait until there are no more connections with active requests in the tracker |
128 | | void WaitUntilEmpty() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex) |
129 | 1.15k | { |
130 | 1.15k | WAIT_LOCK(m_mutex, lock); |
131 | 1.16k | m_cv.wait(lock, [this]() EXCLUSIVE_LOCKS_REQUIRED(m_mutex) { return m_tracker.empty(); }); |
132 | 1.15k | } |
133 | | }; |
134 | | //! Track active requests |
135 | | static HTTPRequestTracker g_requests; |
136 | | |
137 | | /** Check if a network address is allowed to access the HTTP server */ |
138 | | static bool ClientAllowed(const CNetAddr& netaddr) |
139 | 171k | { |
140 | 171k | if (!netaddr.IsValid()) |
141 | 0 | return false; |
142 | 171k | for(const CSubNet& subnet : rpc_allow_subnets) |
143 | 171k | if (subnet.Match(netaddr)) |
144 | 171k | return true; |
145 | 1 | return false; |
146 | 171k | } |
147 | | |
148 | | /** Initialize ACL list for HTTP server */ |
149 | | static bool InitHTTPAllowList() |
150 | 1.11k | { |
151 | 1.11k | rpc_allow_subnets.clear(); |
152 | 1.11k | rpc_allow_subnets.emplace_back(LookupHost("127.0.0.1", false).value(), 8); // always allow IPv4 local subnet |
153 | 1.11k | rpc_allow_subnets.emplace_back(LookupHost("::1", false).value()); // always allow IPv6 localhost |
154 | 1.11k | for (const std::string& strAllow : gArgs.GetArgs("-rpcallowip")) { |
155 | 13 | const CSubNet subnet{LookupSubNet(strAllow)}; |
156 | 13 | if (!subnet.IsValid()) { |
157 | 1 | uiInterface.ThreadSafeMessageBox( |
158 | 1 | 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)), |
159 | 1 | CClientUIInterface::MSG_ERROR); |
160 | 1 | return false; |
161 | 1 | } |
162 | 12 | rpc_allow_subnets.push_back(subnet); |
163 | 12 | } |
164 | 1.11k | std::string strAllowed; |
165 | 1.11k | for (const CSubNet& subnet : rpc_allow_subnets) |
166 | 2.23k | strAllowed += subnet.ToString() + " "; |
167 | 1.11k | LogDebug(BCLog::HTTP, "Allowing HTTP connections from: %s\n", strAllowed); |
168 | 1.11k | return true; |
169 | 1.11k | } |
170 | | |
171 | | /** HTTP request method as string - use for logging only */ |
172 | | std::string RequestMethodString(HTTPRequest::RequestMethod m) |
173 | 171k | { |
174 | 171k | switch (m) { |
175 | 743 | case HTTPRequest::GET: |
176 | 743 | return "GET"; |
177 | 171k | case HTTPRequest::POST: |
178 | 171k | return "POST"; |
179 | 0 | case HTTPRequest::HEAD: |
180 | 0 | return "HEAD"; |
181 | 0 | case HTTPRequest::PUT: |
182 | 0 | return "PUT"; |
183 | 0 | case HTTPRequest::UNKNOWN: |
184 | 0 | return "unknown"; |
185 | 171k | } // no default case, so the compiler can warn about missing cases |
186 | 171k | assert(false); |
187 | 0 | } |
188 | | |
189 | | /** HTTP request callback */ |
190 | | static void http_request_cb(struct evhttp_request* req, void* arg) |
191 | 171k | { |
192 | 171k | evhttp_connection* conn{evhttp_request_get_connection(req)}; |
193 | | // Track active requests |
194 | 171k | { |
195 | 171k | g_requests.AddRequest(req); |
196 | 171k | evhttp_request_set_on_complete_cb(req, [](struct evhttp_request* req, void*) { |
197 | 171k | g_requests.RemoveRequest(req); |
198 | 171k | }, nullptr); |
199 | 171k | evhttp_connection_set_closecb(conn, [](evhttp_connection* conn, void* arg) { |
200 | 3.07k | g_requests.RemoveConnection(conn); |
201 | 3.07k | }, nullptr); |
202 | 171k | } |
203 | | |
204 | | // Disable reading to work around a libevent bug, fixed in 2.1.9 |
205 | | // See https://github.com/libevent/libevent/commit/5ff8eb26371c4dc56f384b2de35bea2d87814779 |
206 | | // and https://github.com/bitcoin/bitcoin/pull/11593. |
207 | 171k | if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02010900) { |
208 | 0 | if (conn) { |
209 | 0 | bufferevent* bev = evhttp_connection_get_bufferevent(conn); |
210 | 0 | if (bev) { |
211 | 0 | bufferevent_disable(bev, EV_READ); |
212 | 0 | } |
213 | 0 | } |
214 | 0 | } |
215 | 171k | auto hreq{std::make_shared<HTTPRequest>(req, *static_cast<const util::SignalInterrupt*>(arg))}; |
216 | | |
217 | | // Early address-based allow check |
218 | 171k | if (!ClientAllowed(hreq->GetPeer())) { |
219 | 1 | LogDebug(BCLog::HTTP, "HTTP request from %s rejected: Client network is not allowed RPC access\n", |
220 | 1 | hreq->GetPeer().ToStringAddrPort()); |
221 | 1 | hreq->WriteReply(HTTP_FORBIDDEN); |
222 | 1 | return; |
223 | 1 | } |
224 | | |
225 | | // Early reject unknown HTTP methods |
226 | 171k | if (hreq->GetRequestMethod() == HTTPRequest::UNKNOWN) { |
227 | 0 | LogDebug(BCLog::HTTP, "HTTP request from %s rejected: Unknown HTTP request method\n", |
228 | 0 | hreq->GetPeer().ToStringAddrPort()); |
229 | 0 | hreq->WriteReply(HTTP_BAD_METHOD); |
230 | 0 | return; |
231 | 0 | } |
232 | | |
233 | 171k | LogDebug(BCLog::HTTP, "Received a %s request for %s from %s\n", |
234 | 171k | RequestMethodString(hreq->GetRequestMethod()), SanitizeString(hreq->GetURI(), SAFE_CHARS_URI).substr(0, 100), hreq->GetPeer().ToStringAddrPort()); |
235 | | |
236 | | // Find registered handler for prefix |
237 | 171k | std::string strURI = hreq->GetURI(); |
238 | 171k | std::string path; |
239 | 171k | LOCK(g_httppathhandlers_mutex); |
240 | 171k | std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin(); |
241 | 171k | std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end(); |
242 | 197k | for (; i != iend; ++i) { |
243 | 197k | bool match = false; |
244 | 197k | if (i->exactMatch) |
245 | 171k | match = (strURI == i->prefix); |
246 | 25.7k | else |
247 | 25.7k | match = strURI.starts_with(i->prefix); |
248 | 197k | if (match) { |
249 | 171k | path = strURI.substr(i->prefix.size()); |
250 | 171k | break; |
251 | 171k | } |
252 | 197k | } |
253 | | |
254 | | // Dispatch to worker thread |
255 | 171k | if (i != iend) { |
256 | 171k | if (static_cast<int>(g_threadpool_http.WorkQueueSize()) >= g_max_queue_depth) { |
257 | 1 | LogWarning("Request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting"); |
258 | 1 | hreq->WriteReply(HTTP_SERVICE_UNAVAILABLE, "Work queue depth exceeded"); |
259 | 1 | return; |
260 | 1 | } |
261 | | |
262 | 171k | auto item = [req = hreq, in_path = std::move(path), fn = i->handler]() { |
263 | 171k | std::string err_msg; |
264 | 171k | try { |
265 | 171k | fn(req.get(), in_path); |
266 | 171k | return; |
267 | 171k | } catch (const std::exception& e) { |
268 | 0 | LogWarning("Unexpected error while processing request for '%s'. Error msg: '%s'", req->GetURI(), e.what()); |
269 | 0 | err_msg = e.what(); |
270 | 0 | } catch (...) { |
271 | 0 | LogWarning("Unknown error while processing request for '%s'", req->GetURI()); |
272 | 0 | err_msg = "unknown error"; |
273 | 0 | } |
274 | | // Reply so the client doesn't hang waiting for the response. |
275 | 0 | req->WriteHeader("Connection", "close"); |
276 | | // TODO: Implement specific error formatting for the REST and JSON-RPC servers responses. |
277 | 0 | req->WriteReply(HTTP_INTERNAL_SERVER_ERROR, err_msg); |
278 | 0 | }; |
279 | | |
280 | 171k | if (auto res = g_threadpool_http.Submit(std::move(item)); !res.has_value()) { |
281 | 0 | Assume(hreq.use_count() == 1); // ensure request will be deleted |
282 | | // Both SubmitError::Inactive and SubmitError::Interrupted mean shutdown |
283 | 0 | LogWarning("HTTP request rejected during server shutdown: '%s'", SubmitErrorString(res.error())); |
284 | 0 | hreq->WriteReply(HTTP_SERVICE_UNAVAILABLE, "Request rejected during server shutdown"); |
285 | 0 | return; |
286 | 0 | } |
287 | 171k | } else { |
288 | 3 | hreq->WriteReply(HTTP_NOT_FOUND); |
289 | 3 | } |
290 | 171k | } |
291 | | |
292 | | /** Callback to reject HTTP requests after shutdown. */ |
293 | | static void http_reject_request_cb(struct evhttp_request* req, void*) |
294 | 0 | { |
295 | 0 | LogDebug(BCLog::HTTP, "Rejecting request while shutting down\n"); |
296 | 0 | evhttp_send_error(req, HTTP_SERVUNAVAIL, nullptr); |
297 | 0 | } |
298 | | |
299 | | /// \anchor http |
300 | | /** Event dispatcher thread */ |
301 | | static void ThreadHTTP(struct event_base* base) |
302 | 1.09k | { |
303 | 1.09k | util::ThreadRename("http"); |
304 | 1.09k | LogDebug(BCLog::HTTP, "Entering http event loop\n"); |
305 | 1.09k | event_base_dispatch(base); |
306 | | // Event loop will be interrupted by InterruptHTTPServer() |
307 | 1.09k | LogDebug(BCLog::HTTP, "Exited http event loop\n"); |
308 | 1.09k | } |
309 | | |
310 | | /** Bind HTTP server to specified addresses */ |
311 | | static bool HTTPBindAddresses(struct evhttp* http) |
312 | 1.11k | { |
313 | 1.11k | uint16_t http_port{static_cast<uint16_t>(gArgs.GetIntArg("-rpcport", BaseParams().RPCPort()))}; |
314 | 1.11k | std::vector<std::pair<std::string, uint16_t>> endpoints; |
315 | | |
316 | | // Determine what addresses to bind to |
317 | | // To prevent misconfiguration and accidental exposure of the RPC |
318 | | // interface, require -rpcallowip and -rpcbind to both be specified |
319 | | // together. If either is missing, ignore both values, bind to localhost |
320 | | // instead, and log warnings. |
321 | 1.11k | if (gArgs.GetArgs("-rpcallowip").empty() || gArgs.GetArgs("-rpcbind").empty()) { // Default to loopback if not allowing external IPs |
322 | 1.10k | endpoints.emplace_back("::1", http_port); |
323 | 1.10k | endpoints.emplace_back("127.0.0.1", http_port); |
324 | 1.10k | if (!gArgs.GetArgs("-rpcallowip").empty()) { |
325 | 3 | LogWarning("Option -rpcallowip was specified without -rpcbind; this doesn't usually make sense"); |
326 | 3 | } |
327 | 1.10k | if (!gArgs.GetArgs("-rpcbind").empty()) { |
328 | 0 | LogWarning("Option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect"); |
329 | 0 | } |
330 | 1.10k | } else { // Specific bind addresses |
331 | 14 | for (const std::string& strRPCBind : gArgs.GetArgs("-rpcbind")) { |
332 | 14 | uint16_t port{http_port}; |
333 | 14 | std::string host; |
334 | 14 | if (!SplitHostPort(strRPCBind, port, host)) { |
335 | 0 | LogError("%s\n", InvalidPortErrMsg("-rpcbind", strRPCBind).original); |
336 | 0 | return false; |
337 | 0 | } |
338 | 14 | endpoints.emplace_back(host, port); |
339 | 14 | } |
340 | 9 | } |
341 | | |
342 | | // Bind addresses |
343 | 3.32k | for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) { |
344 | 2.21k | LogInfo("Binding RPC on address %s port %i", i->first, i->second); |
345 | 2.21k | evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? nullptr : i->first.c_str(), i->second); |
346 | 2.21k | if (bind_handle) { |
347 | 2.21k | const std::optional<CNetAddr> addr{LookupHost(i->first, false)}; |
348 | 2.21k | if (i->first.empty() || (addr.has_value() && addr->IsBindAny())) { |
349 | 0 | LogWarning("The RPC server is not safe to expose to untrusted networks such as the public internet"); |
350 | 0 | } |
351 | | // Set the no-delay option (disable Nagle's algorithm) on the TCP socket. |
352 | 2.21k | evutil_socket_t fd = evhttp_bound_socket_get_fd(bind_handle); |
353 | 2.21k | int one = 1; |
354 | 2.21k | if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char*>(&one), sizeof(one)) == SOCKET_ERROR) { |
355 | 0 | LogInfo("WARNING: Unable to set TCP_NODELAY on RPC server socket, continuing anyway\n"); |
356 | 0 | } |
357 | 2.21k | boundSockets.push_back(bind_handle); |
358 | 2.21k | } else { |
359 | 0 | LogWarning("Binding RPC on address %s port %i failed.", i->first, i->second); |
360 | 0 | } |
361 | 2.21k | } |
362 | 1.11k | return !boundSockets.empty(); |
363 | 1.11k | } |
364 | | |
365 | | /** libevent event log callback */ |
366 | | static void libevent_log_cb(int severity, const char *msg) |
367 | 0 | { |
368 | 0 | switch (severity) { |
369 | 0 | case EVENT_LOG_DEBUG: |
370 | 0 | LogDebug(BCLog::LIBEVENT, "%s", msg); |
371 | 0 | break; |
372 | 0 | case EVENT_LOG_MSG: |
373 | 0 | LogInfo("libevent: %s", msg); |
374 | 0 | break; |
375 | 0 | case EVENT_LOG_WARN: |
376 | 0 | LogWarning("libevent: %s", msg); |
377 | 0 | break; |
378 | 0 | default: // EVENT_LOG_ERR and others are mapped to error |
379 | 0 | LogError("libevent: %s", msg); |
380 | 0 | break; |
381 | 0 | } |
382 | 0 | } |
383 | | |
384 | | bool InitHTTPServer(const util::SignalInterrupt& interrupt) |
385 | 1.11k | { |
386 | 1.11k | if (!InitHTTPAllowList()) |
387 | 1 | return false; |
388 | | |
389 | | // Redirect libevent's logging to our own log |
390 | 1.11k | event_set_log_callback(&libevent_log_cb); |
391 | | // Update libevent's log handling. |
392 | 1.11k | UpdateHTTPServerLogging(LogInstance().WillLogCategory(BCLog::LIBEVENT)); |
393 | | |
394 | | #ifdef WIN32 |
395 | | evthread_use_windows_threads(); |
396 | | #else |
397 | 1.11k | evthread_use_pthreads(); |
398 | 1.11k | #endif |
399 | | |
400 | 1.11k | raii_event_base base_ctr = obtain_event_base(); |
401 | | |
402 | | /* Create a new evhttp object to handle requests. */ |
403 | 1.11k | raii_evhttp http_ctr = obtain_evhttp(base_ctr.get()); |
404 | 1.11k | struct evhttp* http = http_ctr.get(); |
405 | 1.11k | if (!http) { |
406 | 0 | LogError("Couldn't create evhttp. Exiting."); |
407 | 0 | return false; |
408 | 0 | } |
409 | | |
410 | 1.11k | evhttp_set_timeout(http, gArgs.GetIntArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT)); |
411 | 1.11k | evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE); |
412 | 1.11k | evhttp_set_max_body_size(http, MAX_SIZE); |
413 | 1.11k | evhttp_set_gencb(http, http_request_cb, (void*)&interrupt); |
414 | | |
415 | 1.11k | if (!HTTPBindAddresses(http)) { |
416 | 0 | LogError("Unable to bind any endpoint for RPC server"); |
417 | 0 | return false; |
418 | 0 | } |
419 | | |
420 | 1.11k | LogDebug(BCLog::HTTP, "Initialized HTTP server\n"); |
421 | 1.11k | g_max_queue_depth = std::max(gArgs.GetArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1); |
422 | 1.11k | LogDebug(BCLog::HTTP, "set work queue of depth %d", g_max_queue_depth); |
423 | | |
424 | | // transfer ownership to eventBase/HTTP via .release() |
425 | 1.11k | eventBase = base_ctr.release(); |
426 | 1.11k | eventHTTP = http_ctr.release(); |
427 | 1.11k | return true; |
428 | 1.11k | } |
429 | | |
430 | 1.11k | void UpdateHTTPServerLogging(bool enable) { |
431 | 1.11k | if (enable) { |
432 | 0 | event_enable_debug_logging(EVENT_DBG_ALL); |
433 | 1.11k | } else { |
434 | 1.11k | event_enable_debug_logging(EVENT_DBG_NONE); |
435 | 1.11k | } |
436 | 1.11k | } |
437 | | |
438 | | static std::thread g_thread_http; |
439 | | |
440 | | void StartHTTPServer() |
441 | 1.09k | { |
442 | 1.09k | int rpcThreads = std::max(gArgs.GetArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1); |
443 | 1.09k | LogInfo("Starting HTTP server with %d worker threads", rpcThreads); |
444 | 1.09k | g_threadpool_http.Start(rpcThreads); |
445 | 1.09k | g_thread_http = std::thread(ThreadHTTP, eventBase); |
446 | 1.09k | } |
447 | | |
448 | | void InterruptHTTPServer() |
449 | 1.15k | { |
450 | 1.15k | LogDebug(BCLog::HTTP, "Interrupting HTTP server\n"); |
451 | 1.15k | if (eventHTTP) { |
452 | | // Reject requests on current connections |
453 | 1.11k | evhttp_set_gencb(eventHTTP, http_reject_request_cb, nullptr); |
454 | 1.11k | } |
455 | | // Interrupt pool after disabling requests |
456 | 1.15k | g_threadpool_http.Interrupt(); |
457 | 1.15k | } |
458 | | |
459 | | void StopHTTPServer() |
460 | 1.15k | { |
461 | 1.15k | LogDebug(BCLog::HTTP, "Stopping HTTP server\n"); |
462 | | |
463 | 1.15k | LogDebug(BCLog::HTTP, "Waiting for HTTP worker threads to exit\n"); |
464 | 1.15k | g_threadpool_http.Stop(); |
465 | | |
466 | | // Unlisten sockets, these are what make the event loop running, which means |
467 | | // that after this and all connections are closed the event loop will quit. |
468 | 2.21k | for (evhttp_bound_socket *socket : boundSockets) { |
469 | 2.21k | evhttp_del_accept_socket(eventHTTP, socket); |
470 | 2.21k | } |
471 | 1.15k | boundSockets.clear(); |
472 | 1.15k | { |
473 | 1.15k | if (const auto n_connections{g_requests.CountActiveConnections()}; n_connections != 0) { |
474 | 15 | LogDebug(BCLog::HTTP, "Waiting for %d connections to stop HTTP server\n", n_connections); |
475 | 15 | } |
476 | 1.15k | g_requests.WaitUntilEmpty(); |
477 | 1.15k | } |
478 | 1.15k | if (eventHTTP) { |
479 | | // Schedule a callback to call evhttp_free in the event base thread, so |
480 | | // that evhttp_free does not need to be called again after the handling |
481 | | // of unfinished request connections that follows. |
482 | 1.11k | event_base_once(eventBase, -1, EV_TIMEOUT, [](evutil_socket_t, short, void*) { |
483 | 446 | evhttp_free(eventHTTP); |
484 | 446 | eventHTTP = nullptr; |
485 | 446 | }, nullptr, nullptr); |
486 | 1.11k | } |
487 | 1.15k | if (eventBase) { |
488 | 1.11k | LogDebug(BCLog::HTTP, "Waiting for HTTP event thread to exit\n"); |
489 | 1.11k | if (g_thread_http.joinable()) g_thread_http.join(); |
490 | 1.11k | event_base_free(eventBase); |
491 | 1.11k | eventBase = nullptr; |
492 | 1.11k | } |
493 | 1.15k | LogDebug(BCLog::HTTP, "Stopped HTTP server\n"); |
494 | 1.15k | } |
495 | | |
496 | | struct event_base* EventBase() |
497 | 1.09k | { |
498 | 1.09k | return eventBase; |
499 | 1.09k | } |
500 | | |
501 | | static void httpevent_callback_fn(evutil_socket_t, short, void* data) |
502 | 171k | { |
503 | | // Static handler: simply call inner handler |
504 | 171k | HTTPEvent *self = static_cast<HTTPEvent*>(data); |
505 | 171k | self->handler(); |
506 | 171k | if (self->deleteWhenTriggered) |
507 | 171k | delete self; |
508 | 171k | } |
509 | | |
510 | | HTTPEvent::HTTPEvent(struct event_base* base, bool _deleteWhenTriggered, const std::function<void()>& _handler): |
511 | 171k | deleteWhenTriggered(_deleteWhenTriggered), handler(_handler) |
512 | 171k | { |
513 | 171k | ev = event_new(base, -1, 0, httpevent_callback_fn, this); |
514 | 171k | assert(ev); |
515 | 171k | } |
516 | | HTTPEvent::~HTTPEvent() |
517 | 171k | { |
518 | 171k | event_free(ev); |
519 | 171k | } |
520 | | void HTTPEvent::trigger(struct timeval* tv) |
521 | 171k | { |
522 | 171k | if (tv == nullptr) |
523 | 171k | event_active(ev, 0, 0); // immediately trigger event in main thread |
524 | 0 | else |
525 | 171k | evtimer_add(ev, tv); // trigger after timeval passed |
526 | 171k | } |
527 | | HTTPRequest::HTTPRequest(struct evhttp_request* _req, const util::SignalInterrupt& interrupt, bool _replySent) |
528 | 171k | : req(_req), m_interrupt(interrupt), replySent(_replySent) |
529 | 171k | { |
530 | 171k | } |
531 | | |
532 | | HTTPRequest::~HTTPRequest() |
533 | 171k | { |
534 | 171k | if (!replySent) { |
535 | | // Keep track of whether reply was sent to avoid request leaks |
536 | 0 | LogWarning("Unhandled HTTP request"); |
537 | 0 | WriteReply(HTTP_INTERNAL_SERVER_ERROR, "Unhandled request"); |
538 | 0 | } |
539 | | // evhttpd cleans up the request, as long as a reply was sent. |
540 | 171k | } |
541 | | |
542 | | std::pair<bool, std::string> HTTPRequest::GetHeader(const std::string& hdr) const |
543 | 171k | { |
544 | 171k | const struct evkeyvalq* headers = evhttp_request_get_input_headers(req); |
545 | 171k | assert(headers); |
546 | 171k | const char* val = evhttp_find_header(headers, hdr.c_str()); |
547 | 171k | if (val) |
548 | 171k | return std::make_pair(true, val); |
549 | 0 | else |
550 | 0 | return std::make_pair(false, ""); |
551 | 171k | } |
552 | | |
553 | | std::string HTTPRequest::ReadBody() |
554 | 171k | { |
555 | 171k | struct evbuffer* buf = evhttp_request_get_input_buffer(req); |
556 | 171k | if (!buf) |
557 | 0 | return ""; |
558 | 171k | size_t size = evbuffer_get_length(buf); |
559 | | /** Trivial implementation: if this is ever a performance bottleneck, |
560 | | * internal copying can be avoided in multi-segment buffers by using |
561 | | * evbuffer_peek and an awkward loop. Though in that case, it'd be even |
562 | | * better to not copy into an intermediate string but use a stream |
563 | | * abstraction to consume the evbuffer on the fly in the parsing algorithm. |
564 | | */ |
565 | 171k | const char* data = (const char*)evbuffer_pullup(buf, size); |
566 | 171k | if (!data) // returns nullptr in case of empty buffer |
567 | 18 | return ""; |
568 | 171k | std::string rv(data, size); |
569 | 171k | evbuffer_drain(buf, size); |
570 | 171k | return rv; |
571 | 171k | } |
572 | | |
573 | | void HTTPRequest::WriteHeader(const std::string& hdr, const std::string& value) |
574 | 172k | { |
575 | 172k | struct evkeyvalq* headers = evhttp_request_get_output_headers(req); |
576 | 172k | assert(headers); |
577 | 172k | evhttp_add_header(headers, hdr.c_str(), value.c_str()); |
578 | 172k | } |
579 | | |
580 | | /** Closure sent to main thread to request a reply to be sent to |
581 | | * a HTTP request. |
582 | | * Replies must be sent in the main loop in the main http thread, |
583 | | * this cannot be done from worker threads. |
584 | | */ |
585 | | void HTTPRequest::WriteReply(int nStatus, std::span<const std::byte> reply) |
586 | 171k | { |
587 | 171k | assert(!replySent && req); |
588 | 171k | if (m_interrupt) { |
589 | 978 | WriteHeader("Connection", "close"); |
590 | 978 | } |
591 | | // Send event to main http thread to send reply message |
592 | 171k | struct evbuffer* evb = evhttp_request_get_output_buffer(req); |
593 | 171k | assert(evb); |
594 | 171k | evbuffer_add(evb, reply.data(), reply.size()); |
595 | 171k | auto req_copy = req; |
596 | 171k | HTTPEvent* ev = new HTTPEvent(eventBase, true, [req_copy, nStatus]{ |
597 | 171k | evhttp_send_reply(req_copy, nStatus, nullptr, nullptr); |
598 | | // Re-enable reading from the socket. This is the second part of the libevent |
599 | | // workaround above. |
600 | 171k | if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02010900) { |
601 | 0 | evhttp_connection* conn = evhttp_request_get_connection(req_copy); |
602 | 0 | if (conn) { |
603 | 0 | bufferevent* bev = evhttp_connection_get_bufferevent(conn); |
604 | 0 | if (bev) { |
605 | 0 | bufferevent_enable(bev, EV_READ | EV_WRITE); |
606 | 0 | } |
607 | 0 | } |
608 | 0 | } |
609 | 171k | }); |
610 | 171k | ev->trigger(nullptr); |
611 | 171k | replySent = true; |
612 | 171k | req = nullptr; // transferred back to main thread |
613 | 171k | } |
614 | | |
615 | | CService HTTPRequest::GetPeer() const |
616 | 514k | { |
617 | 514k | evhttp_connection* con = evhttp_request_get_connection(req); |
618 | 514k | CService peer; |
619 | 514k | if (con) { |
620 | | // evhttp retains ownership over returned address string |
621 | 514k | const char* address = ""; |
622 | 514k | uint16_t port = 0; |
623 | | |
624 | | #ifdef HAVE_EVHTTP_CONNECTION_GET_PEER_CONST_CHAR |
625 | | evhttp_connection_get_peer(con, &address, &port); |
626 | | #else |
627 | 514k | evhttp_connection_get_peer(con, (char**)&address, &port); |
628 | 514k | #endif // HAVE_EVHTTP_CONNECTION_GET_PEER_CONST_CHAR |
629 | | |
630 | 514k | peer = MaybeFlipIPv6toCJDNS(LookupNumeric(address, port)); |
631 | 514k | } |
632 | 514k | return peer; |
633 | 514k | } |
634 | | |
635 | | std::string HTTPRequest::GetURI() const |
636 | 514k | { |
637 | 514k | return evhttp_request_get_uri(req); |
638 | 514k | } |
639 | | |
640 | | HTTPRequest::RequestMethod HTTPRequest::GetRequestMethod() const |
641 | 514k | { |
642 | 514k | switch (evhttp_request_get_command(req)) { |
643 | 1.49k | case EVHTTP_REQ_GET: |
644 | 1.49k | return GET; |
645 | 513k | case EVHTTP_REQ_POST: |
646 | 513k | return POST; |
647 | 0 | case EVHTTP_REQ_HEAD: |
648 | 0 | return HEAD; |
649 | 0 | case EVHTTP_REQ_PUT: |
650 | 0 | return PUT; |
651 | 0 | default: |
652 | 0 | return UNKNOWN; |
653 | 514k | } |
654 | 514k | } |
655 | | |
656 | | std::optional<std::string> HTTPRequest::GetQueryParameter(const std::string& key) const |
657 | 85 | { |
658 | 85 | const char* uri{evhttp_request_get_uri(req)}; |
659 | | |
660 | 85 | return GetQueryParameterFromUri(uri, key); |
661 | 85 | } |
662 | | |
663 | | std::optional<std::string> GetQueryParameterFromUri(const char* uri, const std::string& key) |
664 | 93 | { |
665 | 93 | evhttp_uri* uri_parsed{evhttp_uri_parse(uri)}; |
666 | 93 | if (!uri_parsed) { |
667 | 6 | throw std::runtime_error("URI parsing failed, it likely contained RFC 3986 invalid characters"); |
668 | 6 | } |
669 | 87 | const char* query{evhttp_uri_get_query(uri_parsed)}; |
670 | 87 | std::optional<std::string> result; |
671 | | |
672 | 87 | if (query) { |
673 | | // Parse the query string into a key-value queue and iterate over it |
674 | 80 | struct evkeyvalq params_q; |
675 | 80 | evhttp_parse_query_str(query, ¶ms_q); |
676 | | |
677 | 112 | for (struct evkeyval* param{params_q.tqh_first}; param != nullptr; param = param->next.tqe_next) { |
678 | 104 | if (param->key == key) { |
679 | 72 | result = param->value; |
680 | 72 | break; |
681 | 72 | } |
682 | 104 | } |
683 | 80 | evhttp_clear_headers(¶ms_q); |
684 | 80 | } |
685 | 87 | evhttp_uri_free(uri_parsed); |
686 | | |
687 | 87 | return result; |
688 | 93 | } |
689 | | |
690 | | void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler) |
691 | 2.21k | { |
692 | 2.21k | LogDebug(BCLog::HTTP, "Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch); |
693 | 2.21k | LOCK(g_httppathhandlers_mutex); |
694 | 2.21k | pathHandlers.emplace_back(prefix, exactMatch, handler); |
695 | 2.21k | } |
696 | | |
697 | | void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch) |
698 | 18.4k | { |
699 | 18.4k | LOCK(g_httppathhandlers_mutex); |
700 | 18.4k | std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin(); |
701 | 18.4k | std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end(); |
702 | 18.4k | for (; i != iend; ++i) |
703 | 2.21k | if (i->prefix == prefix && i->exactMatch == exactMatch) |
704 | 2.21k | break; |
705 | 18.4k | if (i != iend) |
706 | 2.21k | { |
707 | 2.21k | LogDebug(BCLog::HTTP, "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch); |
708 | 2.21k | pathHandlers.erase(i); |
709 | 2.21k | } |
710 | 18.4k | } |