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