Bitcoin Core  24.99.0
P2P Digital Currency
httpserver.cpp
Go to the documentation of this file.
1 // Copyright (c) 2015-2021 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #if defined(HAVE_CONFIG_H)
7 #endif
8 
9 #include <httpserver.h>
10 
11 #include <chainparamsbase.h>
12 #include <compat/compat.h>
13 #include <netbase.h>
14 #include <node/interface_ui.h>
15 #include <rpc/protocol.h> // For HTTP status codes
16 #include <shutdown.h>
17 #include <sync.h>
18 #include <util/strencodings.h>
19 #include <util/syscall_sandbox.h>
20 #include <util/system.h>
21 #include <util/threadnames.h>
22 #include <util/translation.h>
23 
24 #include <cstdio>
25 #include <cstdlib>
26 #include <deque>
27 #include <memory>
28 #include <optional>
29 #include <string>
30 
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 
34 #include <event2/buffer.h>
35 #include <event2/bufferevent.h>
36 #include <event2/http.h>
37 #include <event2/keyvalq_struct.h>
38 #include <event2/thread.h>
39 #include <event2/util.h>
40 
41 #include <support/events.h>
42 
44 static const size_t MAX_HEADERS_SIZE = 8192;
45 
47 class HTTPWorkItem final : public HTTPClosure
48 {
49 public:
50  HTTPWorkItem(std::unique_ptr<HTTPRequest> _req, const std::string &_path, const HTTPRequestHandler& _func):
51  req(std::move(_req)), path(_path), func(_func)
52  {
53  }
54  void operator()() override
55  {
56  func(req.get(), path);
57  }
58 
59  std::unique_ptr<HTTPRequest> req;
60 
61 private:
62  std::string path;
64 };
65 
69 template <typename WorkItem>
70 class WorkQueue
71 {
72 private:
74  std::condition_variable cond GUARDED_BY(cs);
75  std::deque<std::unique_ptr<WorkItem>> queue GUARDED_BY(cs);
76  bool running GUARDED_BY(cs){true};
77  const size_t maxDepth;
78 
79 public:
80  explicit WorkQueue(size_t _maxDepth) : maxDepth(_maxDepth)
81  {
82  }
85  ~WorkQueue() = default;
87  bool Enqueue(WorkItem* item) EXCLUSIVE_LOCKS_REQUIRED(!cs)
88  {
89  LOCK(cs);
90  if (!running || queue.size() >= maxDepth) {
91  return false;
92  }
93  queue.emplace_back(std::unique_ptr<WorkItem>(item));
94  cond.notify_one();
95  return true;
96  }
99  {
100  while (true) {
101  std::unique_ptr<WorkItem> i;
102  {
103  WAIT_LOCK(cs, lock);
104  while (running && queue.empty())
105  cond.wait(lock);
106  if (!running && queue.empty())
107  break;
108  i = std::move(queue.front());
109  queue.pop_front();
110  }
111  (*i)();
112  }
113  }
116  {
117  LOCK(cs);
118  running = false;
119  cond.notify_all();
120  }
121 };
122 
124 {
125  HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler):
126  prefix(_prefix), exactMatch(_exactMatch), handler(_handler)
127  {
128  }
129  std::string prefix;
132 };
133 
137 static struct event_base* eventBase = nullptr;
139 static struct evhttp* eventHTTP = nullptr;
141 static std::vector<CSubNet> rpc_allow_subnets;
143 static std::unique_ptr<WorkQueue<HTTPClosure>> g_work_queue{nullptr};
146 static std::vector<HTTPPathHandler> pathHandlers GUARDED_BY(g_httppathhandlers_mutex);
148 static std::vector<evhttp_bound_socket *> boundSockets;
149 
151 static bool ClientAllowed(const CNetAddr& netaddr)
152 {
153  if (!netaddr.IsValid())
154  return false;
155  for(const CSubNet& subnet : rpc_allow_subnets)
156  if (subnet.Match(netaddr))
157  return true;
158  return false;
159 }
160 
162 static bool InitHTTPAllowList()
163 {
164  rpc_allow_subnets.clear();
165  CNetAddr localv4;
166  CNetAddr localv6;
167  LookupHost("127.0.0.1", localv4, false);
168  LookupHost("::1", localv6, false);
169  rpc_allow_subnets.push_back(CSubNet(localv4, 8)); // always allow IPv4 local subnet
170  rpc_allow_subnets.push_back(CSubNet(localv6)); // always allow IPv6 localhost
171  for (const std::string& strAllow : gArgs.GetArgs("-rpcallowip")) {
172  CSubNet subnet;
173  LookupSubNet(strAllow, subnet);
174  if (!subnet.IsValid()) {
175  uiInterface.ThreadSafeMessageBox(
176  strprintf(Untranslated("Invalid -rpcallowip subnet specification: %s. Valid are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24)."), strAllow),
178  return false;
179  }
180  rpc_allow_subnets.push_back(subnet);
181  }
182  std::string strAllowed;
183  for (const CSubNet& subnet : rpc_allow_subnets)
184  strAllowed += subnet.ToString() + " ";
185  LogPrint(BCLog::HTTP, "Allowing HTTP connections from: %s\n", strAllowed);
186  return true;
187 }
188 
191 {
192  switch (m) {
193  case HTTPRequest::GET:
194  return "GET";
195  break;
196  case HTTPRequest::POST:
197  return "POST";
198  break;
199  case HTTPRequest::HEAD:
200  return "HEAD";
201  break;
202  case HTTPRequest::PUT:
203  return "PUT";
204  break;
205  default:
206  return "unknown";
207  }
208 }
209 
211 static void http_request_cb(struct evhttp_request* req, void* arg)
212 {
213  // Disable reading to work around a libevent bug, fixed in 2.2.0.
214  if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02020001) {
215  evhttp_connection* conn = evhttp_request_get_connection(req);
216  if (conn) {
217  bufferevent* bev = evhttp_connection_get_bufferevent(conn);
218  if (bev) {
219  bufferevent_disable(bev, EV_READ);
220  }
221  }
222  }
223  std::unique_ptr<HTTPRequest> hreq(new HTTPRequest(req));
224 
225  // Early address-based allow check
226  if (!ClientAllowed(hreq->GetPeer())) {
227  LogPrint(BCLog::HTTP, "HTTP request from %s rejected: Client network is not allowed RPC access\n",
228  hreq->GetPeer().ToString());
229  hreq->WriteReply(HTTP_FORBIDDEN);
230  return;
231  }
232 
233  // Early reject unknown HTTP methods
234  if (hreq->GetRequestMethod() == HTTPRequest::UNKNOWN) {
235  LogPrint(BCLog::HTTP, "HTTP request from %s rejected: Unknown HTTP request method\n",
236  hreq->GetPeer().ToString());
237  hreq->WriteReply(HTTP_BAD_METHOD);
238  return;
239  }
240 
241  LogPrint(BCLog::HTTP, "Received a %s request for %s from %s\n",
242  RequestMethodString(hreq->GetRequestMethod()), SanitizeString(hreq->GetURI(), SAFE_CHARS_URI).substr(0, 100), hreq->GetPeer().ToString());
243 
244  // Find registered handler for prefix
245  std::string strURI = hreq->GetURI();
246  std::string path;
248  std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin();
249  std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end();
250  for (; i != iend; ++i) {
251  bool match = false;
252  if (i->exactMatch)
253  match = (strURI == i->prefix);
254  else
255  match = (strURI.substr(0, i->prefix.size()) == i->prefix);
256  if (match) {
257  path = strURI.substr(i->prefix.size());
258  break;
259  }
260  }
261 
262  // Dispatch to worker thread
263  if (i != iend) {
264  std::unique_ptr<HTTPWorkItem> item(new HTTPWorkItem(std::move(hreq), path, i->handler));
266  if (g_work_queue->Enqueue(item.get())) {
267  item.release(); /* if true, queue took ownership */
268  } else {
269  LogPrintf("WARNING: request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting\n");
270  item->req->WriteReply(HTTP_SERVICE_UNAVAILABLE, "Work queue depth exceeded");
271  }
272  } else {
273  hreq->WriteReply(HTTP_NOT_FOUND);
274  }
275 }
276 
278 static void http_reject_request_cb(struct evhttp_request* req, void*)
279 {
280  LogPrint(BCLog::HTTP, "Rejecting request while shutting down\n");
281  evhttp_send_error(req, HTTP_SERVUNAVAIL, nullptr);
282 }
283 
285 static bool ThreadHTTP(struct event_base* base)
286 {
287  util::ThreadRename("http");
289  LogPrint(BCLog::HTTP, "Entering http event loop\n");
290  event_base_dispatch(base);
291  // Event loop will be interrupted by InterruptHTTPServer()
292  LogPrint(BCLog::HTTP, "Exited http event loop\n");
293  return event_base_got_break(base) == 0;
294 }
295 
297 static bool HTTPBindAddresses(struct evhttp* http)
298 {
299  uint16_t http_port{static_cast<uint16_t>(gArgs.GetIntArg("-rpcport", BaseParams().RPCPort()))};
300  std::vector<std::pair<std::string, uint16_t>> endpoints;
301 
302  // Determine what addresses to bind to
303  if (!(gArgs.IsArgSet("-rpcallowip") && gArgs.IsArgSet("-rpcbind"))) { // Default to loopback if not allowing external IPs
304  endpoints.push_back(std::make_pair("::1", http_port));
305  endpoints.push_back(std::make_pair("127.0.0.1", http_port));
306  if (gArgs.IsArgSet("-rpcallowip")) {
307  LogPrintf("WARNING: option -rpcallowip was specified without -rpcbind; this doesn't usually make sense\n");
308  }
309  if (gArgs.IsArgSet("-rpcbind")) {
310  LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
311  }
312  } else if (gArgs.IsArgSet("-rpcbind")) { // Specific bind address
313  for (const std::string& strRPCBind : gArgs.GetArgs("-rpcbind")) {
314  uint16_t port{http_port};
315  std::string host;
316  SplitHostPort(strRPCBind, port, host);
317  endpoints.push_back(std::make_pair(host, port));
318  }
319  }
320 
321  // Bind addresses
322  for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
323  LogPrintf("Binding RPC on address %s port %i\n", i->first, i->second);
324  evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? nullptr : i->first.c_str(), i->second);
325  if (bind_handle) {
326  CNetAddr addr;
327  if (i->first.empty() || (LookupHost(i->first, addr, false) && addr.IsBindAny())) {
328  LogPrintf("WARNING: the RPC server is not safe to expose to untrusted networks such as the public internet\n");
329  }
330  boundSockets.push_back(bind_handle);
331  } else {
332  LogPrintf("Binding RPC on address %s port %i failed.\n", i->first, i->second);
333  }
334  }
335  return !boundSockets.empty();
336 }
337 
339 static void HTTPWorkQueueRun(WorkQueue<HTTPClosure>* queue, int worker_num)
340 {
341  util::ThreadRename(strprintf("httpworker.%i", worker_num));
343  queue->Run();
344 }
345 
347 static void libevent_log_cb(int severity, const char *msg)
348 {
349  BCLog::Level level;
350  switch (severity) {
351  case EVENT_LOG_DEBUG:
352  level = BCLog::Level::Debug;
353  break;
354  case EVENT_LOG_MSG:
355  level = BCLog::Level::Info;
356  break;
357  case EVENT_LOG_WARN:
358  level = BCLog::Level::Warning;
359  break;
360  default: // EVENT_LOG_ERR and others are mapped to error
361  level = BCLog::Level::Error;
362  break;
363  }
364  LogPrintLevel(BCLog::LIBEVENT, level, "%s\n", msg);
365 }
366 
368 {
369  if (!InitHTTPAllowList())
370  return false;
371 
372  // Redirect libevent's logging to our own log
373  event_set_log_callback(&libevent_log_cb);
374  // Update libevent's log handling.
376 
377 #ifdef WIN32
378  evthread_use_windows_threads();
379 #else
380  evthread_use_pthreads();
381 #endif
382 
383  raii_event_base base_ctr = obtain_event_base();
384 
385  /* Create a new evhttp object to handle requests. */
386  raii_evhttp http_ctr = obtain_evhttp(base_ctr.get());
387  struct evhttp* http = http_ctr.get();
388  if (!http) {
389  LogPrintf("couldn't create evhttp. Exiting.\n");
390  return false;
391  }
392 
393  evhttp_set_timeout(http, gArgs.GetIntArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
394  evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
395  evhttp_set_max_body_size(http, MAX_SIZE);
396  evhttp_set_gencb(http, http_request_cb, nullptr);
397 
398  if (!HTTPBindAddresses(http)) {
399  LogPrintf("Unable to bind any endpoint for RPC server\n");
400  return false;
401  }
402 
403  LogPrint(BCLog::HTTP, "Initialized HTTP server\n");
404  int workQueueDepth = std::max((long)gArgs.GetIntArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
405  LogPrintfCategory(BCLog::HTTP, "creating work queue of depth %d\n", workQueueDepth);
406 
407  g_work_queue = std::make_unique<WorkQueue<HTTPClosure>>(workQueueDepth);
408  // transfer ownership to eventBase/HTTP via .release()
409  eventBase = base_ctr.release();
410  eventHTTP = http_ctr.release();
411  return true;
412 }
413 
414 void UpdateHTTPServerLogging(bool enable) {
415  if (enable) {
416  event_enable_debug_logging(EVENT_DBG_ALL);
417  } else {
418  event_enable_debug_logging(EVENT_DBG_NONE);
419  }
420 }
421 
422 static std::thread g_thread_http;
423 static std::vector<std::thread> g_thread_http_workers;
424 
426 {
427  LogPrint(BCLog::HTTP, "Starting HTTP server\n");
428  int rpcThreads = std::max((long)gArgs.GetIntArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L);
429  LogPrintfCategory(BCLog::HTTP, "starting %d worker threads\n", rpcThreads);
430  g_thread_http = std::thread(ThreadHTTP, eventBase);
431 
432  for (int i = 0; i < rpcThreads; i++) {
433  g_thread_http_workers.emplace_back(HTTPWorkQueueRun, g_work_queue.get(), i);
434  }
435 }
436 
438 {
439  LogPrint(BCLog::HTTP, "Interrupting HTTP server\n");
440  if (eventHTTP) {
441  // Reject requests on current connections
442  evhttp_set_gencb(eventHTTP, http_reject_request_cb, nullptr);
443  }
444  if (g_work_queue) {
445  g_work_queue->Interrupt();
446  }
447 }
448 
450 {
451  LogPrint(BCLog::HTTP, "Stopping HTTP server\n");
452  if (g_work_queue) {
453  LogPrint(BCLog::HTTP, "Waiting for HTTP worker threads to exit\n");
454  for (auto& thread : g_thread_http_workers) {
455  thread.join();
456  }
457  g_thread_http_workers.clear();
458  }
459  // Unlisten sockets, these are what make the event loop running, which means
460  // that after this and all connections are closed the event loop will quit.
461  for (evhttp_bound_socket *socket : boundSockets) {
462  evhttp_del_accept_socket(eventHTTP, socket);
463  }
464  boundSockets.clear();
465  if (eventBase) {
466  LogPrint(BCLog::HTTP, "Waiting for HTTP event thread to exit\n");
467  if (g_thread_http.joinable()) g_thread_http.join();
468  }
469  if (eventHTTP) {
470  evhttp_free(eventHTTP);
471  eventHTTP = nullptr;
472  }
473  if (eventBase) {
474  event_base_free(eventBase);
475  eventBase = nullptr;
476  }
477  g_work_queue.reset();
478  LogPrint(BCLog::HTTP, "Stopped HTTP server\n");
479 }
480 
481 struct event_base* EventBase()
482 {
483  return eventBase;
484 }
485 
486 static void httpevent_callback_fn(evutil_socket_t, short, void* data)
487 {
488  // Static handler: simply call inner handler
489  HTTPEvent *self = static_cast<HTTPEvent*>(data);
490  self->handler();
491  if (self->deleteWhenTriggered)
492  delete self;
493 }
494 
495 HTTPEvent::HTTPEvent(struct event_base* base, bool _deleteWhenTriggered, const std::function<void()>& _handler):
496  deleteWhenTriggered(_deleteWhenTriggered), handler(_handler)
497 {
498  ev = event_new(base, -1, 0, httpevent_callback_fn, this);
499  assert(ev);
500 }
502 {
503  event_free(ev);
504 }
505 void HTTPEvent::trigger(struct timeval* tv)
506 {
507  if (tv == nullptr)
508  event_active(ev, 0, 0); // immediately trigger event in main thread
509  else
510  evtimer_add(ev, tv); // trigger after timeval passed
511 }
512 HTTPRequest::HTTPRequest(struct evhttp_request* _req, bool _replySent) : req(_req), replySent(_replySent)
513 {
514 }
515 
517 {
518  if (!replySent) {
519  // Keep track of whether reply was sent to avoid request leaks
520  LogPrintf("%s: Unhandled request\n", __func__);
521  WriteReply(HTTP_INTERNAL_SERVER_ERROR, "Unhandled request");
522  }
523  // evhttpd cleans up the request, as long as a reply was sent.
524 }
525 
526 std::pair<bool, std::string> HTTPRequest::GetHeader(const std::string& hdr) const
527 {
528  const struct evkeyvalq* headers = evhttp_request_get_input_headers(req);
529  assert(headers);
530  const char* val = evhttp_find_header(headers, hdr.c_str());
531  if (val)
532  return std::make_pair(true, val);
533  else
534  return std::make_pair(false, "");
535 }
536 
538 {
539  struct evbuffer* buf = evhttp_request_get_input_buffer(req);
540  if (!buf)
541  return "";
542  size_t size = evbuffer_get_length(buf);
549  const char* data = (const char*)evbuffer_pullup(buf, size);
550  if (!data) // returns nullptr in case of empty buffer
551  return "";
552  std::string rv(data, size);
553  evbuffer_drain(buf, size);
554  return rv;
555 }
556 
557 void HTTPRequest::WriteHeader(const std::string& hdr, const std::string& value)
558 {
559  struct evkeyvalq* headers = evhttp_request_get_output_headers(req);
560  assert(headers);
561  evhttp_add_header(headers, hdr.c_str(), value.c_str());
562 }
563 
569 void HTTPRequest::WriteReply(int nStatus, const std::string& strReply)
570 {
571  assert(!replySent && req);
572  if (ShutdownRequested()) {
573  WriteHeader("Connection", "close");
574  }
575  // Send event to main http thread to send reply message
576  struct evbuffer* evb = evhttp_request_get_output_buffer(req);
577  assert(evb);
578  evbuffer_add(evb, strReply.data(), strReply.size());
579  auto req_copy = req;
580  HTTPEvent* ev = new HTTPEvent(eventBase, true, [req_copy, nStatus]{
581  evhttp_send_reply(req_copy, nStatus, nullptr, nullptr);
582  // Re-enable reading from the socket. This is the second part of the libevent
583  // workaround above.
584  if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02020001) {
585  evhttp_connection* conn = evhttp_request_get_connection(req_copy);
586  if (conn) {
587  bufferevent* bev = evhttp_connection_get_bufferevent(conn);
588  if (bev) {
589  bufferevent_enable(bev, EV_READ | EV_WRITE);
590  }
591  }
592  }
593  });
594  ev->trigger(nullptr);
595  replySent = true;
596  req = nullptr; // transferred back to main thread
597 }
598 
600 {
601  evhttp_connection* con = evhttp_request_get_connection(req);
602  CService peer;
603  if (con) {
604  // evhttp retains ownership over returned address string
605  const char* address = "";
606  uint16_t port = 0;
607 
608 #ifdef HAVE_EVHTTP_CONNECTION_GET_PEER_CONST_CHAR
609  evhttp_connection_get_peer(con, &address, &port);
610 #else
611  evhttp_connection_get_peer(con, (char**)&address, &port);
612 #endif // HAVE_EVHTTP_CONNECTION_GET_PEER_CONST_CHAR
613 
614  peer = LookupNumeric(address, port);
615  }
616  return peer;
617 }
618 
619 std::string HTTPRequest::GetURI() const
620 {
621  return evhttp_request_get_uri(req);
622 }
623 
625 {
626  switch (evhttp_request_get_command(req)) {
627  case EVHTTP_REQ_GET:
628  return GET;
629  break;
630  case EVHTTP_REQ_POST:
631  return POST;
632  break;
633  case EVHTTP_REQ_HEAD:
634  return HEAD;
635  break;
636  case EVHTTP_REQ_PUT:
637  return PUT;
638  break;
639  default:
640  return UNKNOWN;
641  break;
642  }
643 }
644 
645 std::optional<std::string> HTTPRequest::GetQueryParameter(const std::string& key) const
646 {
647  const char* uri{evhttp_request_get_uri(req)};
648 
649  return GetQueryParameterFromUri(uri, key);
650 }
651 
652 std::optional<std::string> GetQueryParameterFromUri(const char* uri, const std::string& key)
653 {
654  evhttp_uri* uri_parsed{evhttp_uri_parse(uri)};
655  const char* query{evhttp_uri_get_query(uri_parsed)};
656  std::optional<std::string> result;
657 
658  if (query) {
659  // Parse the query string into a key-value queue and iterate over it
660  struct evkeyvalq params_q;
661  evhttp_parse_query_str(query, &params_q);
662 
663  for (struct evkeyval* param{params_q.tqh_first}; param != nullptr; param = param->next.tqe_next) {
664  if (param->key == key) {
665  result = param->value;
666  break;
667  }
668  }
669  evhttp_clear_headers(&params_q);
670  }
671  evhttp_uri_free(uri_parsed);
672 
673  return result;
674 }
675 
676 void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
677 {
678  LogPrint(BCLog::HTTP, "Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
680  pathHandlers.push_back(HTTPPathHandler(prefix, exactMatch, handler));
681 }
682 
683 void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
684 {
686  std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
687  std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
688  for (; i != iend; ++i)
689  if (i->prefix == prefix && i->exactMatch == exactMatch)
690  break;
691  if (i != iend)
692  {
693  LogPrint(BCLog::HTTP, "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
694  pathHandlers.erase(i);
695  }
696 }
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: system.cpp:491
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:500
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: system.cpp:629
Network address.
Definition: netaddress.h:118
bool IsBindAny() const
Definition: netaddress.cpp:304
bool IsValid() const
Definition: netaddress.cpp:445
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:521
bool IsValid() const
Different type to mark Mutex at global scope.
Definition: sync.h:141
Event handler closure.
Definition: httpserver.h:146
Event class.
Definition: httpserver.h:155
struct event * ev
Definition: httpserver.h:172
std::function< void()> handler
Definition: httpserver.h:170
HTTPEvent(struct event_base *base, bool deleteWhenTriggered, const std::function< void()> &handler)
Create a new event.
Definition: httpserver.cpp:495
void trigger(struct timeval *tv)
Trigger the event.
Definition: httpserver.cpp:505
In-flight HTTP request.
Definition: httpserver.h:57
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:645
bool replySent
Definition: httpserver.h:60
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:526
std::string GetURI() const
Get requested URI.
Definition: httpserver.cpp:619
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
Definition: httpserver.cpp:569
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
Definition: httpserver.cpp:557
struct evhttp_request * req
Definition: httpserver.h:59
RequestMethod GetRequestMethod() const
Get request method.
Definition: httpserver.cpp:624
std::string ReadBody()
Read request body.
Definition: httpserver.cpp:537
CService GetPeer() const
Get CService (address:ip) for the origin of the http request.
Definition: httpserver.cpp:599
HTTPRequest(struct evhttp_request *req, bool replySent=false)
Definition: httpserver.cpp:512
HTTP request work item.
Definition: httpserver.cpp:48
void operator()() override
Definition: httpserver.cpp:54
std::unique_ptr< HTTPRequest > req
Definition: httpserver.cpp:59
HTTPWorkItem(std::unique_ptr< HTTPRequest > _req, const std::string &_path, const HTTPRequestHandler &_func)
Definition: httpserver.cpp:50
std::string path
Definition: httpserver.cpp:62
HTTPRequestHandler func
Definition: httpserver.cpp:63
Simple work queue for distributing work over multiple threads.
Definition: httpserver.cpp:71
const size_t maxDepth
Definition: httpserver.cpp:76
bool Enqueue(WorkItem *item) EXCLUSIVE_LOCKS_REQUIRED(!cs)
Enqueue a work item.
Definition: httpserver.cpp:87
~WorkQueue()=default
Precondition: worker threads have all stopped (they have been joined).
std::condition_variable cond GUARDED_BY(cs)
void Interrupt() EXCLUSIVE_LOCKS_REQUIRED(!cs)
Interrupt and exit loops.
Definition: httpserver.cpp:115
Mutex cs
Definition: httpserver.cpp:73
bool running GUARDED_BY(cs)
Definition: httpserver.cpp:76
WorkQueue(size_t _maxDepth)
Definition: httpserver.cpp:80
void Run() EXCLUSIVE_LOCKS_REQUIRED(!cs)
Thread function.
Definition: httpserver.cpp:98
std::deque< std::unique_ptr< WorkItem > > queue GUARDED_BY(cs)
raii_evhttp obtain_evhttp(struct event_base *base)
Definition: events.h:41
raii_event_base obtain_event_base()
Definition: events.h:30
static struct evhttp * eventHTTP
HTTP server.
Definition: httpserver.cpp:139
void InterruptHTTPServer()
Interrupt HTTP server threads.
Definition: httpserver.cpp:437
static void http_request_cb(struct evhttp_request *req, void *arg)
HTTP request callback.
Definition: httpserver.cpp:211
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:652
static bool HTTPBindAddresses(struct evhttp *http)
Bind HTTP server to specified addresses.
Definition: httpserver.cpp:297
static std::vector< evhttp_bound_socket * > boundSockets
Bound listening sockets.
Definition: httpserver.cpp:148
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
Definition: httpserver.cpp:683
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
Definition: httpserver.cpp:676
struct event_base * EventBase()
Return evhttp event base.
Definition: httpserver.cpp:481
void StartHTTPServer()
Start HTTP server.
Definition: httpserver.cpp:425
static struct event_base * eventBase
HTTP module state.
Definition: httpserver.cpp:137
void UpdateHTTPServerLogging(bool enable)
Change logging level for libevent.
Definition: httpserver.cpp:414
static std::thread g_thread_http
Definition: httpserver.cpp:422
static std::unique_ptr< WorkQueue< HTTPClosure > > g_work_queue
Work queue for handling longer requests off the event loop thread.
Definition: httpserver.cpp:143
bool InitHTTPServer()
Initialize HTTP server.
Definition: httpserver.cpp:367
static void httpevent_callback_fn(evutil_socket_t, short, void *data)
Definition: httpserver.cpp:486
std::string RequestMethodString(HTTPRequest::RequestMethod m)
HTTP request method as string - use for logging only.
Definition: httpserver.cpp:190
static void HTTPWorkQueueRun(WorkQueue< HTTPClosure > *queue, int worker_num)
Simple wrapper to set thread name and run work queue.
Definition: httpserver.cpp:339
static bool InitHTTPAllowList()
Initialize ACL list for HTTP server.
Definition: httpserver.cpp:162
static bool ThreadHTTP(struct event_base *base)
Event dispatcher thread.
Definition: httpserver.cpp:285
static void libevent_log_cb(int severity, const char *msg)
libevent event log callback
Definition: httpserver.cpp:347
static std::vector< CSubNet > rpc_allow_subnets
List of subnets to allow RPC connections from.
Definition: httpserver.cpp:141
static bool ClientAllowed(const CNetAddr &netaddr)
Check if a network address is allowed to access the HTTP server.
Definition: httpserver.cpp:151
static void http_reject_request_cb(struct evhttp_request *req, void *)
Callback to reject HTTP requests after shutdown.
Definition: httpserver.cpp:278
static std::vector< HTTPPathHandler > pathHandlers GUARDED_BY(g_httppathhandlers_mutex)
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:449
static std::vector< std::thread > g_thread_http_workers
Definition: httpserver.cpp:423
static GlobalMutex g_httppathhandlers_mutex
Handlers for (sub)paths.
Definition: httpserver.cpp:145
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(HTTPRequest *req, const std::string &)> HTTPRequestHandler
Handler for requests to a certain HTTP path.
Definition: httpserver.h:39
CClientUIInterface uiInterface
BCLog::Logger & LogInstance()
Definition: logging.cpp:20
#define LogPrintLevel(category, level,...)
Definition: logging.h:251
#define LogPrint(category,...)
Definition: logging.h:243
#define LogPrintfCategory(category,...)
Definition: logging.h:237
#define LogPrintf(...)
Definition: logging.h:234
Level
Definition: logging.h:71
@ HTTP
Definition: logging.h:43
@ LIBEVENT
Definition: logging.h:57
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:59
bool LookupSubNet(const std::string &subnet_str, CSubNet &subnet_out)
Parse and resolve a specified subnet string into the appropriate internal representation.
Definition: netbase.cpp:685
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:230
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:170
const char * prefix
Definition: rest.cpp:930
bool(* handler)(const std::any &context, HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:931
@ HTTP_BAD_METHOD
Definition: protocol.h:17
@ HTTP_SERVICE_UNAVAILABLE
Definition: protocol.h:19
@ HTTP_NOT_FOUND
Definition: protocol.h:16
@ HTTP_FORBIDDEN
Definition: protocol.h:15
@ HTTP_INTERNAL_SERVER_ERROR
Definition: protocol.h:18
static constexpr uint64_t MAX_SIZE
The maximum size of a serialized object in bytes or number of elements (for eg vectors) when the size...
Definition: serialize.h:31
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
Definition: shutdown.cpp:89
@ SAFE_CHARS_URI
Chars allowed in URIs (RFC 3986)
Definition: strencodings.h:32
std::string prefix
Definition: httpserver.cpp:129
HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler)
Definition: httpserver.cpp:125
HTTPRequestHandler handler
Definition: httpserver.cpp:131
#define WAIT_LOCK(cs, name)
Definition: sync.h:266
#define LOCK(cs)
Definition: sync.h:261
void SetSyscallSandboxPolicy(SyscallSandboxPolicy syscall_policy)
Force the current thread (and threads created from the current thread) into a restricted-service oper...
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:48
void SplitHostPort(std::string_view in, uint16_t &portOut, std::string &hostOut)
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.
ArgsManager gArgs
Definition: system.cpp:86
assert(!tx.IsCoinBase())