Bitcoin Core 29.99.0
P2P Digital Currency
httpserver.cpp
Go to the documentation of this file.
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>
18#include <util/strencodings.h>
19#include <util/threadnames.h>
20#include <util/translation.h>
21
22#include <condition_variable>
23#include <cstdio>
24#include <cstdlib>
25#include <deque>
26#include <memory>
27#include <optional>
28#include <span>
29#include <string>
30#include <thread>
31#include <unordered_map>
32#include <vector>
33
34#include <sys/types.h>
35#include <sys/stat.h>
36
37#include <event2/buffer.h>
38#include <event2/bufferevent.h>
39#include <event2/http.h>
40#include <event2/http_struct.h>
41#include <event2/keyvalq_struct.h>
42#include <event2/thread.h>
43#include <event2/util.h>
44
45#include <support/events.h>
46
48
50static const size_t MAX_HEADERS_SIZE = 8192;
51
53class HTTPWorkItem final : public HTTPClosure
54{
55public:
56 HTTPWorkItem(std::unique_ptr<HTTPRequest> _req, const std::string &_path, const HTTPRequestHandler& _func):
57 req(std::move(_req)), path(_path), func(_func)
58 {
59 }
60 void operator()() override
61 {
62 func(req.get(), path);
63 }
64
65 std::unique_ptr<HTTPRequest> req;
66
67private:
68 std::string path;
70};
71
75template <typename WorkItem>
77{
78private:
80 std::condition_variable cond GUARDED_BY(cs);
81 std::deque<std::unique_ptr<WorkItem>> queue GUARDED_BY(cs);
82 bool running GUARDED_BY(cs){true};
83 const size_t maxDepth;
84
85public:
86 explicit WorkQueue(size_t _maxDepth) : maxDepth(_maxDepth)
87 {
88 }
91 ~WorkQueue() = default;
93 bool Enqueue(WorkItem* item) EXCLUSIVE_LOCKS_REQUIRED(!cs)
94 {
95 LOCK(cs);
96 if (!running || queue.size() >= maxDepth) {
97 return false;
98 }
99 queue.emplace_back(std::unique_ptr<WorkItem>(item));
100 cond.notify_one();
101 return true;
102 }
105 {
106 while (true) {
107 std::unique_ptr<WorkItem> i;
108 {
109 WAIT_LOCK(cs, lock);
110 while (running && queue.empty())
111 cond.wait(lock);
112 if (!running && queue.empty())
113 break;
114 i = std::move(queue.front());
115 queue.pop_front();
116 }
117 (*i)();
118 }
119 }
122 {
123 LOCK(cs);
124 running = false;
125 cond.notify_all();
126 }
127};
128
130{
131 HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler):
132 prefix(_prefix), exactMatch(_exactMatch), handler(_handler)
133 {
134 }
135 std::string prefix;
138};
139
143static struct event_base* eventBase = nullptr;
145static struct evhttp* eventHTTP = nullptr;
147static std::vector<CSubNet> rpc_allow_subnets;
149static std::unique_ptr<WorkQueue<HTTPClosure>> g_work_queue{nullptr};
152static std::vector<HTTPPathHandler> pathHandlers GUARDED_BY(g_httppathhandlers_mutex);
154static std::vector<evhttp_bound_socket *> boundSockets;
155
161{
162private:
163 mutable Mutex m_mutex;
164 mutable std::condition_variable m_cv;
166 std::unordered_map<const evhttp_connection*, size_t> m_tracker GUARDED_BY(m_mutex);
167
168 void RemoveConnectionInternal(const decltype(m_tracker)::iterator it) EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
169 {
170 m_tracker.erase(it);
171 if (m_tracker.empty()) m_cv.notify_all();
172 }
173public:
175 void AddRequest(evhttp_request* req) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
176 {
177 const evhttp_connection* conn{Assert(evhttp_request_get_connection(Assert(req)))};
178 WITH_LOCK(m_mutex, ++m_tracker[conn]);
179 }
182 {
183 const evhttp_connection* conn{Assert(evhttp_request_get_connection(Assert(req)))};
184 LOCK(m_mutex);
185 auto it{m_tracker.find(conn)};
186 if (it != m_tracker.end() && it->second > 0) {
187 if (--(it->second) == 0) RemoveConnectionInternal(it);
188 }
189 }
191 void RemoveConnection(const evhttp_connection* conn) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
192 {
193 LOCK(m_mutex);
194 auto it{m_tracker.find(Assert(conn))};
195 if (it != m_tracker.end()) RemoveConnectionInternal(it);
196 }
198 {
199 return WITH_LOCK(m_mutex, return m_tracker.size());
200 }
203 {
204 WAIT_LOCK(m_mutex, lock);
205 m_cv.wait(lock, [this]() EXCLUSIVE_LOCKS_REQUIRED(m_mutex) { return m_tracker.empty(); });
206 }
207};
210
212static bool ClientAllowed(const CNetAddr& netaddr)
213{
214 if (!netaddr.IsValid())
215 return false;
216 for(const CSubNet& subnet : rpc_allow_subnets)
217 if (subnet.Match(netaddr))
218 return true;
219 return false;
220}
221
223static bool InitHTTPAllowList()
224{
225 rpc_allow_subnets.clear();
226 rpc_allow_subnets.emplace_back(LookupHost("127.0.0.1", false).value(), 8); // always allow IPv4 local subnet
227 rpc_allow_subnets.emplace_back(LookupHost("::1", false).value()); // always allow IPv6 localhost
228 for (const std::string& strAllow : gArgs.GetArgs("-rpcallowip")) {
229 const CSubNet subnet{LookupSubNet(strAllow)};
230 if (!subnet.IsValid()) {
231 uiInterface.ThreadSafeMessageBox(
232 Untranslated(strprintf("Invalid -rpcallowip subnet specification: %s. Valid are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24).", strAllow)),
234 return false;
235 }
236 rpc_allow_subnets.push_back(subnet);
237 }
238 std::string strAllowed;
239 for (const CSubNet& subnet : rpc_allow_subnets)
240 strAllowed += subnet.ToString() + " ";
241 LogDebug(BCLog::HTTP, "Allowing HTTP connections from: %s\n", strAllowed);
242 return true;
243}
244
247{
248 switch (m) {
249 case HTTPRequest::GET:
250 return "GET";
252 return "POST";
254 return "HEAD";
255 case HTTPRequest::PUT:
256 return "PUT";
258 return "unknown";
259 } // no default case, so the compiler can warn about missing cases
260 assert(false);
261}
262
264static void http_request_cb(struct evhttp_request* req, void* arg)
265{
266 evhttp_connection* conn{evhttp_request_get_connection(req)};
267 // Track active requests
268 {
270 evhttp_request_set_on_complete_cb(req, [](struct evhttp_request* req, void*) {
272 }, nullptr);
273 evhttp_connection_set_closecb(conn, [](evhttp_connection* conn, void* arg) {
275 }, nullptr);
276 }
277
278 // Disable reading to work around a libevent bug, fixed in 2.1.9
279 // See https://github.com/libevent/libevent/commit/5ff8eb26371c4dc56f384b2de35bea2d87814779
280 // and https://github.com/bitcoin/bitcoin/pull/11593.
281 if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02010900) {
282 if (conn) {
283 bufferevent* bev = evhttp_connection_get_bufferevent(conn);
284 if (bev) {
285 bufferevent_disable(bev, EV_READ);
286 }
287 }
288 }
289 auto hreq{std::make_unique<HTTPRequest>(req, *static_cast<const util::SignalInterrupt*>(arg))};
290
291 // Early address-based allow check
292 if (!ClientAllowed(hreq->GetPeer())) {
293 LogDebug(BCLog::HTTP, "HTTP request from %s rejected: Client network is not allowed RPC access\n",
294 hreq->GetPeer().ToStringAddrPort());
295 hreq->WriteReply(HTTP_FORBIDDEN);
296 return;
297 }
298
299 // Early reject unknown HTTP methods
300 if (hreq->GetRequestMethod() == HTTPRequest::UNKNOWN) {
301 LogDebug(BCLog::HTTP, "HTTP request from %s rejected: Unknown HTTP request method\n",
302 hreq->GetPeer().ToStringAddrPort());
303 hreq->WriteReply(HTTP_BAD_METHOD);
304 return;
305 }
306
307 LogDebug(BCLog::HTTP, "Received a %s request for %s from %s\n",
308 RequestMethodString(hreq->GetRequestMethod()), SanitizeString(hreq->GetURI(), SAFE_CHARS_URI).substr(0, 100), hreq->GetPeer().ToStringAddrPort());
309
310 // Find registered handler for prefix
311 std::string strURI = hreq->GetURI();
312 std::string path;
314 std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin();
315 std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end();
316 for (; i != iend; ++i) {
317 bool match = false;
318 if (i->exactMatch)
319 match = (strURI == i->prefix);
320 else
321 match = strURI.starts_with(i->prefix);
322 if (match) {
323 path = strURI.substr(i->prefix.size());
324 break;
325 }
326 }
327
328 // Dispatch to worker thread
329 if (i != iend) {
330 std::unique_ptr<HTTPWorkItem> item(new HTTPWorkItem(std::move(hreq), path, i->handler));
332 if (g_work_queue->Enqueue(item.get())) {
333 item.release(); /* if true, queue took ownership */
334 } else {
335 LogPrintf("WARNING: request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting\n");
336 item->req->WriteReply(HTTP_SERVICE_UNAVAILABLE, "Work queue depth exceeded");
337 }
338 } else {
339 hreq->WriteReply(HTTP_NOT_FOUND);
340 }
341}
342
344static void http_reject_request_cb(struct evhttp_request* req, void*)
345{
346 LogDebug(BCLog::HTTP, "Rejecting request while shutting down\n");
347 evhttp_send_error(req, HTTP_SERVUNAVAIL, nullptr);
348}
349
351static void ThreadHTTP(struct event_base* base)
352{
353 util::ThreadRename("http");
354 LogDebug(BCLog::HTTP, "Entering http event loop\n");
355 event_base_dispatch(base);
356 // Event loop will be interrupted by InterruptHTTPServer()
357 LogDebug(BCLog::HTTP, "Exited http event loop\n");
358}
359
361static bool HTTPBindAddresses(struct evhttp* http)
362{
363 uint16_t http_port{static_cast<uint16_t>(gArgs.GetIntArg("-rpcport", BaseParams().RPCPort()))};
364 std::vector<std::pair<std::string, uint16_t>> endpoints;
365
366 // Determine what addresses to bind to
367 // To prevent misconfiguration and accidental exposure of the RPC
368 // interface, require -rpcallowip and -rpcbind to both be specified
369 // together. If either is missing, ignore both values, bind to localhost
370 // instead, and log warnings.
371 if (gArgs.GetArgs("-rpcallowip").empty() || gArgs.GetArgs("-rpcbind").empty()) { // Default to loopback if not allowing external IPs
372 endpoints.emplace_back("::1", http_port);
373 endpoints.emplace_back("127.0.0.1", http_port);
374 if (!gArgs.GetArgs("-rpcallowip").empty()) {
375 LogPrintf("WARNING: option -rpcallowip was specified without -rpcbind; this doesn't usually make sense\n");
376 }
377 if (!gArgs.GetArgs("-rpcbind").empty()) {
378 LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
379 }
380 } else { // Specific bind addresses
381 for (const std::string& strRPCBind : gArgs.GetArgs("-rpcbind")) {
382 uint16_t port{http_port};
383 std::string host;
384 if (!SplitHostPort(strRPCBind, port, host)) {
385 LogError("%s\n", InvalidPortErrMsg("-rpcbind", strRPCBind).original);
386 return false;
387 }
388 endpoints.emplace_back(host, port);
389 }
390 }
391
392 // Bind addresses
393 for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
394 LogPrintf("Binding RPC on address %s port %i\n", i->first, i->second);
395 evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? nullptr : i->first.c_str(), i->second);
396 if (bind_handle) {
397 const std::optional<CNetAddr> addr{LookupHost(i->first, false)};
398 if (i->first.empty() || (addr.has_value() && addr->IsBindAny())) {
399 LogPrintf("WARNING: the RPC server is not safe to expose to untrusted networks such as the public internet\n");
400 }
401 // Set the no-delay option (disable Nagle's algorithm) on the TCP socket.
402 evutil_socket_t fd = evhttp_bound_socket_get_fd(bind_handle);
403 int one = 1;
404 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (sockopt_arg_type)&one, sizeof(one)) == SOCKET_ERROR) {
405 LogInfo("WARNING: Unable to set TCP_NODELAY on RPC server socket, continuing anyway\n");
406 }
407 boundSockets.push_back(bind_handle);
408 } else {
409 LogPrintf("Binding RPC on address %s port %i failed.\n", i->first, i->second);
410 }
411 }
412 return !boundSockets.empty();
413}
414
416static void HTTPWorkQueueRun(WorkQueue<HTTPClosure>* queue, int worker_num)
417{
418 util::ThreadRename(strprintf("httpworker.%i", worker_num));
419 queue->Run();
420}
421
423static void libevent_log_cb(int severity, const char *msg)
424{
425 BCLog::Level level;
426 switch (severity) {
427 case EVENT_LOG_DEBUG:
428 level = BCLog::Level::Debug;
429 break;
430 case EVENT_LOG_MSG:
431 level = BCLog::Level::Info;
432 break;
433 case EVENT_LOG_WARN:
434 level = BCLog::Level::Warning;
435 break;
436 default: // EVENT_LOG_ERR and others are mapped to error
437 level = BCLog::Level::Error;
438 break;
439 }
440 LogPrintLevel(BCLog::LIBEVENT, level, "%s\n", msg);
441}
442
444{
445 if (!InitHTTPAllowList())
446 return false;
447
448 // Redirect libevent's logging to our own log
449 event_set_log_callback(&libevent_log_cb);
450 // Update libevent's log handling.
452
453#ifdef WIN32
454 evthread_use_windows_threads();
455#else
456 evthread_use_pthreads();
457#endif
458
459 raii_event_base base_ctr = obtain_event_base();
460
461 /* Create a new evhttp object to handle requests. */
462 raii_evhttp http_ctr = obtain_evhttp(base_ctr.get());
463 struct evhttp* http = http_ctr.get();
464 if (!http) {
465 LogPrintf("couldn't create evhttp. Exiting.\n");
466 return false;
467 }
468
469 evhttp_set_timeout(http, gArgs.GetIntArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
470 evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
471 evhttp_set_max_body_size(http, MAX_SIZE);
472 evhttp_set_gencb(http, http_request_cb, (void*)&interrupt);
473
474 if (!HTTPBindAddresses(http)) {
475 LogPrintf("Unable to bind any endpoint for RPC server\n");
476 return false;
477 }
478
479 LogDebug(BCLog::HTTP, "Initialized HTTP server\n");
480 int workQueueDepth = std::max((long)gArgs.GetIntArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
481 LogDebug(BCLog::HTTP, "creating work queue of depth %d\n", workQueueDepth);
482
483 g_work_queue = std::make_unique<WorkQueue<HTTPClosure>>(workQueueDepth);
484 // transfer ownership to eventBase/HTTP via .release()
485 eventBase = base_ctr.release();
486 eventHTTP = http_ctr.release();
487 return true;
488}
489
490void UpdateHTTPServerLogging(bool enable) {
491 if (enable) {
492 event_enable_debug_logging(EVENT_DBG_ALL);
493 } else {
494 event_enable_debug_logging(EVENT_DBG_NONE);
495 }
496}
497
498static std::thread g_thread_http;
499static std::vector<std::thread> g_thread_http_workers;
500
502{
503 int rpcThreads = std::max((long)gArgs.GetIntArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L);
504 LogInfo("Starting HTTP server with %d worker threads\n", rpcThreads);
505 g_thread_http = std::thread(ThreadHTTP, eventBase);
506
507 for (int i = 0; i < rpcThreads; i++) {
509 }
510}
511
513{
514 LogDebug(BCLog::HTTP, "Interrupting HTTP server\n");
515 if (eventHTTP) {
516 // Reject requests on current connections
517 evhttp_set_gencb(eventHTTP, http_reject_request_cb, nullptr);
518 }
519 if (g_work_queue) {
520 g_work_queue->Interrupt();
521 }
522}
523
525{
526 LogDebug(BCLog::HTTP, "Stopping HTTP server\n");
527 if (g_work_queue) {
528 LogDebug(BCLog::HTTP, "Waiting for HTTP worker threads to exit\n");
529 for (auto& thread : g_thread_http_workers) {
530 thread.join();
531 }
532 g_thread_http_workers.clear();
533 }
534 // Unlisten sockets, these are what make the event loop running, which means
535 // that after this and all connections are closed the event loop will quit.
536 for (evhttp_bound_socket *socket : boundSockets) {
537 evhttp_del_accept_socket(eventHTTP, socket);
538 }
539 boundSockets.clear();
540 {
541 if (const auto n_connections{g_requests.CountActiveConnections()}; n_connections != 0) {
542 LogDebug(BCLog::HTTP, "Waiting for %d connections to stop HTTP server\n", n_connections);
543 }
545 }
546 if (eventHTTP) {
547 // Schedule a callback to call evhttp_free in the event base thread, so
548 // that evhttp_free does not need to be called again after the handling
549 // of unfinished request connections that follows.
550 event_base_once(eventBase, -1, EV_TIMEOUT, [](evutil_socket_t, short, void*) {
551 evhttp_free(eventHTTP);
552 eventHTTP = nullptr;
553 }, nullptr, nullptr);
554 }
555 if (eventBase) {
556 LogDebug(BCLog::HTTP, "Waiting for HTTP event thread to exit\n");
557 if (g_thread_http.joinable()) g_thread_http.join();
558 event_base_free(eventBase);
559 eventBase = nullptr;
560 }
561 g_work_queue.reset();
562 LogDebug(BCLog::HTTP, "Stopped HTTP server\n");
563}
564
565struct event_base* EventBase()
566{
567 return eventBase;
568}
569
570static void httpevent_callback_fn(evutil_socket_t, short, void* data)
571{
572 // Static handler: simply call inner handler
573 HTTPEvent *self = static_cast<HTTPEvent*>(data);
574 self->handler();
575 if (self->deleteWhenTriggered)
576 delete self;
577}
578
579HTTPEvent::HTTPEvent(struct event_base* base, bool _deleteWhenTriggered, const std::function<void()>& _handler):
580 deleteWhenTriggered(_deleteWhenTriggered), handler(_handler)
581{
582 ev = event_new(base, -1, 0, httpevent_callback_fn, this);
583 assert(ev);
584}
586{
587 event_free(ev);
588}
589void HTTPEvent::trigger(struct timeval* tv)
590{
591 if (tv == nullptr)
592 event_active(ev, 0, 0); // immediately trigger event in main thread
593 else
594 evtimer_add(ev, tv); // trigger after timeval passed
595}
596HTTPRequest::HTTPRequest(struct evhttp_request* _req, const util::SignalInterrupt& interrupt, bool _replySent)
597 : req(_req), m_interrupt(interrupt), replySent(_replySent)
598{
599}
600
602{
603 if (!replySent) {
604 // Keep track of whether reply was sent to avoid request leaks
605 LogPrintf("%s: Unhandled request\n", __func__);
606 WriteReply(HTTP_INTERNAL_SERVER_ERROR, "Unhandled request");
607 }
608 // evhttpd cleans up the request, as long as a reply was sent.
609}
610
611std::pair<bool, std::string> HTTPRequest::GetHeader(const std::string& hdr) const
612{
613 const struct evkeyvalq* headers = evhttp_request_get_input_headers(req);
614 assert(headers);
615 const char* val = evhttp_find_header(headers, hdr.c_str());
616 if (val)
617 return std::make_pair(true, val);
618 else
619 return std::make_pair(false, "");
620}
621
623{
624 struct evbuffer* buf = evhttp_request_get_input_buffer(req);
625 if (!buf)
626 return "";
627 size_t size = evbuffer_get_length(buf);
634 const char* data = (const char*)evbuffer_pullup(buf, size);
635 if (!data) // returns nullptr in case of empty buffer
636 return "";
637 std::string rv(data, size);
638 evbuffer_drain(buf, size);
639 return rv;
640}
641
642void HTTPRequest::WriteHeader(const std::string& hdr, const std::string& value)
643{
644 struct evkeyvalq* headers = evhttp_request_get_output_headers(req);
645 assert(headers);
646 evhttp_add_header(headers, hdr.c_str(), value.c_str());
647}
648
654void HTTPRequest::WriteReply(int nStatus, std::span<const std::byte> reply)
655{
656 assert(!replySent && req);
657 if (m_interrupt) {
658 WriteHeader("Connection", "close");
659 }
660 // Send event to main http thread to send reply message
661 struct evbuffer* evb = evhttp_request_get_output_buffer(req);
662 assert(evb);
663 evbuffer_add(evb, reply.data(), reply.size());
664 auto req_copy = req;
665 HTTPEvent* ev = new HTTPEvent(eventBase, true, [req_copy, nStatus]{
666 evhttp_send_reply(req_copy, nStatus, nullptr, nullptr);
667 // Re-enable reading from the socket. This is the second part of the libevent
668 // workaround above.
669 if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02010900) {
670 evhttp_connection* conn = evhttp_request_get_connection(req_copy);
671 if (conn) {
672 bufferevent* bev = evhttp_connection_get_bufferevent(conn);
673 if (bev) {
674 bufferevent_enable(bev, EV_READ | EV_WRITE);
675 }
676 }
677 }
678 });
679 ev->trigger(nullptr);
680 replySent = true;
681 req = nullptr; // transferred back to main thread
682}
683
685{
686 evhttp_connection* con = evhttp_request_get_connection(req);
687 CService peer;
688 if (con) {
689 // evhttp retains ownership over returned address string
690 const char* address = "";
691 uint16_t port = 0;
692
693#ifdef HAVE_EVHTTP_CONNECTION_GET_PEER_CONST_CHAR
694 evhttp_connection_get_peer(con, &address, &port);
695#else
696 evhttp_connection_get_peer(con, (char**)&address, &port);
697#endif // HAVE_EVHTTP_CONNECTION_GET_PEER_CONST_CHAR
698
699 peer = MaybeFlipIPv6toCJDNS(LookupNumeric(address, port));
700 }
701 return peer;
702}
703
704std::string HTTPRequest::GetURI() const
705{
706 return evhttp_request_get_uri(req);
707}
708
710{
711 switch (evhttp_request_get_command(req)) {
712 case EVHTTP_REQ_GET:
713 return GET;
714 case EVHTTP_REQ_POST:
715 return POST;
716 case EVHTTP_REQ_HEAD:
717 return HEAD;
718 case EVHTTP_REQ_PUT:
719 return PUT;
720 default:
721 return UNKNOWN;
722 }
723}
724
725std::optional<std::string> HTTPRequest::GetQueryParameter(const std::string& key) const
726{
727 const char* uri{evhttp_request_get_uri(req)};
728
729 return GetQueryParameterFromUri(uri, key);
730}
731
732std::optional<std::string> GetQueryParameterFromUri(const char* uri, const std::string& key)
733{
734 evhttp_uri* uri_parsed{evhttp_uri_parse(uri)};
735 if (!uri_parsed) {
736 throw std::runtime_error("URI parsing failed, it likely contained RFC 3986 invalid characters");
737 }
738 const char* query{evhttp_uri_get_query(uri_parsed)};
739 std::optional<std::string> result;
740
741 if (query) {
742 // Parse the query string into a key-value queue and iterate over it
743 struct evkeyvalq params_q;
744 evhttp_parse_query_str(query, &params_q);
745
746 for (struct evkeyval* param{params_q.tqh_first}; param != nullptr; param = param->next.tqe_next) {
747 if (param->key == key) {
748 result = param->value;
749 break;
750 }
751 }
752 evhttp_clear_headers(&params_q);
753 }
754 evhttp_uri_free(uri_parsed);
755
756 return result;
757}
758
759void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
760{
761 LogDebug(BCLog::HTTP, "Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
763 pathHandlers.emplace_back(prefix, exactMatch, handler);
764}
765
766void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
767{
769 std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
770 std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
771 for (; i != iend; ++i)
772 if (i->prefix == prefix && i->exactMatch == exactMatch)
773 break;
774 if (i != iend)
775 {
776 LogDebug(BCLog::HTTP, "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
777 pathHandlers.erase(i);
778 }
779}
ArgsManager gArgs
Definition: args.cpp:42
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
#define Assert(val)
Identity function.
Definition: check.h:106
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: args.cpp:362
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: args.cpp:482
Network address.
Definition: netaddress.h:112
bool IsValid() const
Definition: netaddress.cpp:428
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:531
Different type to mark Mutex at global scope.
Definition: sync.h:140
Event handler closure.
Definition: httpserver.h:165
Event class.
Definition: httpserver.h:174
struct event * ev
Definition: httpserver.h:191
bool deleteWhenTriggered
Definition: httpserver.h:188
std::function< void()> handler
Definition: httpserver.h:189
HTTPEvent(struct event_base *base, bool deleteWhenTriggered, const std::function< void()> &handler)
Create a new event.
Definition: httpserver.cpp:579
void trigger(struct timeval *tv)
Trigger the event.
Definition: httpserver.cpp:589
std::optional< std::string > GetQueryParameter(const std::string &key) const
Get the query parameter value from request uri for a specified key, or std::nullopt if the key is not...
Definition: httpserver.cpp:725
bool replySent
Definition: httpserver.h:75
std::pair< bool, std::string > GetHeader(const std::string &hdr) const
Get the request header specified by hdr, or an empty string.
Definition: httpserver.cpp:611
std::string GetURI() const
Get requested URI.
Definition: httpserver.cpp:704
void WriteReply(int nStatus, std::string_view reply="")
Write HTTP reply.
Definition: httpserver.h:141
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
Definition: httpserver.cpp:642
HTTPRequest(struct evhttp_request *req, const util::SignalInterrupt &interrupt, bool replySent=false)
Definition: httpserver.cpp:596
struct evhttp_request * req
Definition: httpserver.h:73
RequestMethod GetRequestMethod() const
Get request method.
Definition: httpserver.cpp:709
const util::SignalInterrupt & m_interrupt
Definition: httpserver.h:74
std::string ReadBody()
Read request body.
Definition: httpserver.cpp:622
CService GetPeer() const
Get CService (address:ip) for the origin of the http request.
Definition: httpserver.cpp:684
Helps keep track of open evhttp_connections with active evhttp_requests
Definition: httpserver.cpp:161
void WaitUntilEmpty() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Wait until there are no more connections with active requests in the tracker.
Definition: httpserver.cpp:202
size_t CountActiveConnections() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Definition: httpserver.cpp:197
void AddRequest(evhttp_request *req) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Increase request counter for the associated connection by 1.
Definition: httpserver.cpp:175
void RemoveConnection(const evhttp_connection *conn) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Remove a connection entirely.
Definition: httpserver.cpp:191
std::unordered_map< const evhttp_connection *, size_t > m_tracker GUARDED_BY(m_mutex)
For each connection, keep a counter of how many requests are open.
void RemoveRequest(evhttp_request *req) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Decrease request counter for the associated connection by 1, remove connection if counter is 0.
Definition: httpserver.cpp:181
std::condition_variable m_cv
Definition: httpserver.cpp:164
void RemoveConnectionInternal(const decltype(m_tracker)::iterator it) EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Definition: httpserver.cpp:168
HTTP request work item.
Definition: httpserver.cpp:54
void operator()() override
Definition: httpserver.cpp:60
std::unique_ptr< HTTPRequest > req
Definition: httpserver.cpp:65
HTTPWorkItem(std::unique_ptr< HTTPRequest > _req, const std::string &_path, const HTTPRequestHandler &_func)
Definition: httpserver.cpp:56
std::string path
Definition: httpserver.cpp:68
HTTPRequestHandler func
Definition: httpserver.cpp:69
Simple work queue for distributing work over multiple threads.
Definition: httpserver.cpp:77
const size_t maxDepth
Definition: httpserver.cpp:83
bool Enqueue(WorkItem *item) EXCLUSIVE_LOCKS_REQUIRED(!cs)
Enqueue a work item.
Definition: httpserver.cpp:93
~WorkQueue()=default
Precondition: worker threads have all stopped (they have been joined).
std::deque< std::unique_ptr< WorkItem > > queue GUARDED_BY(cs)
std::condition_variable cond GUARDED_BY(cs)
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!cs)
Interrupt and exit loops.
Definition: httpserver.cpp:121
Mutex cs
Definition: httpserver.cpp:79
bool running GUARDED_BY(cs)
Definition: httpserver.cpp:82
WorkQueue(size_t _maxDepth)
Definition: httpserver.cpp:86
void Run() EXCLUSIVE_LOCKS_REQUIRED(!cs)
Thread function.
Definition: httpserver.cpp:104
Helper class that manages an interrupt flag, and allows a thread or signal to interrupt another threa...
#define SOCKET_ERROR
Definition: compat.h:56
void * sockopt_arg_type
Definition: compat.h:81
raii_evhttp obtain_evhttp(struct event_base *base)
Definition: events.h:41
raii_event_base obtain_event_base()
Definition: events.h:30
static struct evhttp * eventHTTP
HTTP server.
Definition: httpserver.cpp:145
void InterruptHTTPServer()
Interrupt HTTP server threads.
Definition: httpserver.cpp:512
static void http_request_cb(struct evhttp_request *req, void *arg)
HTTP request callback.
Definition: httpserver.cpp:264
static bool HTTPBindAddresses(struct evhttp *http)
Bind HTTP server to specified addresses.
Definition: httpserver.cpp:361
static std::vector< evhttp_bound_socket * > boundSockets
Bound listening sockets.
Definition: httpserver.cpp:154
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
Definition: httpserver.cpp:766
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
Definition: httpserver.cpp:759
std::optional< std::string > GetQueryParameterFromUri(const char *uri, const std::string &key)
Get the query parameter value from request uri for a specified key, or std::nullopt if the key is not...
Definition: httpserver.cpp:732
void StartHTTPServer()
Start HTTP server.
Definition: httpserver.cpp:501
static struct event_base * eventBase
HTTP module state.
Definition: httpserver.cpp:143
void UpdateHTTPServerLogging(bool enable)
Change logging level for libevent.
Definition: httpserver.cpp:490
static std::thread g_thread_http
Definition: httpserver.cpp:498
static std::unique_ptr< WorkQueue< HTTPClosure > > g_work_queue
Work queue for handling longer requests off the event loop thread.
Definition: httpserver.cpp:149
struct event_base * EventBase()
Return evhttp event base.
Definition: httpserver.cpp:565
static void httpevent_callback_fn(evutil_socket_t, short, void *data)
Definition: httpserver.cpp:570
std::string RequestMethodString(HTTPRequest::RequestMethod m)
HTTP request method as string - use for logging only.
Definition: httpserver.cpp:246
static HTTPRequestTracker g_requests
Track active requests.
Definition: httpserver.cpp:209
bool InitHTTPServer(const util::SignalInterrupt &interrupt)
Initialize HTTP server.
Definition: httpserver.cpp:443
static void HTTPWorkQueueRun(WorkQueue< HTTPClosure > *queue, int worker_num)
Simple wrapper to set thread name and run work queue.
Definition: httpserver.cpp:416
static bool InitHTTPAllowList()
Initialize ACL list for HTTP server.
Definition: httpserver.cpp:223
static void libevent_log_cb(int severity, const char *msg)
libevent event log callback
Definition: httpserver.cpp:423
static std::vector< CSubNet > rpc_allow_subnets
List of subnets to allow RPC connections from.
Definition: httpserver.cpp:147
static bool ClientAllowed(const CNetAddr &netaddr)
Check if a network address is allowed to access the HTTP server.
Definition: httpserver.cpp:212
static void http_reject_request_cb(struct evhttp_request *req, void *)
Callback to reject HTTP requests after shutdown.
Definition: httpserver.cpp:344
static const size_t MAX_HEADERS_SIZE
Maximum size of http request (request line + headers)
Definition: httpserver.cpp:50
void StopHTTPServer()
Stop HTTP server.
Definition: httpserver.cpp:524
static void ThreadHTTP(struct event_base *base)
Event dispatcher thread.
Definition: httpserver.cpp:351
static std::vector< std::thread > g_thread_http_workers
Definition: httpserver.cpp:499
static std::vector< HTTPPathHandler > pathHandlers GUARDED_BY(g_httppathhandlers_mutex)
static GlobalMutex g_httppathhandlers_mutex
Handlers for (sub)paths.
Definition: httpserver.cpp:151
static const int DEFAULT_HTTP_SERVER_TIMEOUT
Definition: httpserver.h:28
static const int DEFAULT_HTTP_WORKQUEUE
The default value for -rpcworkqueue.
Definition: httpserver.h:26
static const int DEFAULT_HTTP_THREADS
The default value for -rpcthreads.
Definition: httpserver.h:20
std::function< bool(HTTPRequest *req, const std::string &)> HTTPRequestHandler
Handler for requests to a certain HTTP path.
Definition: httpserver.h:53
CClientUIInterface uiInterface
BCLog::Logger & LogInstance()
Definition: logging.cpp:24
#define LogPrintLevel(category, level,...)
Definition: logging.h:272
#define LogInfo(...)
Definition: logging.h:261
#define LogError(...)
Definition: logging.h:263
#define LogDebug(category,...)
Definition: logging.h:280
#define LogPrintf(...)
Definition: logging.h:266
is a home for simple string functions returning descriptive messages that are used in RPC and GUI int...
Level
Definition: logging.h:76
@ HTTP
Definition: logging.h:46
@ LIBEVENT
Definition: logging.h:60
bilingual_str InvalidPortErrMsg(const std::string &optname, const std::string &invalid_value)
Definition: messages.cpp:157
void ThreadRename(const std::string &)
Rename a thread both in terms of an internal (in-memory) name as well as its system thread name.
Definition: threadnames.cpp:55
CSubNet LookupSubNet(const std::string &subnet_str)
Parse and resolve a specified subnet string into the appropriate internal representation.
Definition: netbase.cpp:816
std::vector< CNetAddr > LookupHost(const std::string &name, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
Resolve a host string to its corresponding network addresses.
Definition: netbase.cpp:177
CService MaybeFlipIPv6toCJDNS(const CService &service)
If an IPv6 address belongs to the address range used by the CJDNS network and the CJDNS network is re...
Definition: netbase.cpp:941
CService LookupNumeric(const std::string &name, uint16_t portDefault, DNSLookupFn dns_lookup_function)
Resolve a service string with a numeric IP to its first corresponding service.
Definition: netbase.cpp:220
const char * prefix
Definition: rest.cpp:1009
bool(* handler)(const std::any &context, HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:1010
@ HTTP_BAD_METHOD
Definition: protocol.h:18
@ HTTP_SERVICE_UNAVAILABLE
Definition: protocol.h:20
@ HTTP_NOT_FOUND
Definition: protocol.h:17
@ HTTP_FORBIDDEN
Definition: protocol.h:16
@ HTTP_INTERNAL_SERVER_ERROR
Definition: protocol.h:19
static constexpr uint64_t MAX_SIZE
The maximum size of a serialized object in bytes or number of elements (for eg vectors) when the size...
Definition: serialize.h:32
@ SAFE_CHARS_URI
Chars allowed in URIs (RFC 3986)
Definition: strencodings.h:35
std::string prefix
Definition: httpserver.cpp:135
HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler)
Definition: httpserver.cpp:131
HTTPRequestHandler handler
Definition: httpserver.cpp:137
#define WAIT_LOCK(cs, name)
Definition: sync.h:263
#define LOCK(cs)
Definition: sync.h:257
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:302
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:82
bool SplitHostPort(std::string_view in, uint16_t &portOut, std::string &hostOut)
Splits socket address string into host string and port value.
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.
assert(!tx.IsCoinBase())