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