Bitcoin ABC 0.32.11
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/keyvalq_struct.h>
27#include <event2/thread.h>
28#include <event2/util.h>
29
30#include <support/events.h>
31
32#include <sys/stat.h>
33#include <sys/types.h>
34
35#include <condition_variable>
36#include <cstdio>
37#include <cstdlib>
38#include <cstring>
39#include <deque>
40#include <memory>
41#include <unordered_map>
42
44static const size_t MAX_HEADERS_SIZE = 8192;
45
50static const size_t MIN_SUPPORTED_BODY_SIZE = 0x02000000;
51
53class HTTPWorkItem final : public HTTPClosure {
54public:
55 HTTPWorkItem(Config &_config, std::unique_ptr<HTTPRequest> _req,
56 const std::string &_path, const HTTPRequestHandler &_func)
57 : req(std::move(_req)), path(_path), func(_func), config(&_config) {}
58
59 void operator()() override { func(*config, req.get(), path); }
60
61 std::unique_ptr<HTTPRequest> req;
62
63private:
64 std::string path;
67};
68
73template <typename WorkItem> class WorkQueue {
74private:
77 std::condition_variable cond;
78 std::deque<std::unique_ptr<WorkItem>> queue;
79 bool running{true};
80 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 (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) {
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;
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 LogPrint(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 LogPrint(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 (workQueue->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 LogPrint(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 LogPrint(BCLog::HTTP, "Entering http event loop\n");
384 event_base_dispatch(base);
385 // Event loop will be interrupted by InterruptHTTPServer()
386 LogPrint(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 LogPrint(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#ifndef EVENT_LOG_WARN
452// EVENT_LOG_WARN was added in 2.0.19; but before then _EVENT_LOG_WARN existed.
453#define EVENT_LOG_WARN _EVENT_LOG_WARN
454#endif
455 BCLog::Level level;
456 switch (severity) {
457 case EVENT_LOG_DEBUG:
458 level = BCLog::Level::Debug;
459 break;
460 case EVENT_LOG_MSG:
461 level = BCLog::Level::Info;
462 break;
463 case EVENT_LOG_WARN:
464 level = BCLog::Level::Warning;
465 break;
466 default: // EVENT_LOG_ERR and others are mapped to error
467 level = BCLog::Level::Error;
468 break;
469 }
470 LogPrintLevel(BCLog::LIBEVENT, level, "%s\n", msg);
471}
472
473bool InitHTTPServer(Config &config) {
474 if (!InitHTTPAllowList()) {
475 return false;
476 }
477
478 // Redirect libevent's logging to our own log
479 event_set_log_callback(&libevent_log_cb);
480 // Update libevent's log handling.
482
483#ifdef WIN32
484 evthread_use_windows_threads();
485#else
486 evthread_use_pthreads();
487#endif
488
489 raii_event_base base_ctr = obtain_event_base();
490
491 /* Create a new evhttp object to handle requests. */
492 raii_evhttp http_ctr = obtain_evhttp(base_ctr.get());
493 struct evhttp *http = http_ctr.get();
494 if (!http) {
495 LogPrintf("couldn't create evhttp. Exiting.\n");
496 return false;
497 }
498
499 evhttp_set_timeout(http, gArgs.GetIntArg("-rpcservertimeout",
501 evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
502 evhttp_set_max_body_size(http, MIN_SUPPORTED_BODY_SIZE +
503 2 * config.GetMaxBlockSize());
504 evhttp_set_gencb(http, http_request_cb, &config);
505
506 // Only POST and OPTIONS are supported, but we return HTTP 405 for the
507 // others
508 evhttp_set_allowed_methods(
509 http, EVHTTP_REQ_GET | EVHTTP_REQ_POST | EVHTTP_REQ_HEAD |
510 EVHTTP_REQ_PUT | EVHTTP_REQ_DELETE | EVHTTP_REQ_OPTIONS);
511
512 if (!HTTPBindAddresses(http)) {
513 LogPrintf("Unable to bind any endpoint for RPC server\n");
514 return false;
515 }
516
517 LogPrint(BCLog::HTTP, "Initialized HTTP server\n");
518 int workQueueDepth = std::max(
519 (long)gArgs.GetIntArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
520 LogDebug(BCLog::HTTP, "creating work queue of depth %d\n", workQueueDepth);
521
522 workQueue = new WorkQueue<HTTPClosure>(workQueueDepth);
523 // transfer ownership to eventBase/HTTP via .release()
524 eventBase = base_ctr.release();
525 eventHTTP = http_ctr.release();
526 return true;
527}
528
529void UpdateHTTPServerLogging(bool enable) {
530 if (enable) {
531 event_enable_debug_logging(EVENT_DBG_ALL);
532 } else {
533 event_enable_debug_logging(EVENT_DBG_NONE);
534 }
535}
536
537static std::thread g_thread_http;
538static std::vector<std::thread> g_thread_http_workers;
539
541 int rpcThreads = std::max(
542 (long)gArgs.GetIntArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L);
543 LogInfo("Starting HTTP server with %d worker threads\n", rpcThreads);
544 g_thread_http = std::thread(ThreadHTTP, eventBase);
545
546 for (int i = 0; i < rpcThreads; i++) {
548 }
549}
550
552 LogPrint(BCLog::HTTP, "Interrupting HTTP server\n");
553 if (eventHTTP) {
554 // Reject requests on current connections
555 evhttp_set_gencb(eventHTTP, http_reject_request_cb, nullptr);
556 }
557 if (workQueue) {
558 workQueue->Interrupt();
559 }
560}
561
563 LogPrint(BCLog::HTTP, "Stopping HTTP server\n");
564 if (workQueue) {
565 LogPrint(BCLog::HTTP, "Waiting for HTTP worker threads to exit\n");
566 for (auto &thread : g_thread_http_workers) {
567 thread.join();
568 }
569 g_thread_http_workers.clear();
570 delete workQueue;
571 workQueue = nullptr;
572 }
573 // Unlisten sockets, these are what make the event loop running, which means
574 // that after this and all connections are closed the event loop will quit.
575 for (evhttp_bound_socket *socket : boundSockets) {
576 evhttp_del_accept_socket(eventHTTP, socket);
577 }
578 boundSockets.clear();
579 {
580 if (const auto n_connections{g_requests.CountActiveConnections()};
581 n_connections != 0) {
583 "Waiting for %d connections to stop HTTP server\n",
584 n_connections);
585 }
587 }
588 if (eventHTTP) {
589 // Schedule a callback to call evhttp_free in the event base thread, so
590 // that evhttp_free does not need to be called again after the handling
591 // of unfinished request connections that follows.
592 event_base_once(
593 eventBase, -1, EV_TIMEOUT,
594 [](evutil_socket_t, short, void *) {
595 evhttp_free(eventHTTP);
596 eventHTTP = nullptr;
597 },
598 nullptr, nullptr);
599 }
600 if (eventBase) {
601 LogPrint(BCLog::HTTP, "Waiting for HTTP event thread to exit\n");
602 if (g_thread_http.joinable()) {
603 g_thread_http.join();
604 }
605 event_base_free(eventBase);
606 eventBase = nullptr;
607 }
608 LogPrint(BCLog::HTTP, "Stopped HTTP server\n");
609}
610
611struct event_base *EventBase() {
612 return eventBase;
613}
614
615static void httpevent_callback_fn(evutil_socket_t, short, void *data) {
616 // Static handler: simply call inner handler
617 HTTPEvent *self = static_cast<HTTPEvent *>(data);
618 self->handler();
619 if (self->deleteWhenTriggered) {
620 delete self;
621 }
622}
623
624HTTPEvent::HTTPEvent(struct event_base *base, bool _deleteWhenTriggered,
625 const std::function<void()> &_handler)
626 : deleteWhenTriggered(_deleteWhenTriggered), handler(_handler) {
627 ev = event_new(base, -1, 0, httpevent_callback_fn, this);
628 assert(ev);
629}
631 event_free(ev);
632}
633void HTTPEvent::trigger(struct timeval *tv) {
634 if (tv == nullptr) {
635 // Immediately trigger event in main thread.
636 event_active(ev, 0, 0);
637 } else {
638 // Trigger after timeval passed.
639 evtimer_add(ev, tv);
640 }
641}
642HTTPRequest::HTTPRequest(struct evhttp_request *_req, bool _replySent)
643 : req(_req), replySent(_replySent) {}
645 if (!replySent) {
646 // Keep track of whether reply was sent to avoid request leaks
647 LogPrintf("%s: Unhandled request\n", __func__);
648 WriteReply(HTTP_INTERNAL_SERVER_ERROR, "Unhandled request");
649 }
650 // evhttpd cleans up the request, as long as a reply was sent.
651}
652
653std::pair<bool, std::string>
654HTTPRequest::GetHeader(const std::string &hdr) const {
655 const struct evkeyvalq *headers = evhttp_request_get_input_headers(req);
656 assert(headers);
657 const char *val = evhttp_find_header(headers, hdr.c_str());
658 if (val) {
659 return std::make_pair(true, val);
660 } else {
661 return std::make_pair(false, "");
662 }
663}
664
666 struct evbuffer *buf = evhttp_request_get_input_buffer(req);
667 if (!buf) {
668 return "";
669 }
670 size_t size = evbuffer_get_length(buf);
678 const char *data = (const char *)evbuffer_pullup(buf, size);
679
680 // returns nullptr in case of empty buffer.
681 if (!data) {
682 return "";
683 }
684 std::string rv(data, size);
685 evbuffer_drain(buf, size);
686 return rv;
687}
688
689void HTTPRequest::WriteHeader(const std::string &hdr,
690 const std::string &value) {
691 struct evkeyvalq *headers = evhttp_request_get_output_headers(req);
692 assert(headers);
693 evhttp_add_header(headers, hdr.c_str(), value.c_str());
694}
695
701void HTTPRequest::WriteReply(int nStatus, const std::string &strReply) {
702 assert(!replySent && req);
703 if (ShutdownRequested()) {
704 WriteHeader("Connection", "close");
705 }
706 // Send event to main http thread to send reply message
707 struct evbuffer *evb = evhttp_request_get_output_buffer(req);
708 assert(evb);
709 evbuffer_add(evb, strReply.data(), strReply.size());
710 auto req_copy = req;
711 HTTPEvent *ev = new HTTPEvent(eventBase, true, [req_copy, nStatus] {
712 evhttp_send_reply(req_copy, nStatus, nullptr, nullptr);
713 // Re-enable reading from the socket. This is the second part of the
714 // libevent workaround above.
715 if (event_get_version_number() >= 0x02010600 &&
716 event_get_version_number() < 0x02020001) {
717 evhttp_connection *conn = evhttp_request_get_connection(req_copy);
718 if (conn) {
719 bufferevent *bev = evhttp_connection_get_bufferevent(conn);
720 if (bev) {
721 bufferevent_enable(bev, EV_READ | EV_WRITE);
722 }
723 }
724 }
725 });
726 ev->trigger(nullptr);
727 replySent = true;
728 // transferred back to main thread.
729 req = nullptr;
730}
731
733 evhttp_connection *con = evhttp_request_get_connection(req);
734 CService peer;
735 if (con) {
736 // evhttp retains ownership over returned address string
737 const char *address = "";
738 uint16_t port = 0;
739 evhttp_connection_get_peer(con, (char **)&address, &port);
740 peer = LookupNumeric(address, port);
741 }
742 return peer;
743}
744
745std::string HTTPRequest::GetURI() const {
746 return evhttp_request_get_uri(req);
747}
748
750 switch (evhttp_request_get_command(req)) {
751 case EVHTTP_REQ_GET:
752 return GET;
753 case EVHTTP_REQ_POST:
754 return POST;
755 case EVHTTP_REQ_HEAD:
756 return HEAD;
757 case EVHTTP_REQ_PUT:
758 return PUT;
759 case EVHTTP_REQ_OPTIONS:
760 return OPTIONS;
761 default:
762 return UNKNOWN;
763 }
764}
765
766void RegisterHTTPHandler(const std::string &prefix, bool exactMatch,
768 LogPrint(BCLog::HTTP, "Registering HTTP handler for %s (exactmatch %d)\n",
769 prefix, exactMatch);
770 pathHandlers.push_back(HTTPPathHandler(prefix, exactMatch, handler));
771}
772
773void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch) {
774 std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
775 std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
776 for (; i != iend; ++i) {
777 if (i->prefix == prefix && i->exactMatch == exactMatch) {
778 break;
779 }
780 }
781 if (i != iend) {
783 "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix,
784 exactMatch);
785 pathHandlers.erase(i);
786 }
787}
ArgsManager gArgs
Definition: args.cpp:39
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
#define Assert(val)
Identity function.
Definition: check.h:84
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:474
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:572
bool IsValid() const
Definition: config.h:19
virtual uint64_t GetMaxBlockSize() const =0
Event handler closure.
Definition: httpserver.h:126
Event class.
Definition: httpserver.h:136
struct event * ev
Definition: httpserver.h:158
bool deleteWhenTriggered
Definition: httpserver.h:154
std::function< void()> handler
Definition: httpserver.h:155
HTTPEvent(struct event_base *base, bool deleteWhenTriggered, const std::function< void()> &handler)
Create a new event.
Definition: httpserver.cpp:624
void trigger(struct timeval *tv)
Trigger the event.
Definition: httpserver.cpp:633
bool replySent
Definition: httpserver.h:74
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:654
std::string GetURI() const
Get requested URI.
Definition: httpserver.cpp:745
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
Definition: httpserver.cpp:701
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
Definition: httpserver.cpp:689
struct evhttp_request * req
Definition: httpserver.h:73
RequestMethod GetRequestMethod() const
Get request method.
Definition: httpserver.cpp:749
std::string ReadBody()
Read request body.
Definition: httpserver.cpp:665
CService GetPeer() const
Get CService (address:ip) for the origin of the http request.
Definition: httpserver.cpp:732
HTTPRequest(struct evhttp_request *req, bool replySent=false)
Definition: httpserver.cpp:642
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:53
void operator()() override
Definition: httpserver.cpp:59
std::unique_ptr< HTTPRequest > req
Definition: httpserver.cpp:61
std::string path
Definition: httpserver.cpp:64
Config * config
Definition: httpserver.cpp:66
HTTPWorkItem(Config &_config, std::unique_ptr< HTTPRequest > _req, const std::string &_path, const HTTPRequestHandler &_func)
Definition: httpserver.cpp:55
HTTPRequestHandler func
Definition: httpserver.cpp:65
Simple work queue for distributing work over multiple threads.
Definition: httpserver.cpp:73
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)
bool running
Definition: httpserver.cpp:79
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!cs)
Interrupt and exit loops.
Definition: httpserver.cpp:120
Mutex cs
Mutex protects entire object.
Definition: httpserver.cpp:76
std::deque< std::unique_ptr< WorkItem > > queue
Definition: httpserver.cpp:78
size_t maxDepth
Definition: httpserver.cpp:80
WorkQueue(size_t _maxDepth)
Definition: httpserver.cpp:83
std::condition_variable cond
Definition: httpserver.cpp:77
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:551
static void http_request_cb(struct evhttp_request *req, void *arg)
HTTP request callback.
Definition: httpserver.cpp:279
static WorkQueue< HTTPClosure > * workQueue
Work queue for handling longer requests off the event loop thread.
Definition: httpserver.cpp:145
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:773
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
Definition: httpserver.cpp:766
void StartHTTPServer()
Start HTTP server.
Definition: httpserver.cpp:540
static struct event_base * eventBase
HTTP module state.
Definition: httpserver.cpp:139
void UpdateHTTPServerLogging(bool enable)
Change logging level for libevent.
Definition: httpserver.cpp:529
static std::thread g_thread_http
Definition: httpserver.cpp:537
struct event_base * EventBase()
Return evhttp event base.
Definition: httpserver.cpp:611
static void httpevent_callback_fn(evutil_socket_t, short, void *data)
Definition: httpserver.cpp:615
std::string RequestMethodString(HTTPRequest::RequestMethod m)
HTTP request method as string - use for logging only.
Definition: httpserver.cpp:261
#define EVENT_LOG_WARN
static const size_t MIN_SUPPORTED_BODY_SIZE
Maximum HTTP post body size.
Definition: httpserver.cpp:50
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:44
void StopHTTPServer()
Stop HTTP server.
Definition: httpserver.cpp:562
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:538
bool InitHTTPServer(Config &config)
Initialize HTTP server.
Definition: httpserver.cpp:473
static const int DEFAULT_HTTP_SERVER_TIMEOUT
Definition: httpserver.h:14
static const int DEFAULT_HTTP_WORKQUEUE
Definition: httpserver.h:13
static const int DEFAULT_HTTP_THREADS
Definition: httpserver.h:12
std::function< bool(Config &config, HTTPRequest *req, const std::string &)> HTTPRequestHandler
Handler for requests to a certain HTTP path.
Definition: httpserver.h:48
BCLog::Logger & LogInstance()
Definition: logging.cpp:25
#define LogPrintLevel(category, level,...)
Definition: logging.h:437
#define LogPrint(category,...)
Definition: logging.h:452
#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:188
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:783
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:247
const char * prefix
Definition: rest.cpp:812
bool(* handler)(Config &config, const std::any &context, HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:813
@ 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:31
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:317
#define LOCK(cs)
Definition: sync.h:306
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:357
#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:1202
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:36
CClientUIInterface uiInterface
void SplitHostPort(std::string_view in, uint16_t &portOut, std::string &hostOut)
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.
assert(!tx.IsCoinBase())