Bitcoin Core  22.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/syscall_sandbox.h>
16 #include <util/system.h>
17 #include <util/threadnames.h>
18 #include <util/translation.h>
19 
20 #include <deque>
21 #include <memory>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string>
25 
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 
29 #include <event2/thread.h>
30 #include <event2/buffer.h>
31 #include <event2/bufferevent.h>
32 #include <event2/util.h>
33 #include <event2/keyvalq_struct.h>
34 
35 #include <support/events.h>
36 
38 static const size_t MAX_HEADERS_SIZE = 8192;
39 
41 class HTTPWorkItem final : public HTTPClosure
42 {
43 public:
44  HTTPWorkItem(std::unique_ptr<HTTPRequest> _req, const std::string &_path, const HTTPRequestHandler& _func):
45  req(std::move(_req)), path(_path), func(_func)
46  {
47  }
48  void operator()() override
49  {
50  func(req.get(), path);
51  }
52 
53  std::unique_ptr<HTTPRequest> req;
54 
55 private:
56  std::string path;
58 };
59 
63 template <typename WorkItem>
64 class WorkQueue
65 {
66 private:
68  std::condition_variable cond GUARDED_BY(cs);
69  std::deque<std::unique_ptr<WorkItem>> queue GUARDED_BY(cs);
70  bool running GUARDED_BY(cs);
71  const 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 (!running || 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 && queue.empty())
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;
140 static std::unique_ptr<WorkQueue<HTTPClosure>> g_work_queue{nullptr};
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));
261  if (g_work_queue->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");
284  LogPrint(BCLog::HTTP, "Entering http event loop\n");
285  event_base_dispatch(base);
286  // Event loop will be interrupted by InterruptHTTPServer()
287  LogPrint(BCLog::HTTP, "Exited http event loop\n");
288  return event_base_got_break(base) == 0;
289 }
290 
292 static bool HTTPBindAddresses(struct evhttp* http)
293 {
294  uint16_t http_port{static_cast<uint16_t>(gArgs.GetIntArg("-rpcport", BaseParams().RPCPort()))};
295  std::vector<std::pair<std::string, uint16_t>> endpoints;
296 
297  // Determine what addresses to bind to
298  if (!(gArgs.IsArgSet("-rpcallowip") && gArgs.IsArgSet("-rpcbind"))) { // Default to loopback if not allowing external IPs
299  endpoints.push_back(std::make_pair("::1", http_port));
300  endpoints.push_back(std::make_pair("127.0.0.1", http_port));
301  if (gArgs.IsArgSet("-rpcallowip")) {
302  LogPrintf("WARNING: option -rpcallowip was specified without -rpcbind; this doesn't usually make sense\n");
303  }
304  if (gArgs.IsArgSet("-rpcbind")) {
305  LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
306  }
307  } else if (gArgs.IsArgSet("-rpcbind")) { // Specific bind address
308  for (const std::string& strRPCBind : gArgs.GetArgs("-rpcbind")) {
309  uint16_t port{http_port};
310  std::string host;
311  SplitHostPort(strRPCBind, port, host);
312  endpoints.push_back(std::make_pair(host, port));
313  }
314  }
315 
316  // Bind addresses
317  for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
318  LogPrint(BCLog::HTTP, "Binding RPC on address %s port %i\n", i->first, i->second);
319  evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? nullptr : i->first.c_str(), i->second);
320  if (bind_handle) {
321  CNetAddr addr;
322  if (i->first.empty() || (LookupHost(i->first, addr, false) && addr.IsBindAny())) {
323  LogPrintf("WARNING: the RPC server is not safe to expose to untrusted networks such as the public internet\n");
324  }
325  boundSockets.push_back(bind_handle);
326  } else {
327  LogPrintf("Binding RPC on address %s port %i failed.\n", i->first, i->second);
328  }
329  }
330  return !boundSockets.empty();
331 }
332 
334 static void HTTPWorkQueueRun(WorkQueue<HTTPClosure>* queue, int worker_num)
335 {
336  util::ThreadRename(strprintf("httpworker.%i", worker_num));
338  queue->Run();
339 }
340 
342 static void libevent_log_cb(int severity, const char *msg)
343 {
344  if (severity >= EVENT_LOG_WARN) // Log warn messages and higher without debug category
345  LogPrintf("libevent: %s\n", msg);
346  else
347  LogPrint(BCLog::LIBEVENT, "libevent: %s\n", msg);
348 }
349 
351 {
352  if (!InitHTTPAllowList())
353  return false;
354 
355  // Redirect libevent's logging to our own log
356  event_set_log_callback(&libevent_log_cb);
357  // Update libevent's log handling. Returns false if our version of
358  // libevent doesn't support debug logging, in which case we should
359  // clear the BCLog::LIBEVENT flag.
360  if (!UpdateHTTPServerLogging(LogInstance().WillLogCategory(BCLog::LIBEVENT))) {
362  }
363 
364 #ifdef WIN32
365  evthread_use_windows_threads();
366 #else
367  evthread_use_pthreads();
368 #endif
369 
370  raii_event_base base_ctr = obtain_event_base();
371 
372  /* Create a new evhttp object to handle requests. */
373  raii_evhttp http_ctr = obtain_evhttp(base_ctr.get());
374  struct evhttp* http = http_ctr.get();
375  if (!http) {
376  LogPrintf("couldn't create evhttp. Exiting.\n");
377  return false;
378  }
379 
380  evhttp_set_timeout(http, gArgs.GetIntArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
381  evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
382  evhttp_set_max_body_size(http, MAX_SIZE);
383  evhttp_set_gencb(http, http_request_cb, nullptr);
384 
385  if (!HTTPBindAddresses(http)) {
386  LogPrintf("Unable to bind any endpoint for RPC server\n");
387  return false;
388  }
389 
390  LogPrint(BCLog::HTTP, "Initialized HTTP server\n");
391  int workQueueDepth = std::max((long)gArgs.GetIntArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
392  LogPrintf("HTTP: creating work queue of depth %d\n", workQueueDepth);
393 
394  g_work_queue = std::make_unique<WorkQueue<HTTPClosure>>(workQueueDepth);
395  // transfer ownership to eventBase/HTTP via .release()
396  eventBase = base_ctr.release();
397  eventHTTP = http_ctr.release();
398  return true;
399 }
400 
401 bool UpdateHTTPServerLogging(bool enable) {
402 #if LIBEVENT_VERSION_NUMBER >= 0x02010100
403  if (enable) {
404  event_enable_debug_logging(EVENT_DBG_ALL);
405  } else {
406  event_enable_debug_logging(EVENT_DBG_NONE);
407  }
408  return true;
409 #else
410  // Can't update libevent logging if version < 02010100
411  return false;
412 #endif
413 }
414 
415 static std::thread g_thread_http;
416 static std::vector<std::thread> g_thread_http_workers;
417 
419 {
420  LogPrint(BCLog::HTTP, "Starting HTTP server\n");
421  int rpcThreads = std::max((long)gArgs.GetIntArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L);
422  LogPrintf("HTTP: starting %d worker threads\n", rpcThreads);
423  g_thread_http = std::thread(ThreadHTTP, eventBase);
424 
425  for (int i = 0; i < rpcThreads; i++) {
426  g_thread_http_workers.emplace_back(HTTPWorkQueueRun, g_work_queue.get(), i);
427  }
428 }
429 
431 {
432  LogPrint(BCLog::HTTP, "Interrupting HTTP server\n");
433  if (eventHTTP) {
434  // Reject requests on current connections
435  evhttp_set_gencb(eventHTTP, http_reject_request_cb, nullptr);
436  }
437  if (g_work_queue) {
438  g_work_queue->Interrupt();
439  }
440 }
441 
443 {
444  LogPrint(BCLog::HTTP, "Stopping HTTP server\n");
445  if (g_work_queue) {
446  LogPrint(BCLog::HTTP, "Waiting for HTTP worker threads to exit\n");
447  for (auto& thread : g_thread_http_workers) {
448  thread.join();
449  }
450  g_thread_http_workers.clear();
451  }
452  // Unlisten sockets, these are what make the event loop running, which means
453  // that after this and all connections are closed the event loop will quit.
454  for (evhttp_bound_socket *socket : boundSockets) {
455  evhttp_del_accept_socket(eventHTTP, socket);
456  }
457  boundSockets.clear();
458  if (eventBase) {
459  LogPrint(BCLog::HTTP, "Waiting for HTTP event thread to exit\n");
460  if (g_thread_http.joinable()) g_thread_http.join();
461  }
462  if (eventHTTP) {
463  evhttp_free(eventHTTP);
464  eventHTTP = nullptr;
465  }
466  if (eventBase) {
467  event_base_free(eventBase);
468  eventBase = nullptr;
469  }
470  g_work_queue.reset();
471  LogPrint(BCLog::HTTP, "Stopped HTTP server\n");
472 }
473 
474 struct event_base* EventBase()
475 {
476  return eventBase;
477 }
478 
479 static void httpevent_callback_fn(evutil_socket_t, short, void* data)
480 {
481  // Static handler: simply call inner handler
482  HTTPEvent *self = static_cast<HTTPEvent*>(data);
483  self->handler();
484  if (self->deleteWhenTriggered)
485  delete self;
486 }
487 
488 HTTPEvent::HTTPEvent(struct event_base* base, bool _deleteWhenTriggered, const std::function<void()>& _handler):
489  deleteWhenTriggered(_deleteWhenTriggered), handler(_handler)
490 {
491  ev = event_new(base, -1, 0, httpevent_callback_fn, this);
492  assert(ev);
493 }
495 {
496  event_free(ev);
497 }
498 void HTTPEvent::trigger(struct timeval* tv)
499 {
500  if (tv == nullptr)
501  event_active(ev, 0, 0); // immediately trigger event in main thread
502  else
503  evtimer_add(ev, tv); // trigger after timeval passed
504 }
505 HTTPRequest::HTTPRequest(struct evhttp_request* _req, bool _replySent) : req(_req), replySent(_replySent)
506 {
507 }
508 
510 {
511  if (!replySent) {
512  // Keep track of whether reply was sent to avoid request leaks
513  LogPrintf("%s: Unhandled request\n", __func__);
514  WriteReply(HTTP_INTERNAL_SERVER_ERROR, "Unhandled request");
515  }
516  // evhttpd cleans up the request, as long as a reply was sent.
517 }
518 
519 std::pair<bool, std::string> HTTPRequest::GetHeader(const std::string& hdr) const
520 {
521  const struct evkeyvalq* headers = evhttp_request_get_input_headers(req);
522  assert(headers);
523  const char* val = evhttp_find_header(headers, hdr.c_str());
524  if (val)
525  return std::make_pair(true, val);
526  else
527  return std::make_pair(false, "");
528 }
529 
531 {
532  struct evbuffer* buf = evhttp_request_get_input_buffer(req);
533  if (!buf)
534  return "";
535  size_t size = evbuffer_get_length(buf);
542  const char* data = (const char*)evbuffer_pullup(buf, size);
543  if (!data) // returns nullptr in case of empty buffer
544  return "";
545  std::string rv(data, size);
546  evbuffer_drain(buf, size);
547  return rv;
548 }
549 
550 void HTTPRequest::WriteHeader(const std::string& hdr, const std::string& value)
551 {
552  struct evkeyvalq* headers = evhttp_request_get_output_headers(req);
553  assert(headers);
554  evhttp_add_header(headers, hdr.c_str(), value.c_str());
555 }
556 
562 void HTTPRequest::WriteReply(int nStatus, const std::string& strReply)
563 {
564  assert(!replySent && req);
565  if (ShutdownRequested()) {
566  WriteHeader("Connection", "close");
567  }
568  // Send event to main http thread to send reply message
569  struct evbuffer* evb = evhttp_request_get_output_buffer(req);
570  assert(evb);
571  evbuffer_add(evb, strReply.data(), strReply.size());
572  auto req_copy = req;
573  HTTPEvent* ev = new HTTPEvent(eventBase, true, [req_copy, nStatus]{
574  evhttp_send_reply(req_copy, nStatus, nullptr, nullptr);
575  // Re-enable reading from the socket. This is the second part of the libevent
576  // workaround above.
577  if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02020001) {
578  evhttp_connection* conn = evhttp_request_get_connection(req_copy);
579  if (conn) {
580  bufferevent* bev = evhttp_connection_get_bufferevent(conn);
581  if (bev) {
582  bufferevent_enable(bev, EV_READ | EV_WRITE);
583  }
584  }
585  }
586  });
587  ev->trigger(nullptr);
588  replySent = true;
589  req = nullptr; // transferred back to main thread
590 }
591 
593 {
594  evhttp_connection* con = evhttp_request_get_connection(req);
595  CService peer;
596  if (con) {
597  // evhttp retains ownership over returned address string
598  const char* address = "";
599  uint16_t port = 0;
600  evhttp_connection_get_peer(con, (char**)&address, &port);
601  peer = LookupNumeric(address, port);
602  }
603  return peer;
604 }
605 
606 std::string HTTPRequest::GetURI() const
607 {
608  return evhttp_request_get_uri(req);
609 }
610 
612 {
613  switch (evhttp_request_get_command(req)) {
614  case EVHTTP_REQ_GET:
615  return GET;
616  break;
617  case EVHTTP_REQ_POST:
618  return POST;
619  break;
620  case EVHTTP_REQ_HEAD:
621  return HEAD;
622  break;
623  case EVHTTP_REQ_PUT:
624  return PUT;
625  break;
626  default:
627  return UNKNOWN;
628  break;
629  }
630 }
631 
632 void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
633 {
634  LogPrint(BCLog::HTTP, "Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
635  pathHandlers.push_back(HTTPPathHandler(prefix, exactMatch, handler));
636 }
637 
638 void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
639 {
640  std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
641  std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
642  for (; i != iend; ++i)
643  if (i->prefix == prefix && i->exactMatch == exactMatch)
644  break;
645  if (i != iend)
646  {
647  LogPrint(BCLog::HTTP, "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
648  pathHandlers.erase(i);
649  }
650 }
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:528
HTTPRequest::HEAD
@ HEAD
Definition: httpserver.h:70
HTTPRequest::GetRequestMethod
RequestMethod GetRequestMethod() const
Get request method.
Definition: httpserver.cpp:611
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:170
HTTP_SERVICE_UNAVAILABLE
@ HTTP_SERVICE_UNAVAILABLE
Definition: protocol.h:19
assert
assert(!tx.IsCoinBase())
HTTPEvent::~HTTPEvent
~HTTPEvent()
Definition: httpserver.cpp:494
HTTPWorkItem::path
std::string path
Definition: httpserver.cpp:56
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:679
UnregisterHTTPHandler
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
Definition: httpserver.cpp:638
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
g_work_queue
static std::unique_ptr< WorkQueue< HTTPClosure > > g_work_queue
Work queue for handling longer requests off the event loop thread.
Definition: httpserver.cpp:140
DEFAULT_HTTP_WORKQUEUE
static const int DEFAULT_HTTP_WORKQUEUE
Definition: httpserver.h:12
HTTPRequest::~HTTPRequest
~HTTPRequest()
Definition: httpserver.cpp:509
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:334
sync.h
handler
bool(* handler)(const std::any &context, HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:715
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:474
CNetAddr
Network address.
Definition: netaddress.h:118
chainparamsbase.h
ArgsManager::IsArgSet
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: system.cpp:496
HTTPRequest::GetPeer
CService GetPeer() const
Get CService (address:ip) for the origin of the http request.
Definition: httpserver.cpp:592
protocol.h
AnnotatedMixin< std::mutex >
WorkQueue::Enqueue
bool Enqueue(WorkItem *item)
Enqueue a work item.
Definition: httpserver.cpp:84
WorkQueue::GUARDED_BY
std::condition_variable cond GUARDED_BY(cs)
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:550
StartHTTPServer
void StartHTTPServer()
Start HTTP server.
Definition: httpserver.cpp:418
HTTPRequest::PUT
@ PUT
Definition: httpserver.h:71
SyscallSandboxPolicy::NET_HTTP_SERVER
@ NET_HTTP_SERVER
HTTPRequest::GetURI
std::string GetURI() const
Get requested URI.
Definition: httpserver.cpp:606
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:519
CNetAddr::IsBindAny
bool IsBindAny() const
Definition: netaddress.cpp:310
HTTPWorkItem::req
std::unique_ptr< HTTPRequest > req
Definition: httpserver.cpp:53
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:488
shutdown.h
WorkQueue::cs
Mutex cs
Definition: httpserver.cpp:67
prefix
const char * prefix
Definition: rest.cpp:714
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:38
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:64
HTTPRequest::POST
@ POST
Definition: httpserver.h:69
events.h
syscall_sandbox.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:41
HTTPWorkItem::operator()
void operator()() override
Definition: httpserver.cpp:48
Untranslated
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
Definition: translation.h:46
HTTPWorkItem::HTTPWorkItem
HTTPWorkItem(std::unique_ptr< HTTPRequest > _req, const std::string &_path, const HTTPRequestHandler &_func)
Definition: httpserver.cpp:44
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:401
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:416
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
WorkQueue::maxDepth
const size_t maxDepth
Definition: httpserver.cpp:71
HTTPRequest::ReadBody
std::string ReadBody()
Read request body.
Definition: httpserver.cpp:530
HTTPRequest::UNKNOWN
@ UNKNOWN
Definition: httpserver.h:67
HTTPRequest::HTTPRequest
HTTPRequest(struct evhttp_request *req, bool replySent=false)
Definition: httpserver.cpp:505
LogPrintf
#define LogPrintf(...)
Definition: logging.h:187
boundSockets
static std::vector< evhttp_bound_socket * > boundSockets
Bound listening sockets.
Definition: httpserver.cpp:144
CNetAddr::IsValid
bool IsValid() const
Definition: netaddress.cpp:451
CSubNet
Definition: netaddress.h:475
SetSyscallSandboxPolicy
void SetSyscallSandboxPolicy(SyscallSandboxPolicy syscall_policy)
Force the current thread (and threads created from the current thread) into a restricted-service oper...
Definition: syscall_sandbox.cpp:828
WorkQueue::Run
void Run()
Thread function.
Definition: httpserver.cpp:95
SAFE_CHARS_URI
@ SAFE_CHARS_URI
Chars allowed in URIs (RFC 3986)
Definition: strencodings.h:29
LogPrint
#define LogPrint(category,...)
Definition: logging.h:191
HTTPRequest::RequestMethod
RequestMethod
Definition: httpserver.h:66
gArgs
ArgsManager gArgs
Definition: system.cpp:85
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
SyscallSandboxPolicy::NET_HTTP_SERVER_WORKER
@ NET_HTTP_SERVER_WORKER
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:342
translation.h
HTTPEvent::trigger
void trigger(struct timeval *tv)
Trigger the event.
Definition: httpserver.cpp:498
BaseParams
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
Definition: chainparamsbase.cpp:33
HTTPWorkItem::func
HTTPRequestHandler func
Definition: httpserver.cpp:57
HTTPEvent
Event class.
Definition: httpserver.h:129
LOCK
#define LOCK(cs)
Definition: sync.h:226
InterruptHTTPServer
void InterruptHTTPServer()
Interrupt HTTP server threads.
Definition: httpserver.cpp:430
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:479
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:17
WorkQueue::WorkQueue
WorkQueue(size_t _maxDepth)
Definition: httpserver.cpp:74
CSubNet::IsValid
bool IsValid() const
Definition: netaddress.cpp:1219
HTTPBindAddresses
static bool HTTPBindAddresses(struct evhttp *http)
Bind HTTP server to specified addresses.
Definition: httpserver.cpp:292
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:230
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:487
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:106
StopHTTPServer
void StopHTTPServer()
Stop HTTP server.
Definition: httpserver.cpp:442
RegisterHTTPHandler
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
Definition: httpserver.cpp:632
g_thread_http
static std::thread g_thread_http
Definition: httpserver.cpp:415
ArgsManager::GetIntArg
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: system.cpp:596
ByteUnit::m
@ m
threadnames.h
HTTPRequest::WriteReply
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
Definition: httpserver.cpp:562
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
WAIT_LOCK
#define WAIT_LOCK(cs, name)
Definition: sync.h:231
HTTPPathHandler::handler
HTTPRequestHandler handler
Definition: httpserver.cpp:128
InitHTTPServer
bool InitHTTPServer()
Initialize HTTP server.
Definition: httpserver.cpp:350
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