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