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