Bitcoin ABC  0.24.10
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 
388 bool InitHTTPServer(Config &config) {
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 g_thread_http;
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  g_thread_http = std::thread(ThreadHTTP, eventBase);
472 
473  for (int i = 0; i < rpcThreads; 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  if (g_thread_http.joinable()) {
509  g_thread_http.join();
510  }
511  }
512  if (eventHTTP) {
513  evhttp_free(eventHTTP);
514  eventHTTP = nullptr;
515  }
516  if (eventBase) {
517  event_base_free(eventBase);
518  eventBase = nullptr;
519  }
520  LogPrint(BCLog::HTTP, "Stopped HTTP server\n");
521 }
522 
523 struct event_base *EventBase() {
524  return eventBase;
525 }
526 
527 static void httpevent_callback_fn(evutil_socket_t, short, void *data) {
528  // Static handler: simply call inner handler
529  HTTPEvent *self = static_cast<HTTPEvent *>(data);
530  self->handler();
531  if (self->deleteWhenTriggered) {
532  delete self;
533  }
534 }
535 
536 HTTPEvent::HTTPEvent(struct event_base *base, bool _deleteWhenTriggered,
537  const std::function<void()> &_handler)
538  : deleteWhenTriggered(_deleteWhenTriggered), handler(_handler) {
539  ev = event_new(base, -1, 0, httpevent_callback_fn, this);
540  assert(ev);
541 }
543  event_free(ev);
544 }
545 void HTTPEvent::trigger(struct timeval *tv) {
546  if (tv == nullptr) {
547  // Immediately trigger event in main thread.
548  event_active(ev, 0, 0);
549  } else {
550  // Trigger after timeval passed.
551  evtimer_add(ev, tv);
552  }
553 }
554 HTTPRequest::HTTPRequest(struct evhttp_request *_req, bool _replySent)
555  : req(_req), replySent(_replySent) {}
557  if (!replySent) {
558  // Keep track of whether reply was sent to avoid request leaks
559  LogPrintf("%s: Unhandled request\n", __func__);
560  WriteReply(HTTP_INTERNAL_SERVER_ERROR, "Unhandled request");
561  }
562  // evhttpd cleans up the request, as long as a reply was sent.
563 }
564 
565 std::pair<bool, std::string>
566 HTTPRequest::GetHeader(const std::string &hdr) const {
567  const struct evkeyvalq *headers = evhttp_request_get_input_headers(req);
568  assert(headers);
569  const char *val = evhttp_find_header(headers, hdr.c_str());
570  if (val) {
571  return std::make_pair(true, val);
572  } else {
573  return std::make_pair(false, "");
574  }
575 }
576 
577 std::string HTTPRequest::ReadBody() {
578  struct evbuffer *buf = evhttp_request_get_input_buffer(req);
579  if (!buf) {
580  return "";
581  }
582  size_t size = evbuffer_get_length(buf);
590  const char *data = (const char *)evbuffer_pullup(buf, size);
591 
592  // returns nullptr in case of empty buffer.
593  if (!data) {
594  return "";
595  }
596  std::string rv(data, size);
597  evbuffer_drain(buf, size);
598  return rv;
599 }
600 
601 void HTTPRequest::WriteHeader(const std::string &hdr,
602  const std::string &value) {
603  struct evkeyvalq *headers = evhttp_request_get_output_headers(req);
604  assert(headers);
605  evhttp_add_header(headers, hdr.c_str(), value.c_str());
606 }
607 
613 void HTTPRequest::WriteReply(int nStatus, const std::string &strReply) {
614  assert(!replySent && req);
615  if (ShutdownRequested()) {
616  WriteHeader("Connection", "close");
617  }
618  // Send event to main http thread to send reply message
619  struct evbuffer *evb = evhttp_request_get_output_buffer(req);
620  assert(evb);
621  evbuffer_add(evb, strReply.data(), strReply.size());
622  auto req_copy = req;
623  HTTPEvent *ev = new HTTPEvent(eventBase, true, [req_copy, nStatus] {
624  evhttp_send_reply(req_copy, nStatus, nullptr, nullptr);
625  // Re-enable reading from the socket. This is the second part of the
626  // libevent workaround above.
627  if (event_get_version_number() >= 0x02010600 &&
628  event_get_version_number() < 0x02020001) {
629  evhttp_connection *conn = evhttp_request_get_connection(req_copy);
630  if (conn) {
631  bufferevent *bev = evhttp_connection_get_bufferevent(conn);
632  if (bev) {
633  bufferevent_enable(bev, EV_READ | EV_WRITE);
634  }
635  }
636  }
637  });
638  ev->trigger(nullptr);
639  replySent = true;
640  // transferred back to main thread.
641  req = nullptr;
642 }
643 
645  evhttp_connection *con = evhttp_request_get_connection(req);
646  CService peer;
647  if (con) {
648  // evhttp retains ownership over returned address string
649  const char *address = "";
650  uint16_t port = 0;
651  evhttp_connection_get_peer(con, (char **)&address, &port);
652  peer = LookupNumeric(address, port);
653  }
654  return peer;
655 }
656 
657 std::string HTTPRequest::GetURI() const {
658  return evhttp_request_get_uri(req);
659 }
660 
662  switch (evhttp_request_get_command(req)) {
663  case EVHTTP_REQ_GET:
664  return GET;
665  case EVHTTP_REQ_POST:
666  return POST;
667  case EVHTTP_REQ_HEAD:
668  return HEAD;
669  case EVHTTP_REQ_PUT:
670  return PUT;
671  case EVHTTP_REQ_OPTIONS:
672  return OPTIONS;
673  default:
674  return UNKNOWN;
675  }
676 }
677 
678 void RegisterHTTPHandler(const std::string &prefix, bool exactMatch,
679  const HTTPRequestHandler &handler) {
680  LogPrint(BCLog::HTTP, "Registering HTTP handler for %s (exactmatch %d)\n",
681  prefix, exactMatch);
682  pathHandlers.push_back(HTTPPathHandler(prefix, exactMatch, handler));
683 }
684 
685 void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch) {
686  std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
687  std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
688  for (; i != iend; ++i) {
689  if (i->prefix == prefix && i->exactMatch == exactMatch) {
690  break;
691  }
692  }
693  if (i != iend) {
695  "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix,
696  exactMatch);
697  pathHandlers.erase(i);
698  }
699 }
Config::GetMaxBlockSize
virtual uint64_t GetMaxBlockSize() const =0
ShutdownRequested
bool ShutdownRequested()
Definition: shutdown.cpp:18
CService
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:514
HTTPRequest::HEAD
@ HEAD
Definition: httpserver.h:83
HTTPRequest::GetRequestMethod
RequestMethod GetRequestMethod() const
Get request method.
Definition: httpserver.cpp:661
HTTPEvent::~HTTPEvent
~HTTPEvent()
Definition: httpserver.cpp:542
HTTPWorkItem::path
std::string path
Definition: httpserver.cpp:67
BCLog::HTTP
@ HTTP
Definition: logging.h:41
UnregisterHTTPHandler
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
Definition: httpserver.cpp:685
HTTP_BAD_METHOD
@ HTTP_BAD_METHOD
Definition: protocol.h:16
ClientAllowed
static bool ClientAllowed(const CNetAddr &netaddr)
Check if a network address is allowed to access the HTTP server.
Definition: httpserver.cpp:155
DEFAULT_HTTP_WORKQUEUE
static const int DEFAULT_HTTP_WORKQUEUE
Definition: httpserver.h:13
HTTPRequest::~HTTPRequest
~HTTPRequest()
Definition: httpserver.cpp:556
uiInterface
CClientUIInterface uiInterface
Definition: ui_interface.cpp:12
HTTPWorkQueueRun
static void HTTPWorkQueueRun(WorkQueue< HTTPClosure > *queue, int worker_num)
Simple wrapper to set thread name and run work queue.
Definition: httpserver.cpp:369
workQueue
static WorkQueue< HTTPClosure > * workQueue
Work queue for handling longer requests off the event loop thread.
Definition: httpserver.cpp:148
sync.h
HTTPPathHandler::HTTPPathHandler
HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler)
Definition: httpserver.cpp:131
HTTPWorkItem::HTTPWorkItem
HTTPWorkItem(Config &_config, std::unique_ptr< HTTPRequest > _req, const std::string &_path, const HTTPRequestHandler &_func)
Definition: httpserver.cpp:58
EventBase
struct event_base * EventBase()
Return evhttp event base.
Definition: httpserver.cpp:523
CNetAddr
Network address.
Definition: netaddress.h:117
chainparamsbase.h
EVENT_LOG_WARN
#define EVENT_LOG_WARN
ArgsManager::IsArgSet
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:482
HTTPRequest::GetPeer
CService GetPeer() const
Get CService (address:ip) for the origin of the http request.
Definition: httpserver.cpp:644
protocol.h
AnnotatedMixin< std::mutex >
WorkQueue::Enqueue
bool Enqueue(WorkItem *item)
Enqueue a work item.
Definition: httpserver.cpp:93
HTTPPathHandler::exactMatch
bool exactMatch
Definition: httpserver.cpp:135
SplitHostPort
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)
Definition: strencodings.cpp:113
HTTPRequest::WriteHeader
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
Definition: httpserver.cpp:601
StartHTTPServer
void StartHTTPServer()
Start HTTP server.
Definition: httpserver.cpp:466
HTTPRequest::PUT
@ PUT
Definition: httpserver.h:83
WorkQueue::maxDepth
size_t maxDepth
Definition: httpserver.cpp:83
HTTPRequest::GetURI
std::string GetURI() const
Get requested URI.
Definition: httpserver.cpp:657
HTTPRequest::GetHeader
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:566
CNetAddr::IsBindAny
bool IsBindAny() const
Definition: netaddress.cpp:296
HTTPRequest::OPTIONS
@ OPTIONS
Definition: httpserver.h:83
HTTPWorkItem::req
std::unique_ptr< HTTPRequest > req
Definition: httpserver.cpp:64
HTTPEvent::ev
struct event * ev
Definition: httpserver.h:161
HTTPEvent::HTTPEvent
HTTPEvent(struct event_base *base, bool deleteWhenTriggered, const std::function< void()> &handler)
Create a new event.
Definition: httpserver.cpp:536
shutdown.h
WorkQueue::queue
std::deque< std::unique_ptr< WorkItem > > queue
Definition: httpserver.cpp:81
WorkQueue::cs
Mutex cs
Mutex protects entire object.
Definition: httpserver.cpp:79
prefix
const char * prefix
Definition: rest.cpp:772
HTTPRequest::replySent
bool replySent
Definition: httpserver.h:77
MAX_HEADERS_SIZE
static const size_t MAX_HEADERS_SIZE
Maximum size of http request (request line + headers)
Definition: httpserver.cpp:47
strencodings.h
http_request_cb
static void http_request_cb(struct evhttp_request *req, void *arg)
HTTP request callback.
Definition: httpserver.cpp:221
Config
Definition: config.h:17
WorkQueue
Simple work queue for distributing work over multiple threads.
Definition: httpserver.cpp:76
HTTPRequest::POST
@ POST
Definition: httpserver.h:83
events.h
InitHTTPServer
bool InitHTTPServer(Config &config)
Initialize HTTP server.
Definition: httpserver.cpp:388
eventHTTP
static struct evhttp * eventHTTP
HTTP server.
Definition: httpserver.cpp:144
HTTPWorkItem
HTTP request work item.
Definition: httpserver.cpp:56
HTTPWorkItem::operator()
void operator()() override
Definition: httpserver.cpp:62
Untranslated
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:36
HTTPWorkItem::config
Config * config
Definition: httpserver.cpp:69
MIN_SUPPORTED_BODY_SIZE
static const size_t MIN_SUPPORTED_BODY_SIZE
Maximum HTTP post body size.
Definition: httpserver.cpp:53
HTTP_FORBIDDEN
@ HTTP_FORBIDDEN
Definition: protocol.h:14
UpdateHTTPServerLogging
bool UpdateHTTPServerLogging(bool enable)
Change logging level for libevent.
Definition: httpserver.cpp:449
eventBase
static struct event_base * eventBase
HTTP module state.
Definition: httpserver.cpp:142
g_thread_http_workers
static std::vector< std::thread > g_thread_http_workers
Definition: httpserver.cpp:464
HTTPPathHandler
Definition: httpserver.cpp:130
compat.h
util::ThreadRename
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
BCLog::LIBEVENT
@ LIBEVENT
Definition: logging.h:55
HTTPRequest::ReadBody
std::string ReadBody()
Read request body.
Definition: httpserver.cpp:577
HTTPRequest::UNKNOWN
@ UNKNOWN
Definition: httpserver.h:83
HTTPRequest::HTTPRequest
HTTPRequest(struct evhttp_request *req, bool replySent=false)
Definition: httpserver.cpp:554
ArgsManager::GetArg
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:582
boundSockets
static std::vector< evhttp_bound_socket * > boundSockets
Bound listening sockets.
Definition: httpserver.cpp:152
CNetAddr::IsValid
bool IsValid() const
Definition: netaddress.cpp:441
CSubNet
Definition: netaddress.h:465
WorkQueue::Run
void Run()
Thread function.
Definition: httpserver.cpp:104
WorkQueue::cond
std::condition_variable cond
Definition: httpserver.cpp:80
SAFE_CHARS_URI
@ SAFE_CHARS_URI
Chars allowed in URIs (RFC 3986)
Definition: strencodings.h:31
LogPrint
#define LogPrint(category,...)
Definition: logging.h:193
handler
bool(* handler)(Config &config, const util::Ref &context, HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:773
HTTPRequest::RequestMethod
RequestMethod
Definition: httpserver.h:83
HTTPRequest::req
struct evhttp_request * req
Definition: httpserver.h:76
ui_interface.h
system.h
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1201
CClientUIInterface::MSG_ERROR
@ MSG_ERROR
Definition: ui_interface.h:73
SanitizeString
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
Definition: strencodings.cpp:31
LookupHost
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:177
pathHandlers
static std::vector< HTTPPathHandler > pathHandlers
Handlers for (sub)paths.
Definition: httpserver.cpp:150
obtain_event_base
raii_event_base obtain_event_base()
Definition: events.h:28
libevent_log_cb
static void libevent_log_cb(int severity, const char *msg)
libevent event log callback
Definition: httpserver.cpp:375
translation.h
HTTPEvent::trigger
void trigger(struct timeval *tv)
Trigger the event.
Definition: httpserver.cpp:545
BaseParams
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
Definition: chainparamsbase.cpp:36
HTTPWorkItem::func
HTTPRequestHandler func
Definition: httpserver.cpp:68
HTTPEvent
Event class.
Definition: httpserver.h:139
LOCK
#define LOCK(cs)
Definition: sync.h:241
gArgs
ArgsManager gArgs
Definition: system.cpp:76
InterruptHTTPServer
void InterruptHTTPServer()
Interrupt HTTP server threads.
Definition: httpserver.cpp:478
InitHTTPAllowList
static bool InitHTTPAllowList()
Initialize ACL list for HTTP server.
Definition: httpserver.cpp:168
httpevent_callback_fn
static void httpevent_callback_fn(evutil_socket_t, short, void *data)
Definition: httpserver.cpp:527
logging.h
HTTP_NOT_FOUND
@ HTTP_NOT_FOUND
Definition: protocol.h:15
HTTPClosure
Event handler closure.
Definition: httpserver.h:129
rpc_allow_subnets
static std::vector< CSubNet > rpc_allow_subnets
List of subnets to allow RPC connections from.
Definition: httpserver.cpp:146
LogInstance
BCLog::Logger & LogInstance()
Definition: logging.cpp:15
WorkQueue::WorkQueue
WorkQueue(size_t _maxDepth)
Definition: httpserver.cpp:86
CSubNet::IsValid
bool IsValid() const
Definition: netaddress.cpp:1158
HTTPBindAddresses
static bool HTTPBindAddresses(struct evhttp *http)
Bind HTTP server to specified addresses.
Definition: httpserver.cpp:316
HTTPRequestHandler
std::function< bool(Config &config, HTTPRequest *req, const std::string &)> HTTPRequestHandler
Handler for requests to a certain HTTP path.
Definition: httpserver.h:51
config.h
LookupNumeric
CService LookupNumeric(const std::string &name, int portDefault)
Resolve a service string with a numeric IP to its first corresponding service.
Definition: netbase.cpp:283
RequestMethodString
std::string RequestMethodString(HTTPRequest::RequestMethod m)
HTTP request method as string - use for logging only.
Definition: httpserver.cpp:203
netbase.h
WorkQueue::Interrupt
void Interrupt()
Interrupt and exit loops.
Definition: httpserver.cpp:123
HTTPRequest::GET
@ GET
Definition: httpserver.h:83
httpserver.h
http_reject_request_cb
static void http_reject_request_cb(struct evhttp_request *req, void *)
Callback to reject HTTP requests after shutdown.
Definition: httpserver.cpp:300
ArgsManager::GetArgs
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: system.cpp:473
ThreadHTTP
static bool ThreadHTTP(struct event_base *base)
Event dispatcher thread.
Definition: httpserver.cpp:306
StopHTTPServer
void StopHTTPServer()
Stop HTTP server.
Definition: httpserver.cpp:489
RegisterHTTPHandler
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
Definition: httpserver.cpp:678
g_thread_http
static std::thread g_thread_http
Definition: httpserver.cpp:463
threadnames.h
HTTPRequest::WriteReply
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
Definition: httpserver.cpp:613
DEFAULT_HTTP_THREADS
static const int DEFAULT_HTTP_THREADS
Definition: httpserver.h:12
WorkQueue::~WorkQueue
~WorkQueue()
Precondition: worker threads have all stopped (they have all been joined)
Definition: httpserver.cpp:90
LogPrintf
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:175
WorkQueue::running
bool running
Definition: httpserver.cpp:82
WAIT_LOCK
#define WAIT_LOCK(cs, name)
Definition: sync.h:249
HTTPPathHandler::handler
HTTPRequestHandler handler
Definition: httpserver.cpp:136
HTTPPathHandler::prefix
std::string prefix
Definition: httpserver.cpp:134
DEFAULT_HTTP_SERVER_TIMEOUT
static const int DEFAULT_HTTP_SERVER_TIMEOUT
Definition: httpserver.h:14
LookupSubNet
bool LookupSubNet(const std::string &strSubnet, CSubNet &ret)
Parse and resolve a specified subnet string into the appropriate internal representation.
Definition: netbase.cpp:903
BCLog::Logger::DisableCategory
void DisableCategory(LogFlags category)
Definition: logging.cpp:309
HTTPEvent::handler
std::function< void()> handler
Definition: httpserver.h:158
obtain_evhttp
raii_evhttp obtain_evhttp(struct event_base *base)
Definition: events.h:41
HTTP_INTERNAL_SERVER_ERROR
@ HTTP_INTERNAL_SERVER_ERROR
Definition: protocol.h:17