-
Notifications
You must be signed in to change notification settings - Fork 295
/
httpserver.cpp
598 lines (536 loc) · 20.2 KB
/
httpserver.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
// Copyright (c) 2015-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "httpserver.h"
#include "chainparamsbase.h"
#include "config.h"
#include "net/netbase.h"
#include "rpc/http_protocol.h" // For HTTP status codes
#include "task_helpers.h"
#include "ui_interface.h"
#include "util.h"
#include "utilstrencodings.h"
#include <sys/types.h>
#include <event2/buffer.h>
#include <event2/event.h>
#include <event2/http.h>
#include <event2/keyvalq_struct.h>
#include <event2/thread.h>
#include <event2/util.h>
#ifdef EVENT__HAVE_NETINET_IN_H
#include <netinet/in.h>
#ifdef _XOPEN_SOURCE_EXTENDED
#include <arpa/inet.h>
#endif
#endif
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <future>
/** Maximum size of http request (request line + headers) */
static const size_t MAX_HEADERS_SIZE = 8192;
/**
* Maximum HTTP post body size. Twice the maximum block size is added to this
* value in practice.
*/
static const size_t MIN_SUPPORTED_BODY_SIZE = 0x02000000;
struct HTTPPathHandler {
HTTPPathHandler() {}
HTTPPathHandler(std::string _prefix, bool _exactMatch,
HTTPRequestHandler _handler)
: prefix(_prefix), exactMatch(_exactMatch), handler(_handler) {}
std::string prefix;
bool exactMatch;
HTTPRequestHandler handler;
};
/** HTTP module state */
//! libevent event loop
static struct event_base *eventBase = 0;
//! HTTP server
struct evhttp *eventHTTP = 0;
//! List of subnets to allow RPC connections from
static std::vector<CSubNet> rpc_allow_subnets;
//! Work queue for handling longer requests off the event loop thread
static std::unique_ptr<CThreadPool<CQueueAdaptor>> pWorkQueue {nullptr};
//! Handlers for (sub)paths
std::vector<HTTPPathHandler> pathHandlers;
//! Bound listening sockets
std::vector<evhttp_bound_socket *> boundSockets;
/** Check if a network address is allowed to access the HTTP server */
static bool ClientAllowed(const CNetAddr &netaddr) {
if (!netaddr.IsValid()) return false;
for (const CSubNet &subnet : rpc_allow_subnets)
if (subnet.Match(netaddr)) return true;
return false;
}
/** Initialize ACL list for HTTP server */
static bool InitHTTPAllowList() {
rpc_allow_subnets.clear();
CNetAddr localv4;
CNetAddr localv6;
LookupHost("127.0.0.1", localv4, false);
LookupHost("::1", localv6, false);
// always allow IPv4 local subnet.
rpc_allow_subnets.push_back(CSubNet(localv4, 8));
// always allow IPv6 localhost.
rpc_allow_subnets.push_back(CSubNet(localv6));
if (gArgs.IsArgSet("-rpcallowip")) {
for (const std::string &strAllow : gArgs.GetArgs("-rpcallowip")) {
CSubNet subnet;
LookupSubNet(strAllow.c_str(), subnet);
if (!subnet.IsValid()) {
uiInterface.ThreadSafeMessageBox(
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),
"", CClientUIInterface::MSG_ERROR);
return false;
}
rpc_allow_subnets.push_back(subnet);
}
}
std::string strAllowed;
for (const CSubNet &subnet : rpc_allow_subnets)
strAllowed += subnet.ToString() + " ";
LogPrint(BCLog::HTTP, "Allowing HTTP connections from: %s\n", strAllowed);
return true;
}
/** HTTP request method as string - use for logging only */
static std::string RequestMethodString(HTTPRequest::RequestMethod m) {
switch (m) {
case HTTPRequest::GET:
return "GET";
case HTTPRequest::POST:
return "POST";
case HTTPRequest::HEAD:
return "HEAD";
case HTTPRequest::PUT:
return "PUT";
case HTTPRequest::OPTIONS:
return "OPTIONS";
default:
return "unknown";
}
}
/** HTTP request callback */
static void http_request_cb(struct evhttp_request *req, void *arg) {
Config &config = *reinterpret_cast<Config *>(arg);
std::shared_ptr<HTTPRequest> hreq { std::make_shared<HTTPRequest>(req) };
LogPrint(BCLog::HTTP, "Received a %s request for %s from %s\n",
RequestMethodString(hreq->GetRequestMethod()), hreq->GetURI(),
hreq->GetPeer().ToString());
// Early address-based allow check
if (!ClientAllowed(hreq->GetPeer())) {
hreq->WriteReply(HTTP_FORBIDDEN);
return;
}
// Early reject unknown HTTP methods
if (hreq->GetRequestMethod() == HTTPRequest::UNKNOWN) {
hreq->WriteReply(HTTP_BADMETHOD);
return;
}
// Find registered handler for prefix
std::string strURI = hreq->GetURI();
std::string path;
std::vector<HTTPPathHandler>::const_iterator i = pathHandlers.begin();
std::vector<HTTPPathHandler>::const_iterator iend = pathHandlers.end();
for (; i != iend; ++i) {
bool match = false;
if (i->exactMatch) {
match = (strURI == i->prefix);
} else {
match = (strURI.substr(0, i->prefix.size()) == i->prefix);
}
if (match) {
path = strURI.substr(i->prefix.size());
break;
}
}
// Dispatch to worker thread.
if (i != iend) {
size_t workQueueDepth = std::max(static_cast<size_t>(gArgs.GetArg("-rpcworkqueue", DEFAULT_HTTP_WORKQUEUE)), size_t{1});
assert(pWorkQueue);
if(pWorkQueue->getTaskDepth() < workQueueDepth) {
auto handleTask = [&config, hreq = std::move(hreq), path, handler = i->handler]()
{
handler(config, hreq.get(), path);
};
make_task(*pWorkQueue, std::move(handleTask));
}
else {
LogPrintf("WARNING: request rejected because http work queue depth "
"exceeded, it can be increased with the -rpcworkqueue= "
"setting\n");
hreq->WriteReply(HTTP_INTERNAL, "Work queue depth exceeded");
}
} else {
hreq->WriteReply(HTTP_NOTFOUND);
}
}
/** Callback to reject HTTP requests after shutdown. */
static void http_reject_request_cb(struct evhttp_request *req, void *) {
LogPrint(BCLog::HTTP, "Rejecting request while shutting down\n");
evhttp_send_error(req, HTTP_SERVUNAVAIL, nullptr);
}
/** Event dispatcher thread */
static bool ThreadHTTP(struct event_base *base, struct evhttp *http) {
RenameThread("http");
LogPrint(BCLog::HTTP, "Entering http event loop\n");
event_base_dispatch(base);
// Event loop will be interrupted by InterruptHTTPServer()
LogPrint(BCLog::HTTP, "Exited http event loop\n");
return event_base_got_break(base) == 0;
}
/** Bind HTTP server to specified addresses */
static bool HTTPBindAddresses(struct evhttp *http) {
int defaultPort = gArgs.GetArg("-rpcport", BaseParams().RPCPort());
std::vector<std::pair<std::string, uint16_t>> endpoints;
// Determine what addresses to bind to
if (!gArgs.IsArgSet("-rpcallowip")) {
// Default to loopback if not allowing external IPs.
endpoints.push_back(std::make_pair("::1", defaultPort));
endpoints.push_back(std::make_pair("127.0.0.1", defaultPort));
if (gArgs.IsArgSet("-rpcbind")) {
LogPrintf("WARNING: option -rpcbind was ignored because "
"-rpcallowip was not specified, refusing to allow "
"everyone to connect\n");
}
} else if (gArgs.IsArgSet("-rpcbind")) {
// Specific bind address.
for (const std::string &strRPCBind : gArgs.GetArgs("-rpcbind")) {
int port = defaultPort;
std::string host;
SplitHostPort(strRPCBind, port, host);
endpoints.push_back(std::make_pair(host, port));
}
} else {
// No specific bind address specified, bind to any.
endpoints.push_back(std::make_pair("::", defaultPort));
endpoints.push_back(std::make_pair("0.0.0.0", defaultPort));
}
// Bind addresses
for (std::vector<std::pair<std::string, uint16_t>>::iterator i =
endpoints.begin();
i != endpoints.end(); ++i) {
LogPrint(BCLog::HTTP, "Binding RPC on address %s port %i\n", i->first,
i->second);
evhttp_bound_socket *bind_handle = evhttp_bind_socket_with_handle(
http, i->first.empty() ? nullptr : i->first.c_str(), i->second);
if (bind_handle) {
boundSockets.push_back(bind_handle);
} else {
LogPrintf("Binding RPC on address %s port %i failed.\n", i->first,
i->second);
}
}
return !boundSockets.empty();
}
/** libevent event log callback */
static void libevent_log_cb(int severity, const char *msg) {
#ifndef EVENT_LOG_WARN
// EVENT_LOG_WARN was added in 2.0.19; but before then _EVENT_LOG_WARN existed.
#define EVENT_LOG_WARN _EVENT_LOG_WARN
#endif
// Log warn messages and higher without debug category.
if (severity >= EVENT_LOG_WARN) {
LogPrintf("libevent: %s\n", msg);
} else {
LogPrint(BCLog::LIBEVENT, "libevent: %s\n", msg);
}
}
ev_ssize_t GetMaxBodySizeSafe(uint64_t maxBlockSize)
{
ev_ssize_t maxBodySize{ 0 };
constexpr auto maxSsize = std::numeric_limits<ev_ssize_t>::max();
if (maxBlockSize > (maxSsize / 2 - MIN_SUPPORTED_BODY_SIZE))
{
maxBodySize = maxSsize;
}
else
{
maxBodySize = MIN_SUPPORTED_BODY_SIZE + 2 * maxBlockSize;
}
return maxBodySize;
}
bool InitHTTPServer(Config &config) {
struct evhttp *http = 0;
struct event_base *base = 0;
if (!InitHTTPAllowList()) return false;
if (gArgs.GetBoolArg("-rpcssl", false)) {
uiInterface.ThreadSafeMessageBox(
"SSL mode for RPC (-rpcssl) is no longer supported.", "",
CClientUIInterface::MSG_ERROR);
return false;
}
// Redirect libevent's logging to our own log
event_set_log_callback(&libevent_log_cb);
#if LIBEVENT_VERSION_NUMBER >= 0x02010100
// If -debug=libevent, set full libevent debugging.
// Otherwise, disable all libevent debugging.
if (LogAcceptCategory(BCLog::LIBEVENT)) {
event_enable_debug_logging(EVENT_DBG_ALL);
} else {
event_enable_debug_logging(EVENT_DBG_NONE);
}
#endif
#ifdef WIN32
evthread_use_windows_threads();
#else
evthread_use_pthreads();
#endif
// XXX RAII
base = event_base_new();
if (!base) {
LogPrintf("Couldn't create an event_base: exiting\n");
return false;
}
/* Create a new evhttp object to handle requests. */
// XXX RAII
http = evhttp_new(base);
if (!http) {
LogPrintf("couldn't create evhttp. Exiting.\n");
event_base_free(base);
return false;
}
evhttp_set_timeout(
http, gArgs.GetArg("-rpcservertimeout", DEFAULT_HTTP_SERVER_TIMEOUT));
evhttp_set_max_headers_size(http, MAX_HEADERS_SIZE);
evhttp_set_max_body_size(http, GetMaxBodySizeSafe(config.GetMaxBlockSize()));
evhttp_set_gencb(http, http_request_cb, &config);
// Only POST and OPTIONS are supported, but we return HTTP 405 for the
// others
evhttp_set_allowed_methods(http,
EVHTTP_REQ_GET | EVHTTP_REQ_POST |
EVHTTP_REQ_HEAD | EVHTTP_REQ_PUT |
EVHTTP_REQ_DELETE | EVHTTP_REQ_OPTIONS);
if (!HTTPBindAddresses(http)) {
LogPrintf("Unable to bind any endpoint for RPC server\n");
evhttp_free(http);
event_base_free(base);
return false;
}
eventBase = base;
eventHTTP = http;
LogPrint(BCLog::HTTP, "Initialized HTTP server\n");
int rpcThreads = std::max(static_cast<long>(gArgs.GetArg("-rpcthreads", DEFAULT_HTTP_THREADS)), 1L);
LogPrintf("HTTP: creating work queue with %d threads\n", rpcThreads);
pWorkQueue = std::make_unique<CThreadPool<CQueueAdaptor>>(true, "HTTPServer", rpcThreads);
return true;
}
std::thread threadHTTP;
std::future<bool> threadResult;
bool StartHTTPServer() {
LogPrint(BCLog::HTTP, "Starting HTTP server\n");
std::packaged_task<bool(event_base *, evhttp *)> task(ThreadHTTP);
threadResult = task.get_future();
threadHTTP = std::thread(std::move(task), eventBase, eventHTTP);
return true;
}
void InterruptHTTPServer() {
LogPrint(BCLog::HTTP, "Interrupting HTTP server\n");
if (eventHTTP) {
// Unlisten sockets
for (evhttp_bound_socket *socket : boundSockets) {
evhttp_del_accept_socket(eventHTTP, socket);
}
// Reject requests on current connections
evhttp_set_gencb(eventHTTP, http_reject_request_cb, nullptr);
}
if (pWorkQueue)
pWorkQueue->pause();
}
void StopHTTPServer() {
LogPrint(BCLog::HTTP, "Stopping HTTP server\n");
if (pWorkQueue) {
LogPrint(BCLog::HTTP, "Waiting for HTTP worker threads to exit\n");
pWorkQueue.reset();
}
if (eventBase) {
LogPrint(BCLog::HTTP, "Waiting for HTTP event thread to exit\n");
// Give event loop a few seconds to exit (to send back last RPC
// responses), then break it. Before this was solved with
// event_base_loopexit, but that didn't work as expected in at least
// libevent 2.0.21 and always introduced a delay. In libevent master
// that appears to be solved, so in the future that solution could be
// used again (if desirable).
// (see discussion in https://github.com/bitcoin/bitcoin/pull/6990)
if (threadResult.valid() &&
threadResult.wait_for(std::chrono::milliseconds(2000)) ==
std::future_status::timeout) {
LogPrintf("HTTP event loop did not exit within allotted time, "
"sending loopbreak\n");
event_base_loopbreak(eventBase);
}
threadHTTP.join();
}
if (eventHTTP) {
evhttp_free(eventHTTP);
eventHTTP = 0;
}
if (eventBase) {
event_base_free(eventBase);
eventBase = 0;
}
LogPrint(BCLog::HTTP, "Stopped HTTP server\n");
}
struct event_base *EventBase() {
return eventBase;
}
// this callback is called after successful or failed transmission
static void httpevent_callback_fn(evutil_socket_t, short, void *data) {
// Static handler: simply call inner handler
HTTPEvent *self = ((HTTPEvent *)data);
self->handler();
if (self->deleteWhenTriggered) delete self;
}
HTTPEvent::HTTPEvent(struct event_base *base, bool _deleteWhenTriggered,
const std::function<void(void)> &_handler)
: deleteWhenTriggered(_deleteWhenTriggered), handler(_handler) {
ev = event_new(base, -1, 0, httpevent_callback_fn, this);
assert(ev);
}
HTTPEvent::~HTTPEvent() {
event_free(ev);
}
void HTTPEvent::trigger(struct timeval *tv) {
if (tv == nullptr) {
// Immediately trigger event in main thread.
event_active(ev, 0, 0);
} else {
// Trigger after timeval passed.
evtimer_add(ev, tv);
}
}
HTTPRequest::HTTPRequest(struct evhttp_request *_req)
: req(_req), replySent(false) {}
HTTPRequest::~HTTPRequest() {
if (!replySent) {
// Keep track of whether reply was sent to avoid request leaks
LogPrintf("%s: Unhandled request\n", __func__);
WriteReply(HTTP_INTERNAL, "Unhandled request");
}
// evhttpd cleans up the request, as long as a reply was sent.
}
std::pair<bool, std::string> HTTPRequest::GetHeader(const std::string &hdr) {
const struct evkeyvalq *headers = evhttp_request_get_input_headers(req);
assert(headers);
const char *val = evhttp_find_header(headers, hdr.c_str());
if (val)
return std::make_pair(true, val);
else
return std::make_pair(false, "");
}
std::string HTTPRequest::ReadBody() {
struct evbuffer *buf = evhttp_request_get_input_buffer(req);
if (!buf) return "";
size_t size = evbuffer_get_length(buf);
/** Trivial implementation: if this is ever a performance bottleneck,
* internal copying can be avoided in multi-segment buffers by using
* evbuffer_peek and an awkward loop. Though in that case, it'd be even
* better to not copy into an intermediate string but use a stream
* abstraction to consume the evbuffer on the fly in the parsing algorithm.
*/
const char *data = (const char *)evbuffer_pullup(buf, size);
// returns nullptr in case of empty buffer.
if (!data) {
return "";
}
std::string rv(data, size);
evbuffer_drain(buf, size);
return rv;
}
void HTTPRequest::WriteHeader(const std::string &hdr,
const std::string &value) {
struct evkeyvalq *headers = evhttp_request_get_output_headers(req);
assert(headers);
evhttp_add_header(headers, hdr.c_str(), value.c_str());
}
/** Closure sent to main thread to request a reply to be sent to a HTTP request.
* Replies must be sent in the main loop in the main http thread, this cannot be
* done from worker threads.
*/
void HTTPRequest::WriteReply(int nStatus, const std::string &strReply) {
assert(!replySent && req);
// Send event to main http thread to send reply message
struct evbuffer *evb = evhttp_request_get_output_buffer(req);
assert(evb);
evbuffer_add(evb, strReply.data(), strReply.size());
HTTPEvent *ev =
new HTTPEvent(eventBase, true, std::bind(evhttp_send_reply, req,
nStatus, (const char *)nullptr,
(struct evbuffer *)nullptr));
ev->trigger(0);
replySent = true;
// transferred back to main thread.
req = 0;
}
void HTTPRequest::StartWritingChunks(int nStatus) {
HTTPEvent *ev = new HTTPEvent(eventBase, true, std::bind(evhttp_send_reply_start, req, nStatus, (const char *)nullptr));
ev->trigger(nullptr);
}
void HTTPRequest::WriteReplyChunk(std::string_view strReply) {
struct evbuffer *evb = evbuffer_new();
evbuffer_add(evb, strReply.data(), strReply.length());
// Send event to main http thread to send reply message
HTTPEvent *ev = new HTTPEvent(eventBase, true, std::bind(evhttp_send_reply_chunk, req, evb));
ev->trigger(nullptr);
HTTPEvent *evDel = new HTTPEvent(eventBase, true, std::bind(evbuffer_free, evb));
evDel->trigger(nullptr);
}
void HTTPRequest::StopWritingChunks() {
HTTPEvent *ev = new HTTPEvent(eventBase, true, std::bind(evhttp_send_reply_end, req));
ev->trigger(nullptr);
replySent = true;
req = 0;
}
CService HTTPRequest::GetPeer() {
evhttp_connection *con = evhttp_request_get_connection(req);
CService peer;
if (con) {
// evhttp retains ownership over returned address string
char * address = nullptr;
uint16_t port = 0;
evhttp_connection_get_peer(con, &address, &port);
peer = LookupNumeric(address, port);
}
return peer;
}
std::string HTTPRequest::GetURI() {
return evhttp_request_get_uri(req);
}
HTTPRequest::RequestMethod HTTPRequest::GetRequestMethod() {
switch (evhttp_request_get_command(req)) {
case EVHTTP_REQ_GET:
return GET;
case EVHTTP_REQ_POST:
return POST;
case EVHTTP_REQ_HEAD:
return HEAD;
case EVHTTP_REQ_PUT:
return PUT;
case EVHTTP_REQ_OPTIONS:
return OPTIONS;
default:
return UNKNOWN;
}
}
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch,
const HTTPRequestHandler &handler) {
LogPrint(BCLog::HTTP, "Registering HTTP handler for %s (exactmatch %d)\n",
prefix, exactMatch);
pathHandlers.push_back(HTTPPathHandler(prefix, exactMatch, handler));
}
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch) {
std::vector<HTTPPathHandler>::iterator i = pathHandlers.begin();
std::vector<HTTPPathHandler>::iterator iend = pathHandlers.end();
for (; i != iend; ++i)
if (i->prefix == prefix && i->exactMatch == exactMatch) break;
if (i != iend) {
LogPrint(BCLog::HTTP,
"Unregistering HTTP handler for %s (exactmatch %d)\n", prefix,
exactMatch);
pathHandlers.erase(i);
}
}