BSHA3  0.17.99
P2P Blockchain, based on Bitcoin
httpserver.cpp
Go to the documentation of this file.
1 // Copyright (c) 2015-2018 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.h>
10 #include <utilstrencodings.h>
11 #include <netbase.h>
12 #include <rpc/protocol.h> // For HTTP status codes
13 #include <sync.h>
14 #include <ui_interface.h>
15 
16 #include <memory>
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <signal.h>
24 #include <future>
25 
26 #include <event2/thread.h>
27 #include <event2/buffer.h>
28 #include <event2/bufferevent.h>
29 #include <event2/util.h>
30 #include <event2/keyvalq_struct.h>
31 
32 #include <support/events.h>
33 
34 #ifdef EVENT__HAVE_NETINET_IN_H
35 #include <netinet/in.h>
36 #ifdef _XOPEN_SOURCE_EXTENDED
37 #include <arpa/inet.h>
38 #endif
39 #endif
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:
73  std::condition_variable cond;
74  std::deque<std::unique_ptr<WorkItem>> queue;
75  bool running;
76  size_t maxDepth;
77 
78 public:
79  explicit WorkQueue(size_t _maxDepth) : running(true),
80  maxDepth(_maxDepth)
81  {
82  }
86  {
87  }
89  bool Enqueue(WorkItem* item)
90  {
91  LOCK(cs);
92  if (queue.size() >= maxDepth) {
93  return false;
94  }
95  queue.emplace_back(std::unique_ptr<WorkItem>(item));
96  cond.notify_one();
97  return true;
98  }
100  void Run()
101  {
102  while (true) {
103  std::unique_ptr<WorkItem> i;
104  {
105  WAIT_LOCK(cs, lock);
106  while (running && queue.empty())
107  cond.wait(lock);
108  if (!running)
109  break;
110  i = std::move(queue.front());
111  queue.pop_front();
112  }
113  (*i)();
114  }
115  }
117  void Interrupt()
118  {
119  LOCK(cs);
120  running = false;
121  cond.notify_all();
122  }
123 };
124 
126 {
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 struct evhttp* eventHTTP = nullptr;
144 static std::vector<CSubNet> rpc_allow_subnets;
146 static WorkQueue<HTTPClosure>* workQueue = nullptr;
148 std::vector<HTTPPathHandler> pathHandlers;
150 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.c_str(), 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 
192 static std::string RequestMethodString(HTTPRequest::RequestMethod m)
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  LogPrint(BCLog::HTTP, "Received a %s request for %s from %s\n",
228  RequestMethodString(hreq->GetRequestMethod()), hreq->GetURI(), hreq->GetPeer().ToString());
229 
230  // Early address-based allow check
231  if (!ClientAllowed(hreq->GetPeer())) {
232  hreq->WriteReply(HTTP_FORBIDDEN);
233  return;
234  }
235 
236  // Early reject unknown HTTP methods
237  if (hreq->GetRequestMethod() == HTTPRequest::UNKNOWN) {
238  hreq->WriteReply(HTTP_BADMETHOD);
239  return;
240  }
241 
242  // Find registered handler for prefix
243  std::string strURI = hreq->GetURI();
244  std::string path;
245  std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin();
246  std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end();
247  for (; i != iend; ++i) {
248  bool match = false;
249  if (i->exactMatch)
250  match = (strURI == i->prefix);
251  else
252  match = (strURI.substr(0, i->prefix.size()) == i->prefix);
253  if (match) {
254  path = strURI.substr(i->prefix.size());
255  break;
256  }
257  }
258 
259  // Dispatch to worker thread
260  if (i != iend) {
261  std::unique_ptr<HTTPWorkItem> item(new HTTPWorkItem(std::move(hreq), path, i->handler));
262  assert(workQueue);
263  if (workQueue->Enqueue(item.get()))
264  item.release(); /* if true, queue took ownership */
265  else {
266  LogPrintf("WARNING: request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting\n");
267  item->req->WriteReply(HTTP_INTERNAL, "Work queue depth exceeded");
268  }
269  } else {
270  hreq->WriteReply(HTTP_NOTFOUND);
271  }
272 }
273 
275 static void http_reject_request_cb(struct evhttp_request* req, void*)
276 {
277  LogPrint(BCLog::HTTP, "Rejecting request while shutting down\n");
278  evhttp_send_error(req, HTTP_SERVUNAVAIL, nullptr);
279 }
280 
282 static bool ThreadHTTP(struct event_base* base)
283 {
284  RenameThread("bsha3-http");
285  LogPrint(BCLog::HTTP, "Entering http event loop\n");
286  event_base_dispatch(base);
287  // Event loop will be interrupted by InterruptHTTPServer()
288  LogPrint(BCLog::HTTP, "Exited http event loop\n");
289  return event_base_got_break(base) == 0;
290 }
291 
293 static bool HTTPBindAddresses(struct evhttp* http)
294 {
295  int defaultPort = gArgs.GetArg("-rpcport", BaseParams().RPCPort());
296  std::vector<std::pair<std::string, uint16_t> > endpoints;
297 
298  // Determine what addresses to bind to
299  if (!gArgs.IsArgSet("-rpcallowip")) { // Default to loopback if not allowing external IPs
300  endpoints.push_back(std::make_pair("::1", defaultPort));
301  endpoints.push_back(std::make_pair("127.0.0.1", defaultPort));
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  int port = defaultPort;
308  std::string host;
309  SplitHostPort(strRPCBind, port, host);
310  endpoints.push_back(std::make_pair(host, port));
311  }
312  } else { // No specific bind address specified, bind to any
313  endpoints.push_back(std::make_pair("::", defaultPort));
314  endpoints.push_back(std::make_pair("0.0.0.0", defaultPort));
315  }
316 
317  // Bind addresses
318  for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
319  LogPrint(BCLog::HTTP, "Binding RPC on address %s port %i\n", i->first, i->second);
320  evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? nullptr : i->first.c_str(), i->second);
321  if (bind_handle) {
322  boundSockets.push_back(bind_handle);
323  } else {
324  LogPrintf("Binding RPC on address %s port %i failed.\n", i->first, i->second);
325  }
326  }
327  return !boundSockets.empty();
328 }
329 
331 static void HTTPWorkQueueRun(WorkQueue<HTTPClosure>* queue)
332 {
333  RenameThread("bsha3-httpworker");
334  queue->Run();
335 }
336 
338 static void libevent_log_cb(int severity, const char *msg)
339 {
340 #ifndef EVENT_LOG_WARN
341 // EVENT_LOG_WARN was added in 2.0.19; but before then _EVENT_LOG_WARN existed.
342 # define EVENT_LOG_WARN _EVENT_LOG_WARN
343 #endif
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.
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.GetArg("-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.GetArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
392  LogPrintf("HTTP: creating work queue of depth %d\n", workQueueDepth);
393 
394  workQueue = new 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 std::thread threadHTTP;
416 std::future<bool> threadResult;
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  std::packaged_task<bool(event_base*)> task(ThreadHTTP);
425  threadResult = task.get_future();
426  threadHTTP = std::thread(std::move(task), eventBase);
427 
428  for (int i = 0; i < rpcThreads; i++) {
429  g_thread_http_workers.emplace_back(HTTPWorkQueueRun, workQueue);
430  }
431 }
432 
434 {
435  LogPrint(BCLog::HTTP, "Interrupting HTTP server\n");
436  if (eventHTTP) {
437  // Unlisten sockets
438  for (evhttp_bound_socket *socket : boundSockets) {
439  evhttp_del_accept_socket(eventHTTP, socket);
440  }
441  // Reject requests on current connections
442  evhttp_set_gencb(eventHTTP, http_reject_request_cb, nullptr);
443  }
444  if (workQueue)
445  workQueue->Interrupt();
446 }
447 
449 {
450  LogPrint(BCLog::HTTP, "Stopping HTTP server\n");
451  if (workQueue) {
452  LogPrint(BCLog::HTTP, "Waiting for HTTP worker threads to exit\n");
453  for (auto& thread: g_thread_http_workers) {
454  thread.join();
455  }
456  g_thread_http_workers.clear();
457  delete workQueue;
458  workQueue = nullptr;
459  }
460  if (eventBase) {
461  LogPrint(BCLog::HTTP, "Waiting for HTTP event thread to exit\n");
462  // Exit the event loop as soon as there are no active events.
463  event_base_loopexit(eventBase, nullptr);
464  // Give event loop a few seconds to exit (to send back last RPC responses), then break it
465  // Before this was solved with event_base_loopexit, but that didn't work as expected in
466  // at least libevent 2.0.21 and always introduced a delay. In libevent
467  // master that appears to be solved, so in the future that solution
468  // could be used again (if desirable).
469  // (see discussion in https://github.com/bitcoin/bitcoin/pull/6990)
470  if (threadResult.valid() && threadResult.wait_for(std::chrono::milliseconds(2000)) == std::future_status::timeout) {
471  LogPrintf("HTTP event loop did not exit within allotted time, sending loopbreak\n");
472  event_base_loopbreak(eventBase);
473  }
474  threadHTTP.join();
475  }
476  if (eventHTTP) {
477  evhttp_free(eventHTTP);
478  eventHTTP = nullptr;
479  }
480  if (eventBase) {
481  event_base_free(eventBase);
482  eventBase = nullptr;
483  }
484  LogPrint(BCLog::HTTP, "Stopped HTTP server\n");
485 }
486 
487 struct event_base* EventBase()
488 {
489  return eventBase;
490 }
491 
492 static void httpevent_callback_fn(evutil_socket_t, short, void* data)
493 {
494  // Static handler: simply call inner handler
495  HTTPEvent *self = static_cast<HTTPEvent*>(data);
496  self->handler();
497  if (self->deleteWhenTriggered)
498  delete self;
499 }
500 
501 HTTPEvent::HTTPEvent(struct event_base* base, bool _deleteWhenTriggered, const std::function<void()>& _handler):
502  deleteWhenTriggered(_deleteWhenTriggered), handler(_handler)
503 {
504  ev = event_new(base, -1, 0, httpevent_callback_fn, this);
505  assert(ev);
506 }
508 {
509  event_free(ev);
510 }
511 void HTTPEvent::trigger(struct timeval* tv)
512 {
513  if (tv == nullptr)
514  event_active(ev, 0, 0); // immediately trigger event in main thread
515  else
516  evtimer_add(ev, tv); // trigger after timeval passed
517 }
518 HTTPRequest::HTTPRequest(struct evhttp_request* _req) : req(_req),
519  replySent(false)
520 {
521 }
523 {
524  if (!replySent) {
525  // Keep track of whether reply was sent to avoid request leaks
526  LogPrintf("%s: Unhandled request\n", __func__);
527  WriteReply(HTTP_INTERNAL, "Unhandled request");
528  }
529  // evhttpd cleans up the request, as long as a reply was sent.
530 }
531 
532 std::pair<bool, std::string> HTTPRequest::GetHeader(const std::string& hdr) const
533 {
534  const struct evkeyvalq* headers = evhttp_request_get_input_headers(req);
535  assert(headers);
536  const char* val = evhttp_find_header(headers, hdr.c_str());
537  if (val)
538  return std::make_pair(true, val);
539  else
540  return std::make_pair(false, "");
541 }
542 
544 {
545  struct evbuffer* buf = evhttp_request_get_input_buffer(req);
546  if (!buf)
547  return "";
548  size_t size = evbuffer_get_length(buf);
555  const char* data = (const char*)evbuffer_pullup(buf, size);
556  if (!data) // returns nullptr in case of empty buffer
557  return "";
558  std::string rv(data, size);
559  evbuffer_drain(buf, size);
560  return rv;
561 }
562 
563 void HTTPRequest::WriteHeader(const std::string& hdr, const std::string& value)
564 {
565  struct evkeyvalq* headers = evhttp_request_get_output_headers(req);
566  assert(headers);
567  evhttp_add_header(headers, hdr.c_str(), value.c_str());
568 }
569 
575 void HTTPRequest::WriteReply(int nStatus, const std::string& strReply)
576 {
577  assert(!replySent && req);
578  // Send event to main http thread to send reply message
579  struct evbuffer* evb = evhttp_request_get_output_buffer(req);
580  assert(evb);
581  evbuffer_add(evb, strReply.data(), strReply.size());
582  auto req_copy = req;
583  HTTPEvent* ev = new HTTPEvent(eventBase, true, [req_copy, nStatus]{
584  evhttp_send_reply(req_copy, nStatus, nullptr, nullptr);
585  // Re-enable reading from the socket. This is the second part of the libevent
586  // workaround above.
587  if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02020001) {
588  evhttp_connection* conn = evhttp_request_get_connection(req_copy);
589  if (conn) {
590  bufferevent* bev = evhttp_connection_get_bufferevent(conn);
591  if (bev) {
592  bufferevent_enable(bev, EV_READ | EV_WRITE);
593  }
594  }
595  }
596  });
597  ev->trigger(nullptr);
598  replySent = true;
599  req = nullptr; // transferred back to main thread
600 }
601 
603 {
604  evhttp_connection* con = evhttp_request_get_connection(req);
605  CService peer;
606  if (con) {
607  // evhttp retains ownership over returned address string
608  const char* address = "";
609  uint16_t port = 0;
610  evhttp_connection_get_peer(con, (char**)&address, &port);
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 }
661 
662 std::string urlDecode(const std::string &urlEncoded) {
663  std::string res;
664  if (!urlEncoded.empty()) {
665  char *decoded = evhttp_uridecode(urlEncoded.c_str(), false, nullptr);
666  if (decoded) {
667  res = std::string(decoded);
668  free(decoded);
669  }
670  }
671  return res;
672 }
bool(* handler)(HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:582
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
Definition: util.cpp:502
raii_event_base obtain_event_base()
Definition: events.h:30
std::vector< evhttp_bound_socket * > boundSockets
Bound listening sockets.
Definition: httpserver.cpp:150
HTTPWorkItem(std::unique_ptr< HTTPRequest > _req, const std::string &_path, const HTTPRequestHandler &_func)
Definition: httpserver.cpp:48
HTTPRequest(struct evhttp_request *req)
Definition: httpserver.cpp:518
raii_evhttp obtain_evhttp(struct event_base *base)
Definition: events.h:41
#define strprintf
Definition: tinyformat.h:1066
std::vector< HTTPPathHandler > pathHandlers
Handlers for (sub)paths.
Definition: httpserver.cpp:148
CService LookupNumeric(const char *pszName, int portDefault)
Definition: netbase.cpp:168
Event class.
Definition: httpserver.h:130
const char * prefix
Definition: rest.cpp:581
std::string urlDecode(const std::string &urlEncoded)
Definition: httpserver.cpp:662
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
size_t maxDepth
Definition: httpserver.cpp:76
std::string path
Definition: httpserver.cpp:60
struct evhttp_request * req
Definition: httpserver.h:60
std::deque< std::unique_ptr< WorkItem > > queue
Definition: httpserver.cpp:74
std::thread threadHTTP
Definition: httpserver.cpp:415
HTTP request work item.
Definition: httpserver.cpp:45
void InterruptHTTPServer()
Interrupt HTTP server threads.
Definition: httpserver.cpp:433
void RenameThread(const char *name)
Definition: util.cpp:1168
bool Enqueue(WorkItem *item)
Enqueue a work item.
Definition: httpserver.cpp:89
Event handler closure.
Definition: httpserver.h:121
struct event * ev
Definition: httpserver.h:148
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
Definition: httpserver.cpp:642
bool IsValid() const
Definition: netaddress.cpp:188
Mutex cs
Mutex protects entire object.
Definition: httpserver.cpp:72
void Run()
Thread function.
Definition: httpserver.cpp:100
HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler)
Definition: httpserver.cpp:128
bool InitHTTPServer()
Initialize HTTP server.
Definition: httpserver.cpp:350
void StopHTTPServer()
Stop HTTP server.
Definition: httpserver.cpp:448
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
Definition: httpserver.cpp:575
#define LOCK(cs)
Definition: sync.h:181
HTTPEvent(struct event_base *base, bool deleteWhenTriggered, const std::function< void()> &handler)
Create a new event.
Definition: httpserver.cpp:501
RequestMethod GetRequestMethod() const
Get request method.
Definition: httpserver.cpp:621
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:142
std::condition_variable cond
Definition: httpserver.cpp:73
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
Definition: httpserver.cpp:648
HTTPRequestHandler func
Definition: httpserver.cpp:61
void DisableCategory(LogFlags flag)
Definition: logging.cpp:68
#define WAIT_LOCK(cs, name)
Definition: sync.h:186
std::future< bool > threadResult
Definition: httpserver.cpp:416
bool WillLogCategory(LogFlags category) const
Definition: logging.cpp:81
struct event_base * EventBase()
Return evhttp event base.
Definition: httpserver.cpp:487
bool LookupSubNet(const char *pszName, CSubNet &ret)
Definition: netbase.cpp:614
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
Definition: netaddress.h:32
bool IsValid() const
Definition: netaddress.cpp:699
Simple work queue for distributing work over multiple threads.
Definition: httpserver.cpp:68
ArgsManager gArgs
Definition: util.cpp:88
std::string ToString() const
Definition: netaddress.cpp:661
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)
#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:563
void trigger(struct timeval *tv)
Trigger the event.
Definition: httpserver.cpp:511
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: util.cpp:526
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:532
std::function< void()> handler
Definition: httpserver.h:146
bool running
Definition: httpserver.cpp:75
std::function< bool(HTTPRequest *req, const std::string &)> HTTPRequestHandler
Handler for requests to a certain HTTP path.
Definition: httpserver.h:40
CService GetPeer() const
Get CService (address:ip) for the origin of the http request.
Definition: httpserver.cpp:602
void operator()() override
Definition: httpserver.cpp:52
std::string ReadBody()
Read request body.
Definition: httpserver.cpp:543
void StartHTTPServer()
Start HTTP server.
Definition: httpserver.cpp:419
WorkQueue(size_t _maxDepth)
Definition: httpserver.cpp:79
In-flight HTTP request.
Definition: httpserver.h:57
std::unique_ptr< HTTPRequest > req
Definition: httpserver.cpp:57
CClientUIInterface uiInterface
bool LookupHost(const char *pszName, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
Definition: netbase.cpp:118
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: util.cpp:483
HTTPRequestHandler handler
Definition: httpserver.cpp:134
bool replySent
Definition: httpserver.h:61
struct evhttp * eventHTTP
HTTP server.
Definition: httpserver.cpp:142
BCLog::Logger *const g_logger
NOTE: the logger instances is leaked on exit.
Definition: logging.cpp:24
std::string GetURI() const
Get requested URI.
Definition: httpserver.cpp:616
bool UpdateHTTPServerLogging(bool enable)
Change logging level for libevent.
Definition: httpserver.cpp:401
~WorkQueue()
Precondition: worker threads have all stopped (they have been joined).
Definition: httpserver.cpp:85
void Interrupt()
Interrupt and exit loops.
Definition: httpserver.cpp:117