PRCYCoin  2.0.0.7rc1
P2P Digital Currency
httpserver.cpp
Go to the documentation of this file.
1 // Copyright (c) 2015 The Bitcoin Core developers
2 // Copyright (c) 2015-2018 The PIVX developers
3 // Copyright (c) 2018-2020 The DAPS Project developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #include "httpserver.h"
8 
9 #include "chainparamsbase.h"
10 #include "compat.h"
11 #include "util.h"
12 #include "netbase.h"
13 #include "rpc/protocol.h" // For HTTP status codes
14 #include "sync.h"
15 #include "guiinterface.h"
16 
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 <deque>
27 #include <event2/event.h>
28 #include <event2/http.h>
29 #include <event2/thread.h>
30 #include <event2/buffer.h>
31 #include <event2/bufferevent.h>
32 #include <event2/util.h>
33 #include <event2/keyvalq_struct.h>
34 
35 #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 : public HTTPClosure
47 {
48 public:
49  HTTPWorkItem(HTTPRequest* req, const std::string &path, const HTTPRequestHandler& func):
50  req(req), path(path), func(func)
51  {
52  }
53  void operator()()
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:
73  std::mutex cs;
74  std::condition_variable cond;
75  /* XXX in C++11 we can use std::unique_ptr here and avoid manual cleanup */
76  std::deque<WorkItem*> queue;
77  bool running;
78  size_t maxDepth;
80 
83  {
84  public:
87  {
88  std::lock_guard<std::mutex> lock(wq.cs);
89  wq.numThreads += 1;
90  }
92  {
93  std::lock_guard<std::mutex> lock(wq.cs);
94  wq.numThreads -= 1;
95  wq.cond.notify_all();
96  }
97  };
98 
99 public:
100  WorkQueue(size_t maxDepth) : running(true),
102  numThreads(0)
103  {
104  }
105  /*( Precondition: worker threads have all stopped
106  * (call WaitExit)
107  */
109  {
110  while (!queue.empty()) {
111  delete queue.front();
112  queue.pop_front();
113  }
114  }
116  bool Enqueue(WorkItem* item)
117  {
118  std::unique_lock<std::mutex> lock(cs);
119  if (queue.size() >= maxDepth) {
120  return false;
121  }
122  queue.push_back(item);
123  cond.notify_one();
124  return true;
125  }
127  void Run()
128  {
129  ThreadCounter count(*this);
130  while (running) {
131  WorkItem* i = 0;
132  {
133  std::unique_lock<std::mutex> lock(cs);
134  while (running && queue.empty())
135  cond.wait(lock);
136  if (!running)
137  break;
138  i = queue.front();
139  queue.pop_front();
140  }
141  (*i)();
142  delete i;
143  }
144  }
146  void Interrupt()
147  {
148  std::unique_lock<std::mutex> lock(cs);
149  running = false;
150  cond.notify_all();
151  }
153  void WaitExit()
154  {
155  std::unique_lock<std::mutex> lock(cs);
156  while (numThreads > 0)
157  cond.wait(lock);
158  }
159 
161  size_t Depth()
162  {
163  std::unique_lock<std::mutex> lock(cs);
164  return queue.size();
165  }
166 };
167 
169 {
173  {
174  }
175  std::string prefix;
178 };
179 
182 static struct event_base* eventBase = 0;
185 struct evhttp* eventHTTP = 0;
187 static std::vector<CSubNet> rpc_allow_subnets;
189 static WorkQueue<HTTPClosure>* workQueue = 0;
191 std::vector<HTTPPathHandler> pathHandlers;
192 std::vector<evhttp_bound_socket *> boundSockets;
193 
195 static bool ClientAllowed(const CNetAddr& netaddr)
196 {
197  if (!netaddr.IsValid())
198  return false;
199  for (const CSubNet& subnet : rpc_allow_subnets)
200  if (subnet.Match(netaddr))
201  return true;
202  return false;
203 }
204 
206 static bool InitHTTPAllowList()
207 {
208  rpc_allow_subnets.clear();
209  CNetAddr localv4;
210  CNetAddr localv6;
211  LookupHost("127.0.0.1", localv4, false);
212  LookupHost("::1", localv6, false);
213  rpc_allow_subnets.push_back(CSubNet(localv4, 8)); // always allow IPv4 local subnet
214  rpc_allow_subnets.push_back(CSubNet(localv6)); // always allow IPv6 localhost
215  if (mapMultiArgs.count("-rpcallowip")) {
216  const std::vector<std::string>& vAllow = mapMultiArgs["-rpcallowip"];
217  for (std::string strAllow : vAllow) {
218  CSubNet subnet;
219  LookupSubNet(strAllow.c_str(), subnet);
220  if (!subnet.IsValid()) {
222  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),
224  return false;
225  }
226  rpc_allow_subnets.push_back(subnet);
227  }
228  }
229  std::string strAllowed;
230  for (const CSubNet& subnet : rpc_allow_subnets)
231  strAllowed += subnet.ToString() + " ";
232  LogPrint(BCLog::HTTP, "Allowing HTTP connections from: %s\n", strAllowed);
233  return true;
234 }
235 
237 static std::string RequestMethodString(HTTPRequest::RequestMethod m)
238 {
239  switch (m) {
240  case HTTPRequest::GET:
241  return "GET";
242  break;
243  case HTTPRequest::POST:
244  return "POST";
245  break;
246  case HTTPRequest::HEAD:
247  return "HEAD";
248  break;
249  case HTTPRequest::PUT:
250  return "PUT";
251  break;
252  default:
253  return "unknown";
254  }
255 }
256 
258 static void http_request_cb(struct evhttp_request* req, void* arg)
259 {
260  // Disable reading to work around a libevent bug, fixed in 2.2.0.
261  if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02020001) {
262  evhttp_connection* conn = evhttp_request_get_connection(req);
263  if (conn) {
264  bufferevent* bev = evhttp_connection_get_bufferevent(conn);
265  if (bev) {
266  bufferevent_disable(bev, EV_READ);
267  }
268  }
269  }
270  std::unique_ptr<HTTPRequest> hreq(new HTTPRequest(req));
271 
272  LogPrint(BCLog::HTTP, "Received a %s request for %s from %s\n",
273  RequestMethodString(hreq->GetRequestMethod()), hreq->GetURI(), hreq->GetPeer().ToString());
274 
275  // Early address-based allow check
276  if (!ClientAllowed(hreq->GetPeer())) {
277  hreq->WriteReply(HTTP_FORBIDDEN);
278  return;
279  }
280 
281  // Early reject unknown HTTP methods
282  if (hreq->GetRequestMethod() == HTTPRequest::UNKNOWN) {
283  hreq->WriteReply(HTTP_BADMETHOD);
284  return;
285  }
286 
287  // Find registered handler for prefix
288  std::string strURI = hreq->GetURI();
289  std::string path;
290  std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin();
291  std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end();
292  for (; i != iend; ++i) {
293  bool match = false;
294  if (i->exactMatch)
295  match = (strURI == i->prefix);
296  else
297  match = (strURI.substr(0, i->prefix.size()) == i->prefix);
298  if (match) {
299  path = strURI.substr(i->prefix.size());
300  break;
301  }
302  }
303 
304  // Dispatch to worker thread
305  if (i != iend) {
306  std::unique_ptr<HTTPWorkItem> item(new HTTPWorkItem(hreq.release(), path, i->handler));
307  assert(workQueue);
308  if (workQueue->Enqueue(item.get()))
309  item.release(); /* if true, queue took ownership */
310  else
311  item->req->WriteReply(HTTP_INTERNAL, "Work queue depth exceeded");
312  } else {
313  hreq->WriteReply(HTTP_NOTFOUND);
314  }
315 }
316 
318 static void http_reject_request_cb(struct evhttp_request* req, void*)
319 {
320  LogPrint(BCLog::HTTP, "Rejecting request while shutting down\n");
321  evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
322 }
324 static bool ThreadHTTP(struct event_base* base, struct evhttp* http)
325 {
326  util::ThreadRename("bitcoin-http");
327  LogPrint(BCLog::HTTP, "Entering http event loop\n");
328  event_base_dispatch(base);
329  // Event loop will be interrupted by InterruptHTTPServer()
330  LogPrint(BCLog::HTTP, "Exited http event loop\n");
331  return event_base_got_break(base) == 0;
332 }
333 
335 static bool HTTPBindAddresses(struct evhttp* http)
336 {
337  int defaultPort = GetArg("-rpcport", BaseParams().RPCPort());
338  std::vector<std::pair<std::string, uint16_t> > endpoints;
339 
340  // Determine what addresses to bind to
341  if (!mapArgs.count("-rpcallowip")) { // Default to loopback if not allowing external IPs
342  endpoints.push_back(std::make_pair("::1", defaultPort));
343  endpoints.push_back(std::make_pair("127.0.0.1", defaultPort));
344  if (mapArgs.count("-rpcbind")) {
345  LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
346  }
347  } else if (mapArgs.count("-rpcbind")) { // Specific bind address
348  const std::vector<std::string>& vbind = mapMultiArgs["-rpcbind"];
349  for (std::vector<std::string>::const_iterator i = vbind.begin(); i != vbind.end(); ++i) {
350  int port = defaultPort;
351  std::string host;
352  SplitHostPort(*i, port, host);
353  endpoints.push_back(std::make_pair(host, port));
354  }
355  } else { // No specific bind address specified, bind to any
356  endpoints.push_back(std::make_pair("::", defaultPort));
357  endpoints.push_back(std::make_pair("0.0.0.0", defaultPort));
358  }
359 
360  // Bind addresses
361  for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
362  LogPrint(BCLog::HTTP, "Binding RPC on address %s port %i\n", i->first, i->second);
363  evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? NULL : i->first.c_str(), i->second);
364  if (bind_handle) {
365  boundSockets.push_back(bind_handle);
366  } else {
367  LogPrintf("Binding RPC on address %s port %i failed.\n", i->first, i->second);
368  }
369  }
370  return !boundSockets.empty();
371 }
372 
374 static void HTTPWorkQueueRun(WorkQueue<HTTPClosure>* queue)
375 {
376  util::ThreadRename("bitcoin-httpworker");
377  queue->Run();
378 }
379 
381 static void libevent_log_cb(int severity, const char *msg)
382 {
383 #ifndef EVENT_LOG_WARN
384 // EVENT_LOG_WARN was added in 2.0.19; but before then _EVENT_LOG_WARN existed.
385 # define EVENT_LOG_WARN _EVENT_LOG_WARN
386 #endif
387  if (severity >= EVENT_LOG_WARN) // Log warn messages and higher without debug category
388  LogPrintf("libevent: %s\n", msg);
389  else
390  LogPrint(BCLog::LIBEVENT, "libevent: %s\n", msg);
391 }
392 
394 {
395  struct evhttp* http = 0;
396  struct event_base* base = 0;
397 
398  if (!InitHTTPAllowList())
399  return false;
400 
401  if (GetBoolArg("-rpcssl", false)) {
403  "SSL mode for RPC (-rpcssl) is no longer supported.",
405  return false;
406  }
407 
408  // Redirect libevent's logging to our own log
409  event_set_log_callback(&libevent_log_cb);
410  // Update libevent's log handling. Returns false if our version of
411  // libevent doesn't support debug logging, in which case we should
412  // clear the BCLog::LIBEVENT flag.
415  }
416 
417 #ifdef WIN32
418  evthread_use_windows_threads();
419 #else
420  evthread_use_pthreads();
421 #endif
422 
423  base = event_base_new(); // XXX RAII
424  if (!base) {
425  LogPrintf("Couldn't create an event_base: exiting\n");
426  return false;
427  }
428 
429  /* Create a new evhttp object to handle requests. */
430  http = evhttp_new(base); // XXX RAII
431  if (!http) {
432  LogPrintf("couldn't create evhttp. Exiting.\n");
433  event_base_free(base);
434  return false;
435  }
436 
437  evhttp_set_timeout(http, GetArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
438  evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
439  evhttp_set_max_body_size(http, MAX_SIZE);
440  evhttp_set_gencb(http, http_request_cb, NULL);
441 
442  if (!HTTPBindAddresses(http)) {
443  LogPrintf("Unable to bind any endpoint for RPC server\n");
444  evhttp_free(http);
445  event_base_free(base);
446  return false;
447  }
448 
449  LogPrint(BCLog::HTTP, "Initialized HTTP server\n");
450  int workQueueDepth = std::max((long)GetArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
451  LogPrintf("HTTP: creating work queue of depth %d\n", workQueueDepth);
452 
453  workQueue = new WorkQueue<HTTPClosure>(workQueueDepth);
454  eventBase = base;
455  eventHTTP = http;
456  return true;
457 }
458 
459 bool UpdateHTTPServerLogging(bool enable) {
460 #if LIBEVENT_VERSION_NUMBER >= 0x02010100
461  if (enable) {
462  event_enable_debug_logging(EVENT_DBG_ALL);
463  } else {
464  event_enable_debug_logging(EVENT_DBG_NONE);
465  }
466  return true;
467 #else
468  // Can't update libevent logging if version < 02010100
469  return false;
470 #endif
471 }
472 
473 std::thread threadHTTP;
474 std::future<bool> threadResult;
475 
477 {
478  LogPrint(BCLog::HTTP, "Starting HTTP server\n");
479  int rpcThreads = std::max((long)GetArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L);
480  LogPrintf("HTTP: starting %d worker threads\n", rpcThreads);
481  std::packaged_task<bool(event_base*, evhttp*)> task(ThreadHTTP);
482  threadResult = task.get_future();
483  threadHTTP = std::thread(std::move(task), eventBase, eventHTTP);
484 
485  for (int i = 0; i < rpcThreads; i++) {
486  std::thread rpc_worker(HTTPWorkQueueRun, workQueue);
487  rpc_worker.detach();
488  }
489  return true;
490 }
491 
493 {
494  LogPrint(BCLog::HTTP, "Interrupting HTTP server\n");
495  if (eventHTTP) {
496  for (evhttp_bound_socket *socket : boundSockets) {
497  evhttp_del_accept_socket(eventHTTP, socket);
498  }
499  evhttp_set_gencb(eventHTTP, http_reject_request_cb, NULL);
500  }
501  if (workQueue)
502  workQueue->Interrupt();
503 }
504 
506 {
507  LogPrint(BCLog::HTTP, "Stopping HTTP server\n");
508  if (workQueue) {
509  LogPrint(BCLog::HTTP, "Waiting for HTTP worker threads to exit\n");
510  workQueue->WaitExit();
511  delete workQueue;
512  }
513  MilliSleep(500); // Avoid race condition while the last HTTP-thread is exiting
514  if (eventBase) {
515  LogPrint(BCLog::HTTP, "Waiting for HTTP event thread to exit\n");
516  // Give event loop a few seconds to exit (to send back last RPC responses), then break it
517  // Before this was solved with event_base_loopexit, but that didn't work as expected in
518  // at least libevent 2.0.21 and always introduced a delay. In libevent
519  // master that appears to be solved, so in the future that solution
520  // could be used again (if desirable).
521  // (see discussion in https://github.com/bitcoin/bitcoin/pull/6990)
522  if (threadResult.valid() && threadResult.wait_for(std::chrono::milliseconds(2000)) == std::future_status::timeout) {
523  LogPrintf("HTTP event loop did not exit within allotted time, sending loopbreak\n");
524  event_base_loopbreak(eventBase);
525 
526  }
527  threadHTTP.join();
528  }
529  if (eventHTTP) {
530  evhttp_free(eventHTTP);
531  eventHTTP = 0;
532  }
533  if (eventBase) {
534  event_base_free(eventBase);
535  eventBase = 0;
536  }
537  LogPrint(BCLog::HTTP, "Stopped HTTP server\n");
538 }
539 
540 struct event_base* EventBase()
541 {
542  return eventBase;
543 }
544 
545 static void httpevent_callback_fn(evutil_socket_t, short, void* data)
546 {
547  // Static handler: simply call inner handler
548  HTTPEvent *self = ((HTTPEvent*)data);
549  self->handler();
550  if (self->deleteWhenTriggered)
551  delete self;
552 }
553 
554 HTTPEvent::HTTPEvent(struct event_base* base, bool deleteWhenTriggered, const std::function<void(void)>& handler):
555  deleteWhenTriggered(deleteWhenTriggered), handler(handler)
556 {
557  ev = event_new(base, -1, 0, httpevent_callback_fn, this);
558  assert(ev);
559 }
561 {
562  event_free(ev);
563 }
564 void HTTPEvent::trigger(struct timeval* tv)
565 {
566  if (tv == NULL)
567  event_active(ev, 0, 0); // immediately trigger event in main thread
568  else
569  evtimer_add(ev, tv); // trigger after timeval passed
570 }
571 HTTPRequest::HTTPRequest(struct evhttp_request* req) : req(req),
572  replySent(false)
573 {
574 }
576 {
577  if (!replySent) {
578  // Keep track of whether reply was sent to avoid request leaks
579  LogPrintf("%s: Unhandled request\n", __func__);
580  WriteReply(HTTP_INTERNAL, "Unhandled request");
581  }
582  // evhttpd cleans up the request, as long as a reply was sent.
583 }
584 
585 std::pair<bool, std::string> HTTPRequest::GetHeader(const std::string& hdr)
586 {
587  const struct evkeyvalq* headers = evhttp_request_get_input_headers(req);
588  assert(headers);
589  const char* val = evhttp_find_header(headers, hdr.c_str());
590  if (val)
591  return std::make_pair(true, val);
592  else
593  return std::make_pair(false, "");
594 }
595 
597 {
598  struct evbuffer* buf = evhttp_request_get_input_buffer(req);
599  if (!buf)
600  return "";
601  size_t size = evbuffer_get_length(buf);
608  const char* data = (const char*)evbuffer_pullup(buf, size);
609  if (!data) // returns NULL in case of empty buffer
610  return "";
611  std::string rv(data, size);
612  evbuffer_drain(buf, size);
613  return rv;
614 }
615 
616 void HTTPRequest::WriteHeader(const std::string& hdr, const std::string& value)
617 {
618  struct evkeyvalq* headers = evhttp_request_get_output_headers(req);
619  assert(headers);
620  evhttp_add_header(headers, hdr.c_str(), value.c_str());
621 }
622 
628 void HTTPRequest::WriteReply(int nStatus, const std::string& strReply)
629 {
630  assert(!replySent && req);
631  // Send event to main http thread to send reply message
632  struct evbuffer* evb = evhttp_request_get_output_buffer(req);
633  assert(evb);
634  evbuffer_add(evb, strReply.data(), strReply.size());
635  auto req_copy = req;
636  HTTPEvent* ev = new HTTPEvent(eventBase, true, [req_copy, nStatus]{
637  evhttp_send_reply(req_copy, nStatus, nullptr, nullptr);
638  // Re-enable reading from the socket. This is the second part of the libevent
639  // workaround above.
640  if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02020001) {
641  evhttp_connection* conn = evhttp_request_get_connection(req_copy);
642  if (conn) {
643  bufferevent* bev = evhttp_connection_get_bufferevent(conn);
644  if (bev) {
645  bufferevent_enable(bev, EV_READ | EV_WRITE);
646  }
647  }
648  }
649  });
650  ev->trigger(0);
651  replySent = true;
652  req = 0; // transferred back to main thread
653 }
654 
656 {
657  evhttp_connection* con = evhttp_request_get_connection(req);
658  CService peer;
659  if (con) {
660  // evhttp retains ownership over returned address string
661  const char* address = "";
662  uint16_t port = 0;
663  evhttp_connection_get_peer(con, (char**)&address, &port);
664  peer = LookupNumeric(address, port);
665  }
666  return peer;
667 }
668 
669 std::string HTTPRequest::GetURI()
670 {
671  return evhttp_request_get_uri(req);
672 }
673 
675 {
676  switch (evhttp_request_get_command(req)) {
677  case EVHTTP_REQ_GET:
678  return GET;
679  break;
680  case EVHTTP_REQ_POST:
681  return POST;
682  break;
683  case EVHTTP_REQ_HEAD:
684  return HEAD;
685  break;
686  case EVHTTP_REQ_PUT:
687  return PUT;
688  break;
689  default:
690  return UNKNOWN;
691  break;
692  }
693 }
694 
695 void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
696 {
697  LogPrint(BCLog::HTTP, "Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
698  pathHandlers.push_back(HTTPPathHandler(prefix, exactMatch, handler));
699 }
700 
701 void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
702 {
703  std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
704  std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
705  for (; i != iend; ++i)
706  if (i->prefix == prefix && i->exactMatch == exactMatch)
707  break;
708  if (i != iend)
709  {
710  LogPrint(BCLog::HTTP, "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
711  pathHandlers.erase(i);
712  }
713 }
HTTPWorkItem::HTTPWorkItem
HTTPWorkItem(HTTPRequest *req, const std::string &path, const HTTPRequestHandler &func)
Definition: httpserver.cpp:49
HTTPPathHandler::HTTPPathHandler
HTTPPathHandler()
Definition: httpserver.cpp:170
CService
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:133
HTTPRequest::HEAD
@ HEAD
Definition: httpserver.h:71
LookupSubNet
bool LookupSubNet(const char *pszName, CSubNet &ret)
Definition: netbase.cpp:667
SplitHostPort
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)
Definition: netbase.cpp:74
HTTPRequest::GetPeer
CService GetPeer()
Get CService (address:ip) for the origin of the http request.
Definition: httpserver.cpp:655
WorkQueue::WorkQueue
WorkQueue(size_t maxDepth)
Definition: httpserver.cpp:100
HTTPEvent::~HTTPEvent
~HTTPEvent()
Definition: httpserver.cpp:560
HTTPWorkItem::path
std::string path
Definition: httpserver.cpp:61
BCLog::HTTP
@ HTTP
Definition: logging.h:43
UnregisterHTTPHandler
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
Definition: httpserver.cpp:701
WorkQueue::Depth
size_t Depth()
Return current depth of queue.
Definition: httpserver.cpp:161
BCLog::Logger::WillLogCategory
bool WillLogCategory(LogFlags category) const
Definition: logging.cpp:84
HTTPRequest::~HTTPRequest
~HTTPRequest()
Definition: httpserver.cpp:575
sync.h
threadResult
std::future< bool > threadResult
Definition: httpserver.cpp:474
uiInterface
CClientUIInterface uiInterface
Definition: init.cpp:101
EventBase
struct event_base * EventBase()
Return evhttp event base.
Definition: httpserver.cpp:540
CNetAddr
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
Definition: netaddress.h:30
mapArgs
std::map< std::string, std::string > mapArgs
Definition: util.cpp:111
chainparamsbase.h
EVENT_LOG_WARN
#define EVENT_LOG_WARN
WorkQueue::ThreadCounter::ThreadCounter
ThreadCounter(WorkQueue &w)
Definition: httpserver.cpp:86
g_logger
BCLog::Logger *const g_logger
NOTE: the logger instances is leaked on exit.
Definition: logging.cpp:28
WorkQueue::WaitExit
void WaitExit()
Wait for worker threads to exit.
Definition: httpserver.cpp:153
protocol.h
WorkQueue::Enqueue
bool Enqueue(WorkItem *item)
Enqueue a work item.
Definition: httpserver.cpp:116
HTTPPathHandler::exactMatch
bool exactMatch
Definition: httpserver.cpp:176
guiinterface.h
HTTPRequest::WriteHeader
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
Definition: httpserver.cpp:616
HTTPRequest::PUT
@ PUT
Definition: httpserver.h:72
WorkQueue::maxDepth
size_t maxDepth
Definition: httpserver.cpp:78
WorkQueue::queue
std::deque< WorkItem * > queue
Definition: httpserver.cpp:76
CSubNet::Match
bool Match(const CNetAddr &addr) const
Definition: netaddress.cpp:634
HTTPWorkItem::req
std::unique_ptr< HTTPRequest > req
Definition: httpserver.cpp:58
HTTPEvent::ev
struct event * ev
Definition: httpserver.h:148
WorkQueue::ThreadCounter
RAII object to keep track of number of running worker threads.
Definition: httpserver.cpp:82
prefix
const char * prefix
Definition: rest.cpp:588
HTTPRequest::replySent
bool replySent
Definition: httpserver.h:61
WorkQueue
Simple work queue for distributing work over multiple threads.
Definition: httpserver.cpp:69
HTTPRequest::POST
@ POST
Definition: httpserver.h:70
eventHTTP
struct evhttp * eventHTTP
HTTP server.
Definition: httpserver.cpp:185
HTTPWorkItem
HTTP request work item.
Definition: httpserver.cpp:46
WorkQueue::ThreadCounter::~ThreadCounter
~ThreadCounter()
Definition: httpserver.cpp:91
WorkQueue::numThreads
int numThreads
Definition: httpserver.cpp:79
HTTPRequest
In-flight HTTP request.
Definition: httpserver.h:57
HTTP_FORBIDDEN
@ HTTP_FORBIDDEN
Definition: protocol.h:23
UpdateHTTPServerLogging
bool UpdateHTTPServerLogging(bool enable)
Change logging level for libevent.
Definition: httpserver.cpp:459
CClientUIInterface::ThreadSafeMessageBox
boost::signals2::signal< bool(const std::string &message, const std::string &caption, unsigned int style), boost::signals2::last_value< bool > > ThreadSafeMessageBox
Show message box.
Definition: guiinterface.h:80
HTTPPathHandler
Definition: httpserver.cpp:168
compat.h
LookupHost
bool LookupHost(const char *pszName, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
Definition: netbase.cpp:184
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:57
HTTPRequest::ReadBody
std::string ReadBody()
Read request body.
Definition: httpserver.cpp:596
HTTPRequest::UNKNOWN
@ UNKNOWN
Definition: httpserver.h:68
GetBoolArg
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
Definition: util.cpp:255
LogPrintf
#define LogPrintf(...)
Definition: logging.h:147
boundSockets
std::vector< evhttp_bound_socket * > boundSockets
Definition: httpserver.cpp:192
HTTPRequest::GetHeader
std::pair< bool, std::string > GetHeader(const std::string &hdr)
Get the request header specified by hdr, or an empty string.
Definition: httpserver.cpp:585
CNetAddr::IsValid
bool IsValid() const
Definition: netaddress.cpp:188
StartHTTPServer
bool StartHTTPServer()
Start HTTP server.
Definition: httpserver.cpp:476
CSubNet
Definition: netaddress.h:95
WorkQueue::Run
void Run()
Thread function.
Definition: httpserver.cpp:127
WorkQueue::cond
std::condition_variable cond
Definition: httpserver.cpp:74
LogPrint
#define LogPrint(category,...)
Definition: logging.h:162
HTTPRequest::RequestMethod
RequestMethod
Definition: httpserver.h:67
HTTPRequest::req
struct evhttp_request * req
Definition: httpserver.h:60
HTTPEvent::HTTPEvent
HTTPEvent(struct event_base *base, bool deleteWhenTriggered, const std::function< void(void)> &handler)
Create a new event.
Definition: httpserver.cpp:554
strprintf
#define strprintf
Definition: tinyformat.h:1056
CClientUIInterface::MSG_ERROR
@ MSG_ERROR
Definition: guiinterface.h:76
pathHandlers
std::vector< HTTPPathHandler > pathHandlers
Handlers for (sub)paths.
Definition: httpserver.cpp:191
HTTPEvent::trigger
void trigger(struct timeval *tv)
Trigger the event.
Definition: httpserver.cpp:564
BaseParams
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
Definition: chainparamsbase.cpp:60
HTTPWorkItem::func
HTTPRequestHandler func
Definition: httpserver.cpp:62
CSubNet::ToString
std::string ToString() const
Definition: netaddress.cpp:660
HTTPEvent
Event class.
Definition: httpserver.h:130
L
#define L(x0, x1, x2, x3, x4, x5, x6, x7)
Definition: jh.c:501
InterruptHTTPServer
void InterruptHTTPServer()
Interrupt HTTP server threads.
Definition: httpserver.cpp:492
WorkQueue::cs
std::mutex cs
Mutex protects entire object.
Definition: httpserver.cpp:73
HTTPRequest::GetURI
std::string GetURI()
Get requested URI.
Definition: httpserver.cpp:669
HTTPWorkItem::operator()
void operator()()
Definition: httpserver.cpp:53
HTTPRequest::HTTPRequest
HTTPRequest(struct evhttp_request *req)
Definition: httpserver.cpp:571
HTTPClosure
Event handler closure.
Definition: httpserver.h:121
LookupNumeric
CService LookupNumeric(const char *pszName, int portDefault)
Definition: netbase.cpp:234
MilliSleep
void MilliSleep(int64_t n)
Definition: utiltime.cpp:45
HTTPEvent::handler
std::function< void(void)> handler
Definition: httpserver.h:146
CSubNet::IsValid
bool IsValid() const
Definition: netaddress.cpp:698
threadHTTP
std::thread threadHTTP
Definition: httpserver.cpp:473
netbase.h
WorkQueue::Interrupt
void Interrupt()
Interrupt and exit loops.
Definition: httpserver.cpp:146
HTTPRequest::GetRequestMethod
RequestMethod GetRequestMethod()
Get request method.
Definition: httpserver.cpp:674
HTTPRequest::GET
@ GET
Definition: httpserver.h:69
handler
bool(* handler)(HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:589
httpserver.h
HTTPRequestHandler
std::function< void(HTTPRequest *req, const std::string &)> HTTPRequestHandler
Handler for requests to a certain HTTP path.
Definition: httpserver.h:40
BCLog::Logger::DisableCategory
void DisableCategory(LogFlags flag)
Definition: logging.cpp:71
HTTPPathHandler::HTTPPathHandler
HTTPPathHandler(std::string prefix, bool exactMatch, HTTPRequestHandler handler)
Definition: httpserver.cpp:171
mapMultiArgs
std::map< std::string, std::vector< std::string > > mapMultiArgs
Definition: util.cpp:112
StopHTTPServer
void StopHTTPServer()
Stop HTTP server.
Definition: httpserver.cpp:505
RegisterHTTPHandler
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
Definition: httpserver.cpp:695
GetArg
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
Definition: util.cpp:241
WorkQueue::ThreadCounter::wq
WorkQueue & wq
Definition: httpserver.cpp:85
HTTPRequest::WriteReply
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
Definition: httpserver.cpp:628
util.h
WorkQueue::~WorkQueue
~WorkQueue()
Definition: httpserver.cpp:108
WorkQueue::running
bool running
Definition: httpserver.cpp:77
HTTPPathHandler::handler
HTTPRequestHandler handler
Definition: httpserver.cpp:177
InitHTTPServer
bool InitHTTPServer()
Initialize HTTP server.
Definition: httpserver.cpp:393
HTTPPathHandler::prefix
std::string prefix
Definition: httpserver.cpp:175