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