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