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