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