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