Bitcoin ABC 0.26.3
P2P Digital Currency
Loading...
Searching...
No Matches
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
54public:
55 HTTPWorkItem(Config &_config, std::unique_ptr<HTTPRequest> _req,
56 const std::string &_path, const HTTPRequestHandler &_func)
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:
88
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
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>
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:
181 const evhttp_connection *conn{
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 }
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();
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.
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
286 // Track active requests
287 {
290 req,
291 [](struct evhttp_request *req, void *) {
293 },
294 nullptr);
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) {
308 if (bev) {
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");
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);
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
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
460 switch (severity) {
461 case EVENT_LOG_DEBUG:
463 break;
464 case EVENT_LOG_MSG:
466 break;
467 case EVENT_LOG_WARN:
469 break;
470 default: // EVENT_LOG_ERR and others are mapped to 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
484 // Update libevent's log handling.
486
487#ifdef WIN32
489#else
491#endif
492
494
495 /* Create a new evhttp object to handle requests. */
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",
507 2 * config.GetMaxBlockSize());
509
510 // Only POST and OPTIONS are supported, but we return HTTP 405 for the
511 // others
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",
526
528 // transfer ownership to eventBase/HTTP via .release()
529 eventBase = base_ctr.release();
530 eventHTTP = http_ctr.release();
531 return true;
532}
533
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
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.
583 }
584 boundSockets.clear();
585 {
587 n_connections != 0) {
589 "Waiting for %d connections to stop HTTP server\n",
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.
600 [](evutil_socket_t, short, void *) {
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 }
612 eventBase = nullptr;
613 }
614 LogPrint(BCLog::HTTP, "Stopped HTTP server\n");
615}
616
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
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}
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}
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 {
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
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) {
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
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) {
724 if (conn) {
726 if (bev) {
728 }
729 }
730 }
731 });
732 ev->trigger(nullptr);
733 replySent = true;
734 // transferred back to main thread.
735 req = nullptr;
736}
737
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 {
753}
754
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;
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
A combination of a network address (CNetAddr) and a (TCP) port.
Definition netaddress.h:545
bool IsValid() const
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
std::function< void()> handler
Definition httpserver.h:155
HTTPEvent(struct event_base *base, bool deleteWhenTriggered, const std::function< void()> &handler)
Create a new event.
void trigger(struct timeval *tv)
Trigger the event.
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.
std::string GetURI() const
Get requested URI.
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
struct evhttp_request * req
Definition httpserver.h:73
RequestMethod GetRequestMethod() const
Get request method.
std::string ReadBody()
Read request body.
CService GetPeer() const
Get CService (address:ip) for the origin of the http request.
HTTPRequest(struct evhttp_request *req, bool replySent=false)
Helps keep track of open evhttp_connections with active evhttp_requests
void WaitUntilEmpty() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Wait until there are no more connections with active requests in the tracker.
size_t CountActiveConnections() const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
void AddRequest(evhttp_request *req) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Increase request counter for the associated connection by 1.
void RemoveConnection(const evhttp_connection *conn) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Remove a connection entirely.
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.
std::condition_variable m_cv
void RemoveConnectionInternal(const decltype(m_tracker)::iterator it) EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
HTTP request work item.
void operator()() override
std::unique_ptr< HTTPRequest > req
std::string path
Config * config
HTTPWorkItem(Config &_config, std::unique_ptr< HTTPRequest > _req, const std::string &_path, const HTTPRequestHandler &_func)
HTTPRequestHandler func
Simple work queue for distributing work over multiple threads.
bool Enqueue(WorkItem *item) EXCLUSIVE_LOCKS_REQUIRED(!cs)
Enqueue a work item.
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!cs)
Interrupt and exit loops.
~WorkQueue()
Precondition: worker threads have all stopped (they have all been joined)
Mutex cs
Mutex protects entire object.
std::deque< std::unique_ptr< WorkItem > > queue
size_t maxDepth
WorkQueue(size_t _maxDepth)
std::condition_variable cond
void Run() EXCLUSIVE_LOCKS_REQUIRED(!cs)
Thread function.
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.
void InterruptHTTPServer()
Interrupt HTTP server threads.
static void http_request_cb(struct evhttp_request *req, void *arg)
HTTP request callback.
static WorkQueue< HTTPClosure > * workQueue
Work queue for handling longer requests off the event loop thread.
static bool HTTPBindAddresses(struct evhttp *http)
Bind HTTP server to specified addresses.
static std::vector< evhttp_bound_socket * > boundSockets
Bound listening sockets.
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
void StartHTTPServer()
Start HTTP server.
static struct event_base * eventBase
HTTP module state.
void UpdateHTTPServerLogging(bool enable)
Change logging level for libevent.
static std::thread g_thread_http
struct event_base * EventBase()
Return evhttp event base.
static void httpevent_callback_fn(evutil_socket_t, short, void *data)
std::string RequestMethodString(HTTPRequest::RequestMethod m)
HTTP request method as string - use for logging only.
#define EVENT_LOG_WARN
static const size_t MIN_SUPPORTED_BODY_SIZE
Maximum HTTP post body size.
static HTTPRequestTracker g_requests
Track active requests.
static void HTTPWorkQueueRun(WorkQueue< HTTPClosure > *queue, int worker_num)
Simple wrapper to set thread name and run work queue.
static bool InitHTTPAllowList()
Initialize ACL list for HTTP server.
static bool ThreadHTTP(struct event_base *base)
Event dispatcher thread.
static void libevent_log_cb(int severity, const char *msg)
libevent event log callback
static std::vector< CSubNet > rpc_allow_subnets
List of subnets to allow RPC connections from.
static bool ClientAllowed(const CNetAddr &netaddr)
Check if a network address is allowed to access the HTTP server.
static void http_reject_request_cb(struct evhttp_request *req, void *)
Callback to reject HTTP requests after shutdown.
static const size_t MAX_HEADERS_SIZE
Maximum size of http request (request line + headers)
void StopHTTPServer()
Stop HTTP server.
static std::vector< HTTPPathHandler > pathHandlers
Handlers for (sub)paths.
static std::vector< std::thread > g_thread_http_workers
bool InitHTTPServer(Config &config)
Initialize HTTP server.
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.
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
T GetRand(T nMax=std::numeric_limits< T >::max()) noexcept
Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limi...
Definition random.h:85
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)
std::string prefix
HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler)
HTTPRequestHandler handler
#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(...)
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
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())