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