Fabcoin Core  0.16.2
P2P Digital Currency
httpserver.cpp
Go to the documentation of this file.
1 // Copyright (c) 2015-2017 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 <rpc/server.h> // For HTTP status codes
14 #include <sync.h>
15 #include <ui_interface.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 <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 : public HTTPClosure
46 {
47 public:
48  HTTPWorkItem(std::unique_ptr<HTTPRequest> _req, const std::string &_path, const HTTPRequestHandler& _func):
49  req(std::move(_req)), path(_path), func(_func)
50  {
51  }
52  void operator()() override
53  {
54  func(req.get(), path);
55  }
56 
57  std::unique_ptr<HTTPRequest> req;
58 
59 private:
60  std::string path;
62 };
63 
67 template <typename WorkItem>
68 class WorkQueue
69 {
70 private:
72  std::mutex cs;
73  std::condition_variable cond;
74  std::deque<std::unique_ptr<WorkItem>> queue;
75  bool running;
76  size_t maxDepth;
78 
81  {
82  public:
85  {
86  std::lock_guard<std::mutex> lock(wq.cs);
87  wq.numThreads += 1;
88  }
90  {
91  std::lock_guard<std::mutex> lock(wq.cs);
92  wq.numThreads -= 1;
93  wq.cond.notify_all();
94  }
95  };
96 
97 public:
98  WorkQueue(size_t _maxDepth) : running(true),
99  maxDepth(_maxDepth),
100  numThreads(0)
101  {
102  }
107  {
108  }
110  bool Enqueue(WorkItem* item)
111  {
112  std::unique_lock<std::mutex> lock(cs);
113  if (queue.size() >= maxDepth) {
114  return false;
115  }
116  queue.emplace_back(std::unique_ptr<WorkItem>(item));
117  cond.notify_one();
118  return true;
119  }
121  void Run()
122  {
123  ThreadCounter count(*this);
124  while (true) {
125  std::unique_ptr<WorkItem> i;
126  {
127  std::unique_lock<std::mutex> lock(cs);
128  while (running && queue.empty())
129  cond.wait(lock);
130  if (!running)
131  break;
132  i = std::move(queue.front());
133  queue.pop_front();
134  }
135  (*i)();
136  }
137  }
139  void Interrupt()
140  {
141  std::unique_lock<std::mutex> lock(cs);
142  running = false;
143  cond.notify_all();
144  }
146  void WaitExit()
147  {
148  std::unique_lock<std::mutex> lock(cs);
149  while (numThreads > 0)
150  cond.wait(lock);
151  }
152 };
153 
155 {
157  HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler):
158  prefix(_prefix), exactMatch(_exactMatch), handler(_handler)
159  {
160  }
161  std::string prefix;
164 };
165 
168 static struct event_base* eventBase = 0;
171 struct evhttp* eventHTTP = 0;
173 static std::vector<CSubNet> rpc_allow_subnets;
175 static WorkQueue<HTTPClosure>* workQueue = 0;
177 std::vector<HTTPPathHandler> pathHandlers;
179 std::vector<evhttp_bound_socket *> boundSockets;
180 
182 static bool ClientAllowed(const CNetAddr& netaddr)
183 {
184  if (!netaddr.IsValid())
185  return false;
186  for(const CSubNet& subnet : rpc_allow_subnets)
187  if (subnet.Match(netaddr))
188  return true;
189  return false;
190 }
191 
193 static bool InitHTTPAllowList()
194 {
195  rpc_allow_subnets.clear();
196  CNetAddr localv4;
197  CNetAddr localv6;
198  LookupHost("127.0.0.1", localv4, false);
199  LookupHost("::1", localv6, false);
200  rpc_allow_subnets.push_back(CSubNet(localv4, 8)); // always allow IPv4 local subnet
201  rpc_allow_subnets.push_back(CSubNet(localv6)); // always allow IPv6 localhost
202  for (const std::string& strAllow : gArgs.GetArgs("-rpcallowip")) {
203  CSubNet subnet;
204  LookupSubNet(strAllow.c_str(), subnet);
205  if (!subnet.IsValid()) {
207  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),
209  return false;
210  }
211  rpc_allow_subnets.push_back(subnet);
212  }
213  std::string strAllowed;
214  for (const CSubNet& subnet : rpc_allow_subnets)
215  strAllowed += subnet.ToString() + " ";
216  LogPrint(BCLog::HTTP, "Allowing HTTP connections from: %s\n", strAllowed);
217  return true;
218 }
219 
221 static std::string RequestMethodString(HTTPRequest::RequestMethod m)
222 {
223  switch (m) {
224  case HTTPRequest::GET:
225  return "GET";
226  break;
227  case HTTPRequest::POST:
228  return "POST";
229  break;
230  case HTTPRequest::HEAD:
231  return "HEAD";
232  break;
233  case HTTPRequest::PUT:
234  return "PUT";
235  break;
236  default:
237  return "unknown";
238  }
239 }
240 
242 static void http_request_cb(struct evhttp_request* req, void* arg)
243 {
244  // Disable reading to work around a libevent bug, fixed in 2.2.0.
245  if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02020001) {
246  evhttp_connection* conn = evhttp_request_get_connection(req);
247  if (conn) {
248  bufferevent* bev = evhttp_connection_get_bufferevent(conn);
249  if (bev) {
250  bufferevent_disable(bev, EV_READ);
251  }
252  }
253  }
254  std::unique_ptr<HTTPRequest> hreq(new HTTPRequest(req));
255 
256  LogPrint(BCLog::HTTP, "Received a %s request for %s from %s\n",
257  RequestMethodString(hreq->GetRequestMethod()), hreq->GetURI(), hreq->GetPeer().ToString());
258 
259  // Early address-based allow check
260  if (!ClientAllowed(hreq->GetPeer())) {
261  hreq->WriteReply(HTTP_FORBIDDEN);
262  return;
263  }
264 
265  // Early reject unknown HTTP methods
266  if (hreq->GetRequestMethod() == HTTPRequest::UNKNOWN) {
267  hreq->WriteReply(HTTP_BADMETHOD);
268  return;
269  }
270 
271  // Find registered handler for prefix
272  std::string strURI = hreq->GetURI();
273  std::string path;
274  std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin();
275  std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end();
276  for (; i != iend; ++i) {
277  bool match = false;
278  if (i->exactMatch)
279  match = (strURI == i->prefix);
280  else
281  match = (strURI.substr(0, i->prefix.size()) == i->prefix);
282  if (match) {
283  path = strURI.substr(i->prefix.size());
284  break;
285  }
286  }
287 
288  // Dispatch to worker thread
289  if (i != iend) {
290  std::unique_ptr<HTTPWorkItem> item(new HTTPWorkItem(std::move(hreq), path, i->handler));
291  assert(workQueue);
292  if (workQueue->Enqueue(item.get()))
293  item.release(); /* if true, queue took ownership */
294  else {
295  LogPrintf("WARNING: request rejected because http work queue depth exceeded, it can be increased with the -rpcworkqueue= setting\n");
296  item->req->WriteReply(HTTP_INTERNAL, "Work queue depth exceeded");
297  }
298  } else {
299  hreq->WriteReply(HTTP_NOTFOUND);
300  }
301 }
302 
304 static void http_reject_request_cb(struct evhttp_request* req, void*)
305 {
306  LogPrint(BCLog::HTTP, "Rejecting request while shutting down\n");
307  evhttp_send_error(req, HTTP_SERVUNAVAIL, nullptr);
308 }
309 
311 static bool ThreadHTTP(struct event_base* base, struct evhttp* http)
312 {
313  RenameThread("fabcoin-http");
314  LogPrint(BCLog::HTTP, "Entering http event loop\n");
315  event_base_dispatch(base);
316  // Event loop will be interrupted by InterruptHTTPServer()
317  LogPrint(BCLog::HTTP, "Exited http event loop\n");
318  return event_base_got_break(base) == 0;
319 }
320 
322 static bool HTTPBindAddresses(struct evhttp* http)
323 {
324  int defaultPort = gArgs.GetArg("-rpcport", BaseParams().RPCPort());
325  std::vector<std::pair<std::string, uint16_t> > endpoints;
326 
327  // Determine what addresses to bind to
328  if (!gArgs.IsArgSet("-rpcallowip")) { // Default to loopback if not allowing external IPs
329  endpoints.push_back(std::make_pair("::1", defaultPort));
330  endpoints.push_back(std::make_pair("127.0.0.1", defaultPort));
331  if (gArgs.IsArgSet("-rpcbind")) {
332  LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n");
333  }
334  } else if (gArgs.IsArgSet("-rpcbind")) { // Specific bind address
335  for (const std::string& strRPCBind : gArgs.GetArgs("-rpcbind")) {
336  int port = defaultPort;
337  std::string host;
338  SplitHostPort(strRPCBind, port, host);
339  endpoints.push_back(std::make_pair(host, port));
340  }
341  } else { // No specific bind address specified, bind to any
342  endpoints.push_back(std::make_pair("::", defaultPort));
343  endpoints.push_back(std::make_pair("0.0.0.0", defaultPort));
344  }
345 
346  // Bind addresses
347  for (std::vector<std::pair<std::string, uint16_t> >::iterator i = endpoints.begin(); i != endpoints.end(); ++i) {
348  LogPrint(BCLog::HTTP, "Binding RPC on address %s port %i\n", i->first, i->second);
349  evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(http, i->first.empty() ? nullptr : i->first.c_str(), i->second);
350  if (bind_handle) {
351  boundSockets.push_back(bind_handle);
352  } else {
353  LogPrintf("Binding RPC on address %s port %i failed.\n", i->first, i->second);
354  }
355  }
356  return !boundSockets.empty();
357 }
358 
360 static void HTTPWorkQueueRun(WorkQueue<HTTPClosure>* queue)
361 {
362  RenameThread("fabcoin-httpworker");
363  queue->Run();
364 }
365 
367 static void libevent_log_cb(int severity, const char *msg)
368 {
369 #ifndef EVENT_LOG_WARN
370 // EVENT_LOG_WARN was added in 2.0.19; but before then _EVENT_LOG_WARN existed.
371 # define EVENT_LOG_WARN _EVENT_LOG_WARN
372 #endif
373  if (severity >= EVENT_LOG_WARN) // Log warn messages and higher without debug category
374  LogPrintf("libevent: %s\n", msg);
375  else
376  LogPrint(BCLog::LIBEVENT, "libevent: %s\n", msg);
377 }
378 
380 {
381  if (!InitHTTPAllowList())
382  return false;
383 
384  if (gArgs.GetBoolArg("-rpcssl", false)) {
386  "SSL mode for RPC (-rpcssl) is no longer supported.",
388  return false;
389  }
390 
391  // Redirect libevent's logging to our own log
392  event_set_log_callback(&libevent_log_cb);
393  // Update libevent's log handling. Returns false if our version of
394  // libevent doesn't support debug logging, in which case we should
395  // clear the BCLog::LIBEVENT flag.
398  }
399 
400 #ifdef WIN32
401  evthread_use_windows_threads();
402 #else
403  evthread_use_pthreads();
404 #endif
405 
406  raii_event_base base_ctr = obtain_event_base();
407 
408  /* Create a new evhttp object to handle requests. */
409  raii_evhttp http_ctr = obtain_evhttp(base_ctr.get());
410  struct evhttp* http = http_ctr.get();
411  if (!http) {
412  LogPrintf("couldn't create evhttp. Exiting.\n");
413  return false;
414  }
415 
416  evhttp_set_timeout(http, gArgs.GetArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
417  evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
418  evhttp_set_max_body_size(http, MAX_SIZE);
419  evhttp_set_gencb(http, http_request_cb, nullptr);
420 
421  if (!HTTPBindAddresses(http)) {
422  LogPrintf("Unable to bind any endpoint for RPC server\n");
423  return false;
424  }
425 
426  LogPrint(BCLog::HTTP, "Initialized HTTP server\n");
427  int workQueueDepth = std::max((long)gArgs.GetArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE), 1L);
428  LogPrintf("HTTP: creating work queue of depth %d\n", workQueueDepth);
429 
430  workQueue = new WorkQueue<HTTPClosure>(workQueueDepth);
431  // tranfer ownership to eventBase/HTTP via .release()
432  eventBase = base_ctr.release();
433  eventHTTP = http_ctr.release();
434  return true;
435 }
436 
437 bool UpdateHTTPServerLogging(bool enable) {
438 #if LIBEVENT_VERSION_NUMBER >= 0x02010100
439  if (enable) {
440  event_enable_debug_logging(EVENT_DBG_ALL);
441  } else {
442  event_enable_debug_logging(EVENT_DBG_NONE);
443  }
444  return true;
445 #else
446  // Can't update libevent logging if version < 02010100
447  return false;
448 #endif
449 }
450 
451 std::thread threadHTTP;
452 std::future<bool> threadResult;
453 
455 {
456  LogPrint(BCLog::HTTP, "Starting HTTP server\n");
457  int rpcThreads = std::max((long)gArgs.GetArg("-rpcthreads", DEFAULT_HTTP_THREADS), 1L);
458  LogPrintf("HTTP: starting %d worker threads\n", rpcThreads);
459  std::packaged_task<bool(event_base*, evhttp*)> task(ThreadHTTP);
460  threadResult = task.get_future();
461  threadHTTP = std::thread(std::move(task), eventBase, eventHTTP);
462 
463  for (int i = 0; i < rpcThreads; i++) {
464  std::thread rpc_worker(HTTPWorkQueueRun, workQueue);
465  rpc_worker.detach();
466  }
467  return true;
468 }
469 
471 {
472  LogPrint(BCLog::HTTP, "Interrupting HTTP server\n");
473  if (eventHTTP) {
474  // Unlisten sockets
475  for (evhttp_bound_socket *socket : boundSockets) {
476  evhttp_del_accept_socket(eventHTTP, socket);
477  }
478  // Reject requests on current connections
479  evhttp_set_gencb(eventHTTP, http_reject_request_cb, nullptr);
480  }
481  if (workQueue)
482  workQueue->Interrupt();
483 }
484 
486 {
487  LogPrint(BCLog::HTTP, "Stopping HTTP server\n");
488  if (workQueue) {
489  LogPrint(BCLog::HTTP, "Waiting for HTTP worker threads to exit\n");
490  workQueue->WaitExit();
491  delete workQueue;
492  workQueue = nullptr;
493  }
494  if (eventBase) {
495  LogPrint(BCLog::HTTP, "Waiting for HTTP event thread to exit\n");
496  // Give event loop a few seconds to exit (to send back last RPC responses), then break it
497  // Before this was solved with event_base_loopexit, but that didn't work as expected in
498  // at least libevent 2.0.21 and always introduced a delay. In libevent
499  // master that appears to be solved, so in the future that solution
500  // could be used again (if desirable).
501  // (see discussion in https://github.com/blockchaingate/fabcoin/pull/6990)
502  if (threadResult.valid() && threadResult.wait_for(std::chrono::milliseconds(2000)) == std::future_status::timeout) {
503  LogPrintf("HTTP event loop did not exit within allotted time, sending loopbreak\n");
504  event_base_loopbreak(eventBase);
505  }
506  threadHTTP.join();
507  }
508  if (eventHTTP) {
509  evhttp_free(eventHTTP);
510  eventHTTP = 0;
511  }
512  if (eventBase) {
513  event_base_free(eventBase);
514  eventBase = 0;
515  }
516  LogPrint(BCLog::HTTP, "Stopped HTTP server\n");
517 }
518 
519 struct event_base* EventBase()
520 {
521  return eventBase;
522 }
523 
524 static void httpevent_callback_fn(evutil_socket_t, short, void* data)
525 {
526  // Static handler: simply call inner handler
527  HTTPEvent *self = ((HTTPEvent*)data);
528  self->handler();
529  if (self->deleteWhenTriggered)
530  delete self;
531 }
532 
533 HTTPEvent::HTTPEvent(struct event_base* base, bool _deleteWhenTriggered, struct evbuffer *_databuf, const std::function<void(void)>& _handler):
534  deleteWhenTriggered(_deleteWhenTriggered), handler(_handler), databuf(_databuf)
535 {
536  ev = event_new(base, -1, 0, httpevent_callback_fn, this);
537  assert(ev);
538 }
540 {
541  if (databuf != NULL) {
542  evbuffer_free(databuf);
543  }
544  event_free(ev);
545 }
546 void HTTPEvent::trigger(struct timeval* tv)
547 {
548  if (tv == nullptr)
549  event_active(ev, 0, 0); // immediately trigger event in main thread
550  else
551  evtimer_add(ev, tv); // trigger after timeval passed
552 }
553 HTTPRequest::HTTPRequest(struct evhttp_request* _req) : req(_req),
554  replySent(false),
555  startedChunkTransfer(false),
556  connClosed(false)
557 {
558 }
560 {
561  if (!replySent && !startedChunkTransfer) {
562  // Keep track of whether reply was sent to avoid request leaks
563  LogPrintf("%s: Unhandled request\n", __func__);
564  WriteReply(HTTP_INTERNAL, "Unhandled request");
565  }
566  // evhttpd cleans up the request, as long as a reply was sent.
567 }
568 
570  LogPrint(BCLog::HTTPPOLL, "wait for connection close\n");
571 
572  // wait at most 5 seconds for client to close
573  for (int i = 0; i < 10 && IsRPCRunning() && !isConnClosed(); i++) {
574  std::unique_lock<std::mutex> lock(cs);
575  closeCv.wait_for(lock, std::chrono::milliseconds(500));
576  }
577 
578  if (isConnClosed()) {
579  LogPrint(BCLog::HTTPPOLL, "wait for connection close, ok\n");
580  } else if (!IsRPCRunning()) {
581  LogPrint(BCLog::HTTPPOLL, "wait for connection close, RPC stopped\n");
582  } else {
583  LogPrint(BCLog::HTTPPOLL, "wait for connection close, timeout after 5 seconds\n");
584  }
585 }
586 
588  LogPrint(BCLog::HTTPPOLL, "start detect http connection close\n");
589  // will need to call evhttp_send_reply_end to clean this up
590  auto conn = evhttp_request_get_connection(req);
591 
592  // evhttp_connection_set_closecb does not reliably detect client connection close unless we write to it.
593  //
594  // This problem is supposedly resolved in 2.1.8. See: https://github.com/libevent/libevent/issues/78
595  //
596  // But we should just write to the socket to test liveness. This is useful for long-poll RPC calls to see
597  // if they should terminate the request early.
598  //
599  // More weirdness: if process received SIGTERM, the http event loop (in HTTPThread) returns prematurely with 1.
600  // In which case evhttp_send_reply_end doesn't seem to get called, and evhttp_connection_set_closecb is
601  // not called. BUT when the event base is freed, this callback IS called, and HTTPRequest is already freed.
602  //
603  // So, waitClientClose and startDetectClientClose should just not do anything if RPC is shutting down.
604  evhttp_connection_set_closecb(conn, [](struct evhttp_connection *conn, void *data) {
605  LogPrint(BCLog::HTTPPOLL, "http connection close detected\n");
606 
607  if (IsRPCRunning()) {
608  auto req = (HTTPRequest*) data;
609  req->setConnClosed();
610  }
611  }, (void *) this);
612 }
613 
615  std::lock_guard<std::mutex> lock(cs);
616  connClosed = true;
617  closeCv.notify_all();
618 }
619 
621  std::lock_guard<std::mutex> lock(cs);
622  return connClosed;
623 }
624 
626  return startedChunkTransfer;
627 }
628 
629 std::pair<bool, std::string> HTTPRequest::GetHeader(const std::string& hdr)
630 {
631  const struct evkeyvalq* headers = evhttp_request_get_input_headers(req);
632  assert(headers);
633  const char* val = evhttp_find_header(headers, hdr.c_str());
634  if (val)
635  return std::make_pair(true, val);
636  else
637  return std::make_pair(false, "");
638 }
639 
641 {
642  struct evbuffer* buf = evhttp_request_get_input_buffer(req);
643  if (!buf)
644  return "";
645  size_t size = evbuffer_get_length(buf);
652  const char* data = (const char*)evbuffer_pullup(buf, size);
653  if (!data) // returns nullptr in case of empty buffer
654  return "";
655  std::string rv(data, size);
656  evbuffer_drain(buf, size);
657  return rv;
658 }
659 
661  return replySent;
662 }
663 
664 void HTTPRequest::WriteHeader(const std::string& hdr, const std::string& value)
665 {
666  struct evkeyvalq* headers = evhttp_request_get_output_headers(req);
667  assert(headers);
668  evhttp_add_header(headers, hdr.c_str(), value.c_str());
669 }
670 
673 
674  HTTPEvent* ev = new HTTPEvent(eventBase, true, NULL,
675  std::bind(evhttp_send_reply_end, req));
676 
677  ev->trigger(0);
678 
679  // If HTTPRequest is destroyed before connection is closed, evhttp seems to get messed up.
680  // We wait here for connection close before returning back to the handler, where HTTPRequest will be reclaimed.
681  waitClientClose();
682 
683  replySent = true;
684  // `WriteReply` sets req to 0 to prevent req from being freed. But this is not enough in the case of long-polling.
685  // Something is still freed to early.
686  // req = 0;
687 }
688 
689 void HTTPRequest::Chunk(const std::string& chunk) {
690  assert(!replySent);
691 
692  int status = 200;
693 
694  if (!startedChunkTransfer) {
695  HTTPEvent* ev = new HTTPEvent(eventBase, true, NULL,
696  std::bind(evhttp_send_reply_start, req, status,
697  (const char*) NULL));
698  ev->trigger(0);
699 
701  startedChunkTransfer = true;
702  }
703 
704 
705  if (chunk.size() > 0) {
706  auto databuf = evbuffer_new(); // HTTPEvent will free this buffer
707  evbuffer_add(databuf, chunk.data(), chunk.size());
708  HTTPEvent* ev = new HTTPEvent(eventBase, true, databuf,
709  std::bind(evhttp_send_reply_chunk, req, databuf));
710  ev->trigger(0);
711  }
712 }
713 
719 void HTTPRequest::WriteReply(int nStatus, const std::string& strReply)
720 {
721  assert(!replySent && req);
722  // Send event to main http thread to send reply message
723  struct evbuffer* evb = evhttp_request_get_output_buffer(req);
724  assert(evb);
725  evbuffer_add(evb, strReply.data(), strReply.size());
726  auto req_copy = req;
727  HTTPEvent* ev = new HTTPEvent(eventBase, true, nullptr, [req_copy, nStatus]{
728  evhttp_send_reply(req_copy, nStatus, nullptr, nullptr);
729  // Re-enable reading from the socket. This is the second part of the libevent
730  // workaround above.
731  if (event_get_version_number() >= 0x02010600 && event_get_version_number() < 0x02020001) {
732  evhttp_connection* conn = evhttp_request_get_connection(req_copy);
733  if (conn) {
734  bufferevent* bev = evhttp_connection_get_bufferevent(conn);
735  if (bev) {
736  bufferevent_enable(bev, EV_READ | EV_WRITE);
737  }
738  }
739  }
740  });
741  ev->trigger(nullptr);
742  replySent = true;
743  req = nullptr; // transferred back to main thread
744 }
745 
747 {
748  evhttp_connection* con = evhttp_request_get_connection(req);
749  CService peer;
750  if (con) {
751  // evhttp retains ownership over returned address string
752  const char* address = "";
753  uint16_t port = 0;
754  evhttp_connection_get_peer(con, (char**)&address, &port);
755  peer = LookupNumeric(address, port);
756  }
757  return peer;
758 }
759 
760 std::string HTTPRequest::GetURI()
761 {
762  return evhttp_request_get_uri(req);
763 }
764 
766 {
767  switch (evhttp_request_get_command(req)) {
768  case EVHTTP_REQ_GET:
769  return GET;
770  break;
771  case EVHTTP_REQ_POST:
772  return POST;
773  break;
774  case EVHTTP_REQ_HEAD:
775  return HEAD;
776  break;
777  case EVHTTP_REQ_PUT:
778  return PUT;
779  break;
780  default:
781  return UNKNOWN;
782  break;
783  }
784 }
785 
786 void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
787 {
788  LogPrint(BCLog::HTTP, "Registering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
789  pathHandlers.push_back(HTTPPathHandler(prefix, exactMatch, handler));
790 }
791 
792 void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
793 {
794  std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
795  std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
796  for (; i != iend; ++i)
797  if (i->prefix == prefix && i->exactMatch == exactMatch)
798  break;
799  if (i != iend)
800  {
801  LogPrint(BCLog::HTTP, "Unregistering HTTP handler for %s (exactmatch %d)\n", prefix, exactMatch);
802  pathHandlers.erase(i);
803  }
804 }
805 
806 std::string urlDecode(const std::string &urlEncoded) {
807  std::string res;
808  if (!urlEncoded.empty()) {
809  char *decoded = evhttp_uridecode(urlEncoded.c_str(), false, nullptr);
810  if (decoded) {
811  res = std::string(decoded);
812  free(decoded);
813  }
814  }
815  return res;
816 }
bool(* handler)(HTTPRequest *req, const std::string &strReq)
Definition: rest.cpp:624
ThreadCounter(WorkQueue &w)
Definition: httpserver.cpp:84
raii_event_base obtain_event_base()
Definition: events.h:30
#define function(a, b, c, d, k, s)
bool ReplySent()
Is reply sent?
Definition: httpserver.cpp:660
void WaitExit()
Wait for worker threads to exit.
Definition: httpserver.cpp:146
std::vector< evhttp_bound_socket * > boundSockets
Bound listening sockets.
Definition: httpserver.cpp:179
bool StartHTTPServer()
Start HTTP server.
Definition: httpserver.cpp:454
bool IsArgSet(const std::string &strArg)
Return true if the given argument has been manually set.
Definition: util.cpp:498
bool IsRPCRunning()
Query whether RPC is running.
Definition: server.cpp:335
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:553
raii_evhttp obtain_evhttp(struct event_base *base)
Definition: events.h:41
Definition: util.h:86
#define strprintf
Definition: tinyformat.h:1054
std::vector< HTTPPathHandler > pathHandlers
Handlers for (sub)paths.
Definition: httpserver.cpp:177
std::pair< bool, std::string > GetHeader(const std::string &hdr)
Get the request header specified by hdr, or an empty string.
Definition: httpserver.cpp:629
CService LookupNumeric(const char *pszName, int portDefault)
Definition: netbase.cpp:169
Event class.
Definition: httpserver.h:159
const char * prefix
Definition: rest.cpp:623
std::string urlDecode(const std::string &urlEncoded)
Definition: httpserver.cpp:806
size_t count
Definition: ExecStats.cpp:37
std::string GetURI()
Get requested URI.
Definition: httpserver.cpp:760
void Chunk(const std::string &chunk)
Start chunk transfer.
Definition: httpserver.cpp:689
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
bool GetBoolArg(const std::string &strArg, bool fDefault)
Return boolean argument or default value.
Definition: util.cpp:520
std::hash for asio::adress
Definition: Common.h:323
size_t maxDepth
Definition: httpserver.cpp:76
std::vector< std::string > GetArgs(const std::string &strArg)
Definition: util.cpp:490
assert(len-trim+(2 *lenIndices)<=WIDTH)
std::string path
Definition: httpserver.cpp:60
std::atomic< uint32_t > logCategories
struct evhttp_request * req
Definition: httpserver.h:62
std::deque< std::unique_ptr< WorkItem > > queue
Definition: httpserver.cpp:74
std::thread threadHTTP
Definition: httpserver.cpp:451
HTTP request work item.
Definition: httpserver.cpp:45
void InterruptHTTPServer()
Interrupt HTTP server threads.
Definition: httpserver.cpp:470
RequestMethod GetRequestMethod()
Get request method.
Definition: httpserver.cpp:765
bool isConnClosed()
Definition: httpserver.cpp:620
void RenameThread(const char *name)
Definition: util.cpp:888
bool Enqueue(WorkItem *item)
Enqueue a work item.
Definition: httpserver.cpp:110
void ChunkEnd()
End chunk transfer.
Definition: httpserver.cpp:671
Event handler closure.
Definition: httpserver.h:150
struct event * ev
Definition: httpserver.h:178
std::mutex cs
Definition: httpserver.h:67
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler)
Register handler for prefix.
Definition: httpserver.cpp:786
bool connClosed
Definition: httpserver.h:65
void Run()
Thread function.
Definition: httpserver.cpp:121
HTTPPathHandler(std::string _prefix, bool _exactMatch, HTTPRequestHandler _handler)
Definition: httpserver.cpp:157
bool InitHTTPServer()
Initialize HTTP server.
Definition: httpserver.cpp:379
#define LogPrintf(...)
Definition: util.h:153
void StopHTTPServer()
Stop HTTP server.
Definition: httpserver.cpp:485
void WriteReply(int nStatus, const std::string &strReply="")
Write HTTP reply.
Definition: httpserver.cpp:719
bool IsValid() const
Definition: netaddress.cpp:197
void startDetectClientClose()
Definition: httpserver.cpp:587
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:140
struct evbuffer * databuf
Definition: httpserver.h:177
std::condition_variable cond
Definition: httpserver.cpp:73
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch)
Unregister handler for prefix.
Definition: httpserver.cpp:792
HTTPRequestHandler func
Definition: httpserver.cpp:61
std::function< void(void)> handler
Definition: httpserver.h:175
bool isChunkMode()
Definition: httpserver.cpp:625
int numThreads
Definition: httpserver.cpp:77
std::future< bool > threadResult
Definition: httpserver.cpp:452
std::mutex cs
Mutex protects entire object.
Definition: httpserver.cpp:72
CService GetPeer()
Get CService (address:ip) for the origin of the http request.
Definition: httpserver.cpp:746
struct event_base * EventBase()
Return evhttp event base.
Definition: httpserver.cpp:519
bool LookupSubNet(const char *pszName, CSubNet &ret)
Definition: netbase.cpp:660
#define LogPrint(category,...)
Definition: util.h:164
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
Definition: netaddress.h:31
Simple work queue for distributing work over multiple threads.
Definition: httpserver.cpp:68
ArgsManager gArgs
Definition: util.cpp:94
RAII object to keep track of number of running worker threads.
Definition: httpserver.cpp:80
bool IsValid() const
Definition: netaddress.cpp:721
void SplitHostPort(std::string in, int &portOut, std::string &hostOut)
#define EVENT_LOG_WARN
std::string prefix
Definition: httpserver.cpp:161
void WriteHeader(const std::string &hdr, const std::string &value)
Write output header.
Definition: httpserver.cpp:664
uint8_t const size_t const size
Definition: sha3.h:20
void trigger(struct timeval *tv)
Trigger the event.
Definition: httpserver.cpp:546
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
Definition: util.cpp:504
bool running
Definition: httpserver.cpp:75
bool startedChunkTransfer
Definition: httpserver.h:64
std::function< bool(HTTPRequest *req, const std::string &)> HTTPRequestHandler
Handler for requests to a certain HTTP path.
Definition: httpserver.h:42
void waitClientClose()
Definition: httpserver.cpp:569
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: ui_interface.h:75
void operator()() override
Definition: httpserver.cpp:52
std::string ReadBody()
Read request body.
Definition: httpserver.cpp:640
WorkQueue(size_t _maxDepth)
Definition: httpserver.cpp:98
In-flight HTTP request.
Definition: httpserver.h:59
std::unique_ptr< HTTPRequest > req
Definition: httpserver.cpp:57
dev::WithExisting max(dev::WithExisting _a, dev::WithExisting _b)
Definition: Common.h:326
struct evm_uint160be address(struct evm_env *env)
Definition: capi.c:13
CClientUIInterface uiInterface
Definition: ui_interface.cpp:8
HTTPEvent(struct event_base *base, bool deleteWhenTriggered, struct evbuffer *_databuf, const std::function< void(void)> &handler)
Create a new event.
Definition: httpserver.cpp:533
bool LookupHost(const char *pszName, std::vector< CNetAddr > &vIP, unsigned int nMaxSolutions, bool fAllowLookup)
Definition: netbase.cpp:118
HTTPRequestHandler handler
Definition: httpserver.cpp:163
void setConnClosed()
Definition: httpserver.cpp:614
std::condition_variable closeCv
Definition: httpserver.h:68
bool replySent
Definition: httpserver.h:63
struct evhttp * eventHTTP
HTTP server.
Definition: httpserver.cpp:171
uint8_t const * data
Definition: sha3.h:19
bool UpdateHTTPServerLogging(bool enable)
Change logging level for libevent.
Definition: httpserver.cpp:437
~WorkQueue()
Precondition: worker threads have all stopped (call WaitExit)
Definition: httpserver.cpp:106
void Interrupt()
Interrupt and exit loops.
Definition: httpserver.cpp:139