Bitcoin ABC 0.30.7
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.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;
80 size_t maxDepth;
81
82public:
83 explicit WorkQueue(size_t _maxDepth) : running(true), maxDepth(_maxDepth) {}
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 CNetAddr localv4;
232 CNetAddr localv6;
233 LookupHost("127.0.0.1", localv4, false);
234 LookupHost("::1", localv6, false);
235 // always allow IPv4 local subnet.
236 rpc_allow_subnets.push_back(CSubNet(localv4, 8));
237 // always allow IPv6 localhost.
238 rpc_allow_subnets.push_back(CSubNet(localv6));
239 for (const std::string &strAllow : gArgs.GetArgs("-rpcallowip")) {
240 CSubNet subnet;
241 LookupSubNet(strAllow, subnet);
242 if (!subnet.IsValid()) {
243 uiInterface.ThreadSafeMessageBox(
244 strprintf(
245 Untranslated("Invalid -rpcallowip subnet specification: "
246 "%s. Valid are a single IP (e.g. 1.2.3.4), a "
247 "network/netmask (e.g. 1.2.3.4/255.255.255.0) "
248 "or a network/CIDR (e.g. 1.2.3.4/24)."),
249 strAllow),
251 return false;
252 }
253 rpc_allow_subnets.push_back(subnet);
254 }
255 std::string strAllowed;
256 for (const CSubNet &subnet : rpc_allow_subnets) {
257 strAllowed += subnet.ToString() + " ";
258 }
259 LogPrint(BCLog::HTTP, "Allowing HTTP connections from: %s\n", strAllowed);
260 return true;
261}
262
265 switch (m) {
266 case HTTPRequest::GET:
267 return "GET";
269 return "POST";
271 return "HEAD";
272 case HTTPRequest::PUT:
273 return "PUT";
275 return "OPTIONS";
276 default:
277 return "unknown";
278 }
279}
280
282static void http_request_cb(struct evhttp_request *req, void *arg) {
283 Config &config = *reinterpret_cast<Config *>(arg);
284
285 evhttp_connection *conn{evhttp_request_get_connection(req)};
286 // Track active requests
287 {
289 evhttp_request_set_on_complete_cb(
290 req,
291 [](struct evhttp_request *req, void *) {
293 },
294 nullptr);
295 evhttp_connection_set_closecb(
296 conn,
297 [](evhttp_connection *conn, void *arg) {
299 },
300 nullptr);
301 }
302
303 // Disable reading to work around a libevent bug, fixed in 2.2.0.
304 if (event_get_version_number() >= 0x02010600 &&
305 event_get_version_number() < 0x02020001) {
306 if (conn) {
307 bufferevent *bev = evhttp_connection_get_bufferevent(conn);
308 if (bev) {
309 bufferevent_disable(bev, EV_READ);
310 }
311 }
312 }
313 auto hreq = std::make_unique<HTTPRequest>(req);
314
315 // Early address-based allow check
316 if (!ClientAllowed(hreq->GetPeer())) {
318 "HTTP request from %s rejected: Client network is not allowed "
319 "RPC access\n",
320 hreq->GetPeer().ToString());
321 hreq->WriteReply(HTTP_FORBIDDEN);
322 return;
323 }
324
325 // Early reject unknown HTTP methods
326 if (hreq->GetRequestMethod() == HTTPRequest::UNKNOWN) {
328 "HTTP request from %s rejected: Unknown HTTP request method\n",
329 hreq->GetPeer().ToString());
330 hreq->WriteReply(HTTP_BAD_METHOD);
331 return;
332 }
333
334 LogPrint(BCLog::HTTP, "Received a %s request for %s from %s\n",
335 RequestMethodString(hreq->GetRequestMethod()),
336 SanitizeString(hreq->GetURI(), SAFE_CHARS_URI).substr(0, 100),
337 hreq->GetPeer().ToString());
338
339 // Find registered handler for prefix
340 std::string strURI = hreq->GetURI();
341 std::string path;
342 std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin();
343 std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end();
344 for (; i != iend; ++i) {
345 bool match = false;
346 if (i->exactMatch) {
347 match = (strURI == i->prefix);
348 } else {
349 match = (strURI.substr(0, i->prefix.size()) == i->prefix);
350 }
351 if (match) {
352 path = strURI.substr(i->prefix.size());
353 break;
354 }
355 }
356
357 // Dispatch to worker thread.
358 if (i != iend) {
359 std::unique_ptr<HTTPWorkItem> item(
360 new HTTPWorkItem(config, std::move(hreq), path, i->handler));
362 if (workQueue->Enqueue(item.get())) {
363 /* if true, queue took ownership */
364 item.release();
365 } else {
366 LogPrintf("WARNING: request rejected because http work queue depth "
367 "exceeded, it can be increased with the -rpcworkqueue= "
368 "setting\n");
369 item->req->WriteReply(HTTP_SERVICE_UNAVAILABLE,
370 "Work queue depth exceeded");
371 }
372 } else {
373 hreq->WriteReply(HTTP_NOT_FOUND);
374 }
375}
376
378static void http_reject_request_cb(struct evhttp_request *req, void *) {
379 LogPrint(BCLog::HTTP, "Rejecting request while shutting down\n");
380 evhttp_send_error(req, HTTP_SERVUNAVAIL, nullptr);
381}
382
384static bool ThreadHTTP(struct event_base *base) {
385 util::ThreadRename("http");
386 LogPrint(BCLog::HTTP, "Entering http event loop\n");
387 event_base_dispatch(base);
388 // Event loop will be interrupted by InterruptHTTPServer()
389 LogPrint(BCLog::HTTP, "Exited http event loop\n");
390 return event_base_got_break(base) == 0;
391}
392
394static bool HTTPBindAddresses(struct evhttp *http) {
395 uint16_t http_port{static_cast<uint16_t>(
396 gArgs.GetIntArg("-rpcport", BaseParams().RPCPort()))};
397 std::vector<std::pair<std::string, uint16_t>> endpoints;
398
399 // Determine what addresses to bind to
400 if (!(gArgs.IsArgSet("-rpcallowip") && gArgs.IsArgSet("-rpcbind"))) {
401 // Default to loopback if not allowing external IPs.
402 endpoints.push_back(std::make_pair("::1", http_port));
403 endpoints.push_back(std::make_pair("127.0.0.1", http_port));
404 if (gArgs.IsArgSet("-rpcallowip")) {
405 LogPrintf("WARNING: option -rpcallowip was specified without "
406 "-rpcbind; this doesn't usually make sense\n");
407 }
408 if (gArgs.IsArgSet("-rpcbind")) {
409 LogPrintf("WARNING: option -rpcbind was ignored because "
410 "-rpcallowip was not specified, refusing to allow "
411 "everyone to connect\n");
412 }
413 } else if (gArgs.IsArgSet("-rpcbind")) {
414 // Specific bind address.
415 for (const std::string &strRPCBind : gArgs.GetArgs("-rpcbind")) {
416 uint16_t port{http_port};
417 std::string host;
418 SplitHostPort(strRPCBind, port, host);
419 endpoints.push_back(std::make_pair(host, port));
420 }
421 }
422
423 // Bind addresses
424 for (std::vector<std::pair<std::string, uint16_t>>::iterator i =
425 endpoints.begin();
426 i != endpoints.end(); ++i) {
427 LogPrint(BCLog::HTTP, "Binding RPC on address %s port %i\n", i->first,
428 i->second);
429 evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(
430 http, i->first.empty() ? nullptr : i->first.c_str(), i->second);
431 if (bind_handle) {
432 CNetAddr addr;
433 if (i->first.empty() ||
434 (LookupHost(i->first, addr, false) && addr.IsBindAny())) {
435 LogPrintf("WARNING: the RPC server is not safe to expose to "
436 "untrusted networks such as the public internet\n");
437 }
438 boundSockets.push_back(bind_handle);
439 } else {
440 LogPrintf("Binding RPC on address %s port %i failed.\n", i->first,
441 i->second);
442 }
443 }
444 return !boundSockets.empty();
445}
446
448static void HTTPWorkQueueRun(WorkQueue<HTTPClosure> *queue, int worker_num) {
449 util::ThreadRename(strprintf("httpworker.%i", worker_num));
450 queue->Run();
451}
452
454static void libevent_log_cb(int severity, const char *msg) {
455#ifndef EVENT_LOG_WARN
456// EVENT_LOG_WARN was added in 2.0.19; but before then _EVENT_LOG_WARN existed.
457#define EVENT_LOG_WARN _EVENT_LOG_WARN
458#endif
459 BCLog::Level level;
460 switch (severity) {
461 case EVENT_LOG_DEBUG:
462 level = BCLog::Level::Debug;
463 break;
464 case EVENT_LOG_MSG:
465 level = BCLog::Level::Info;
466 break;
467 case EVENT_LOG_WARN:
468 level = BCLog::Level::Warning;
469 break;
470 default: // EVENT_LOG_ERR and others are mapped to error
471 level = BCLog::Level::Error;
472 break;
473 }
474 LogPrintLevel(BCLog::LIBEVENT, level, "%s\n", msg);
475}
476
477bool InitHTTPServer(Config &config) {
478 if (!InitHTTPAllowList()) {
479 return false;
480 }
481
482 // Redirect libevent's logging to our own log
483 event_set_log_callback(&libevent_log_cb);
484 // Update libevent's log handling.
486
487#ifdef WIN32
488 evthread_use_windows_threads();
489#else
490 evthread_use_pthreads();
491#endif
492
493 raii_event_base base_ctr = obtain_event_base();
494
495 /* Create a new evhttp object to handle requests. */
496 raii_evhttp http_ctr = obtain_evhttp(base_ctr.get());
497 struct evhttp *http = http_ctr.get();
498 if (!http) {
499 LogPrintf("couldn't create evhttp. Exiting.\n");
500 return false;
501 }
502
503 evhttp_set_timeout(http, gArgs.GetIntArg("-rpcservertimeout",
505 evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
506 evhttp_set_max_body_size(http, MIN_SUPPORTED_BODY_SIZE +
507 2 * config.GetMaxBlockSize());
508 evhttp_set_gencb(http, http_request_cb, &config);
509
510 // Only POST and OPTIONS are supported, but we return HTTP 405 for the
511 // others
512 evhttp_set_allowed_methods(
513 http, EVHTTP_REQ_GET | EVHTTP_REQ_POST | EVHTTP_REQ_HEAD |
514 EVHTTP_REQ_PUT | EVHTTP_REQ_DELETE | EVHTTP_REQ_OPTIONS);
515
516 if (!HTTPBindAddresses(http)) {
517 LogPrintf("Unable to bind any endpoint for RPC server\n");
518 return false;
519 }
520
521 LogPrint(BCLog::HTTP, "Initialized HTTP server\n");
522 int workQueueDepth = std::max(
523 (long)gArgs.GetIntArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
524 LogPrintfCategory(BCLog::HTTP, "creating work queue of depth %d\n",
525 workQueueDepth);
526
527 workQueue = new WorkQueue<HTTPClosure>(workQueueDepth);
528 // transfer ownership to eventBase/HTTP via .release()
529 eventBase = base_ctr.release();
530 eventHTTP = http_ctr.release();
531 return true;
532}
533
534void UpdateHTTPServerLogging(bool enable) {
535 if (enable) {
536 event_enable_debug_logging(EVENT_DBG_ALL);
537 } else {
538 event_enable_debug_logging(EVENT_DBG_NONE);
539 }
540}
541
542static std::thread g_thread_http;
543static std::vector<std::thread> g_thread_http_workers;
544
546 LogPrint(BCLog::HTTP, "Starting HTTP server\n");
547 int rpcThreads = std::max(
548 (long)gArgs.GetIntArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L);
549 LogPrintfCategory(BCLog::HTTP, "starting %d worker threads\n", rpcThreads);
550 g_thread_http = std::thread(ThreadHTTP, eventBase);
551
552 for (int i = 0; i < rpcThreads; i++) {
554 }
555}
556
558 LogPrint(BCLog::HTTP, "Interrupting HTTP server\n");
559 if (eventHTTP) {
560 // Reject requests on current connections
561 evhttp_set_gencb(eventHTTP, http_reject_request_cb, nullptr);
562 }
563 if (workQueue) {
564 workQueue->Interrupt();
565 }
566}
567
569 LogPrint(BCLog::HTTP, "Stopping HTTP server\n");
570 if (workQueue) {
571 LogPrint(BCLog::HTTP, "Waiting for HTTP worker threads to exit\n");
572 for (auto &thread : g_thread_http_workers) {
573 thread.join();
574 }
575 g_thread_http_workers.clear();
576 delete workQueue;
577 workQueue = nullptr;
578 }
579 // Unlisten sockets, these are what make the event loop running, which means
580 // that after this and all connections are closed the event loop will quit.
581 for (evhttp_bound_socket *socket : boundSockets) {
582 evhttp_del_accept_socket(eventHTTP, socket);
583 }
584 boundSockets.clear();
585 {
586 if (const auto n_connections{g_requests.CountActiveConnections()};
587 n_connections != 0) {
589 "Waiting for %d connections to stop HTTP server\n",
590 n_connections);
591 }
593 }
594 if (eventHTTP) {
595 // Schedule a callback to call evhttp_free in the event base thread, so
596 // that evhttp_free does not need to be called again after the handling
597 // of unfinished request connections that follows.
598 event_base_once(
599 eventBase, -1, EV_TIMEOUT,
600 [](evutil_socket_t, short, void *) {
601 evhttp_free(eventHTTP);
602 eventHTTP = nullptr;
603 },
604 nullptr, nullptr);
605 }
606 if (eventBase) {
607 LogPrint(BCLog::HTTP, "Waiting for HTTP event thread to exit\n");
608 if (g_thread_http.joinable()) {
609 g_thread_http.join();
610 }
611 event_base_free(eventBase);
612 eventBase = nullptr;
613 }
614 LogPrint(BCLog::HTTP, "Stopped HTTP server\n");
615}
616
617struct event_base *EventBase() {
618 return eventBase;
619}
620
621static void httpevent_callback_fn(evutil_socket_t, short, void *data) {
622 // Static handler: simply call inner handler
623 HTTPEvent *self = static_cast<HTTPEvent *>(data);
624 self->handler();
625 if (self->deleteWhenTriggered) {
626 delete self;
627 }
628}
629
630HTTPEvent::HTTPEvent(struct event_base *base, bool _deleteWhenTriggered,
631 const std::function<void()> &_handler)
632 : deleteWhenTriggered(_deleteWhenTriggered), handler(_handler) {
633 ev = event_new(base, -1, 0, httpevent_callback_fn, this);
634 assert(ev);
635}
637 event_free(ev);
638}
639void HTTPEvent::trigger(struct timeval *tv) {
640 if (tv == nullptr) {
641 // Immediately trigger event in main thread.
642 event_active(ev, 0, 0);
643 } else {
644 // Trigger after timeval passed.
645 evtimer_add(ev, tv);
646 }
647}
648HTTPRequest::HTTPRequest(struct evhttp_request *_req, bool _replySent)
649 : req(_req), replySent(_replySent) {}
651 if (!replySent) {
652 // Keep track of whether reply was sent to avoid request leaks
653 LogPrintf("%s: Unhandled request\n", __func__);
654 WriteReply(HTTP_INTERNAL_SERVER_ERROR, "Unhandled request");
655 }
656 // evhttpd cleans up the request, as long as a reply was sent.
657}
658
659std::pair<bool, std::string>
660HTTPRequest::GetHeader(const std::string &hdr) const {
661 const struct evkeyvalq *headers = evhttp_request_get_input_headers(req);
662 assert(headers);
663 const char *val = evhttp_find_header(headers, hdr.c_str());
664 if (val) {
665 return std::make_pair(true, val);
666 } else {
667 return std::make_pair(false, "");
668 }
669}
670
672 struct evbuffer *buf = evhttp_request_get_input_buffer(req);
673 if (!buf) {
674 return "";
675 }
676 size_t size = evbuffer_get_length(buf);
684 const char *data = (const char *)evbuffer_pullup(buf, size);
685
686 // returns nullptr in case of empty buffer.
687 if (!data) {
688 return "";
689 }
690 std::string rv(data, size);
691 evbuffer_drain(buf, size);
692 return rv;
693}
694
695void HTTPRequest::WriteHeader(const std::string &hdr,
696 const std::string &value) {
697 struct evkeyvalq *headers = evhttp_request_get_output_headers(req);
698 assert(headers);
699 evhttp_add_header(headers, hdr.c_str(), value.c_str());
700}
701
707void HTTPRequest::WriteReply(int nStatus, const std::string &strReply) {
708 assert(!replySent && req);
709 if (ShutdownRequested()) {
710 WriteHeader("Connection", "close");
711 }
712 // Send event to main http thread to send reply message
713 struct evbuffer *evb = evhttp_request_get_output_buffer(req);
714 assert(evb);
715 evbuffer_add(evb, strReply.data(), strReply.size());
716 auto req_copy = req;
717 HTTPEvent *ev = new HTTPEvent(eventBase, true, [req_copy, nStatus] {
718 evhttp_send_reply(req_copy, nStatus, nullptr, nullptr);
719 // Re-enable reading from the socket. This is the second part of the
720 // libevent workaround above.
721 if (event_get_version_number() >= 0x02010600 &&
722 event_get_version_number() < 0x02020001) {
723 evhttp_connection *conn = evhttp_request_get_connection(req_copy);
724 if (conn) {
725 bufferevent *bev = evhttp_connection_get_bufferevent(conn);
726 if (bev) {
727 bufferevent_enable(bev, EV_READ | EV_WRITE);
728 }
729 }
730 }
731 });
732 ev->trigger(nullptr);
733 replySent = true;
734 // transferred back to main thread.
735 req = nullptr;
736}
737
739 evhttp_connection *con = evhttp_request_get_connection(req);
740 CService peer;
741 if (con) {
742 // evhttp retains ownership over returned address string
743 const char *address = "";
744 uint16_t port = 0;
745 evhttp_connection_get_peer(con, (char **)&address, &port);
746 peer = LookupNumeric(address, port);
747 }
748 return peer;
749}
750
751std::string HTTPRequest::GetURI() const {
752 return evhttp_request_get_uri(req);
753}
754
756 switch (evhttp_request_get_command(req)) {
757 case EVHTTP_REQ_GET:
758 return GET;
759 case EVHTTP_REQ_POST:
760 return POST;
761 case EVHTTP_REQ_HEAD:
762 return HEAD;
763 case EVHTTP_REQ_PUT:
764 return PUT;
765 case EVHTTP_REQ_OPTIONS:
766 return OPTIONS;
767 default:
768 return UNKNOWN;
769 }
770}
771
772void RegisterHTTPHandler(const std::string &prefix, bool exactMatch,
774 LogPrint(BCLog::HTTP, "Registering HTTP handler for %s (exactmatch %d)\n",
775 prefix, exactMatch);
776 pathHandlers.push_back(HTTPPathHandler(prefix, exactMatch, handler));
777}
778
779void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch) {
780 std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
781 std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
782 for (; i != iend; ++i) {
783 if (i->prefix == prefix && i->exactMatch == exactMatch) {
784 break;
785 }
786 }
787 if (i != iend) {
789 "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix,
790 exactMatch);
791 pathHandlers.erase(i);
792 }
793}
ArgsManager gArgs
Definition: args.cpp:38
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:371
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: args.cpp:381
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: args.cpp:526
Network address.
Definition: netaddress.h:121
bool IsBindAny() const
Definition: netaddress.cpp:332
bool IsValid() const
Definition: netaddress.cpp:477
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:545
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:630
void trigger(struct timeval *tv)
Trigger the event.
Definition: httpserver.cpp:639
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:660
std::string GetURI() const
Get requested URI.
Definition: httpserver.cpp:751
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
Definition: httpserver.cpp:707
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
Definition: httpserver.cpp:695
struct evhttp_request * req
Definition: httpserver.h:73
RequestMethod GetRequestMethod() const
Get request method.
Definition: httpserver.cpp:755
std::string ReadBody()
Read request body.
Definition: httpserver.cpp:671
CService GetPeer() const
Get CService (address:ip) for the origin of the http request.
Definition: httpserver.cpp:738
HTTPRequest(struct evhttp_request *req, bool replySent=false)
Definition: httpserver.cpp:648
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
bool running
Definition: httpserver.cpp:79
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!cs)
Interrupt and exit loops.
Definition: httpserver.cpp:120
~WorkQueue()
Precondition: worker threads have all stopped (they have all been joined)
Definition: httpserver.cpp:87
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:557
static void http_request_cb(struct evhttp_request *req, void *arg)
HTTP request callback.
Definition: httpserver.cpp:282
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:394
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:779
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
Definition: httpserver.cpp:772
void StartHTTPServer()
Start HTTP server.
Definition: httpserver.cpp:545
static struct event_base * eventBase
HTTP module state.
Definition: httpserver.cpp:139
void UpdateHTTPServerLogging(bool enable)
Change logging level for libevent.
Definition: httpserver.cpp:534
static std::thread g_thread_http
Definition: httpserver.cpp:542
struct event_base * EventBase()
Return evhttp event base.
Definition: httpserver.cpp:617
static void httpevent_callback_fn(evutil_socket_t, short, void *data)
Definition: httpserver.cpp:621
std::string RequestMethodString(HTTPRequest::RequestMethod m)
HTTP request method as string - use for logging only.
Definition: httpserver.cpp:264
#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:448
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:384
static void libevent_log_cb(int severity, const char *msg)
libevent event log callback
Definition: httpserver.cpp:454
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:378
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:568
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:543
bool InitHTTPServer(Config &config)
Initialize HTTP server.
Definition: httpserver.cpp:477
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:21
#define LogPrintLevel(category, level,...)
Definition: logging.h:247
#define LogPrint(category,...)
Definition: logging.h:238
#define LogPrintfCategory(category,...)
Definition: logging.h:231
#define LogPrintf(...)
Definition: logging.h:227
Level
Definition: logging.h:74
@ HTTP
Definition: logging.h:43
@ LIBEVENT
Definition: logging.h:57
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
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:781
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:261
bool LookupHost(const std::string &name, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup, DNSLookupFn dns_lookup_function)
Resolve a host string to its corresponding network addresses.
Definition: netbase.cpp:191
const char * prefix
Definition: rest.cpp:817
bool(* handler)(Config &config, const std::any &context, HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:818
@ 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:85
@ SAFE_CHARS_URI
Chars allowed in URIs (RFC 3986)
Definition: strencodings.h:30
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())