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