-
Notifications
You must be signed in to change notification settings - Fork 30
/
Door.h
416 lines (375 loc) · 11.8 KB
/
Door.h
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
//------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef RIPPLE_SERVER_DOOR_H_INCLUDED
#define RIPPLE_SERVER_DOOR_H_INCLUDED
#include <ripple/server/impl/io_list.h>
#include <ripple/basics/contract.h>
#include <ripple/basics/Log.h>
#include <ripple/server/impl/PlainHTTPPeer.h>
#include <ripple/server/impl/SSLHTTPPeer.h>
#include <ripple/beast/asio/ssl_bundle.h>
#include <boost/beast/core/multi_buffer.hpp>
#include <boost/asio/basic_waitable_timer.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/container/flat_map.hpp>
#include <chrono>
#include <condition_variable>
#include <functional>
#include <memory>
#include <mutex>
namespace ripple {
/** A listening socket. */
template<class Handler>
class Door
: public io_list::work
, public std::enable_shared_from_this<Door<Handler>>
{
private:
using clock_type = std::chrono::steady_clock;
using timer_type = boost::asio::basic_waitable_timer<clock_type>;
using error_code = boost::system::error_code;
using yield_context = boost::asio::yield_context;
using protocol_type = boost::asio::ip::tcp;
using acceptor_type = protocol_type::acceptor;
using endpoint_type = protocol_type::endpoint;
using socket_type = protocol_type::socket;
// Detects SSL on a socket
class Detector
: public io_list::work
, public std::enable_shared_from_this<Detector>
{
private:
Port const& port_;
Handler& handler_;
boost::asio::io_context& ioc_;
socket_type socket_;
timer_type timer_;
endpoint_type remote_address_;
boost::asio::io_context::strand strand_;
beast::Journal j_;
public:
Detector(
Port const& port,
Handler& handler,
boost::asio::io_context& ioc,
socket_type&& socket,
endpoint_type remote_address,
beast::Journal j);
void run();
void close() override;
private:
void do_timer (yield_context yield);
void do_detect (yield_context yield);
};
beast::Journal j_;
Port const& port_;
Handler& handler_;
boost::asio::io_context& ioc_;
acceptor_type acceptor_;
boost::asio::io_context::strand strand_;
bool ssl_;
bool plain_;
public:
Door(Handler& handler, boost::asio::io_context& io_context,
Port const& port, beast::Journal j);
// Work-around because we can't call shared_from_this in ctor
void run();
/** Close the Door listening socket and connections.
The listening socket is closed, and all open connections
belonging to the Door are closed.
Thread Safety:
May be called concurrently
*/
void close() override;
endpoint_type get_endpoint() const
{
return acceptor_.local_endpoint();
}
private:
template <class ConstBufferSequence>
void create (bool ssl, ConstBufferSequence const& buffers,
socket_type&& socket, endpoint_type remote_address);
void do_accept (yield_context yield);
};
/** Detect SSL client handshakes.
Analyzes the bytes in the provided buffer to detect the SSL client
handshake. If the buffer contains insufficient data, more data will be
read from the stream until there is enough to determine a result.
No bytes are discarded from buf. Any additional bytes read are retained.
buf must provide an interface compatible with boost::asio::streambuf
http://boost.org/doc/libs/1_56_0/doc/html/boost_asio/reference/streambuf.html
See
http://www.ietf.org/rfc/rfc2246.txt
Section 7.4. Handshake protocol
@param socket The stream to read from
@param buf A buffer to hold the received data
@param do_yield A do_yield context
@return The error code if an error occurs, otherwise `true` if
the data read indicates the SSL client handshake.
*/
template <class Socket, class StreamBuf, class Yield>
std::pair <boost::system::error_code, bool>
detect_ssl (Socket& socket, StreamBuf& buf, Yield do_yield)
{
std::pair <boost::system::error_code, bool> result;
result.second = false;
for(;;)
{
std::size_t const max = 4; // the most bytes we could need
unsigned char data[max];
auto const bytes = boost::asio::buffer_copy (
boost::asio::buffer(data), buf.data());
if (bytes > 0)
{
if (data[0] != 0x16) // message type 0x16 = "SSL Handshake"
break;
}
if (bytes >= max)
{
result.second = true;
break;
}
buf.commit(boost::asio::async_read (socket,
buf.prepare(max - bytes), boost::asio::transfer_at_least(1),
do_yield[result.first]));
if (result.first)
break;
}
return result;
}
template <class Handler>
Door<Handler>::Detector::Detector(
Port const& port,
Handler& handler,
boost::asio::io_context& ioc,
socket_type&& socket,
endpoint_type remote_address,
beast::Journal j)
: port_(port)
, handler_(handler)
, ioc_(ioc)
, socket_(std::move(socket))
, timer_(ioc_)
, remote_address_(remote_address)
, strand_(ioc_)
, j_(j)
{
}
template<class Handler>
void
Door<Handler>::Detector::
run()
{
// do_detect must be called before do_timer or else
// the timer can be canceled before it gets set.
boost::asio::spawn(strand_, std::bind (&Detector::do_detect,
this->shared_from_this(), std::placeholders::_1));
boost::asio::spawn(strand_, std::bind (&Detector::do_timer,
this->shared_from_this(), std::placeholders::_1));
}
template<class Handler>
void
Door<Handler>::Detector::
close()
{
error_code ec;
socket_.close(ec);
timer_.cancel(ec);
}
template<class Handler>
void
Door<Handler>::Detector::
do_timer(yield_context do_yield)
{
error_code ec; // ignored
while (socket_.is_open())
{
timer_.async_wait (do_yield[ec]);
if (timer_.expires_from_now() <= std::chrono::seconds(0))
socket_.close(ec);
}
}
template<class Handler>
void
Door<Handler>::Detector::
do_detect(boost::asio::yield_context do_yield)
{
bool ssl;
error_code ec;
boost::beast::multi_buffer buf(16);
timer_.expires_from_now(std::chrono::seconds(15));
std::tie(ec, ssl) = detect_ssl(socket_, buf, do_yield);
error_code unused;
timer_.cancel(unused);
if (! ec)
{
if (ssl)
{
if (auto sp = ios().template emplace<SSLHTTPPeer<Handler>>(
port_, handler_, ioc_, j_, remote_address_,
buf.data(), std::move(socket_)))
sp->run();
return;
}
if (auto sp = ios().template emplace<PlainHTTPPeer<Handler>>(
port_, handler_, ioc_, j_, remote_address_,
buf.data(), std::move(socket_)))
sp->run();
return;
}
if (ec != boost::asio::error::operation_aborted)
{
JLOG(j_.trace()) <<
"Error detecting ssl: " << ec.message() <<
" from " << remote_address_;
}
}
//------------------------------------------------------------------------------
template<class Handler>
Door<Handler>::
Door(Handler& handler, boost::asio::io_context& io_context,
Port const& port, beast::Journal j)
: j_(j)
, port_(port)
, handler_(handler)
, ioc_(io_context)
, acceptor_(io_context)
, strand_(io_context)
, ssl_(
port_.protocol.count("https") > 0 ||
port_.protocol.count("wss") > 0 ||
port_.protocol.count("wss2") > 0 ||
port_.protocol.count("peer") > 0)
, plain_(
port_.protocol.count("http") > 0 ||
port_.protocol.count("ws") > 0 ||
port_.protocol.count("ws2"))
{
error_code ec;
endpoint_type const local_address =
endpoint_type(port.ip, port.port);
acceptor_.open(local_address.protocol(), ec);
if (ec)
{
JLOG(j_.error()) <<
"Open port '" << port.name << "' failed:" << ec.message();
Throw<std::exception> ();
}
acceptor_.set_option(
boost::asio::ip::tcp::acceptor::reuse_address(true), ec);
if (ec)
{
JLOG(j_.error()) <<
"Option for port '" << port.name << "' failed:" << ec.message();
Throw<std::exception> ();
}
acceptor_.bind(local_address, ec);
if (ec)
{
JLOG(j_.error()) <<
"Bind port '" << port.name << "' failed:" << ec.message();
Throw<std::exception> ();
}
acceptor_.listen(boost::asio::socket_base::max_connections, ec);
if (ec)
{
JLOG(j_.error()) <<
"Listen on port '" << port.name << "' failed:" << ec.message();
Throw<std::exception> ();
}
JLOG(j_.info()) <<
"Opened " << port;
}
template<class Handler>
void
Door<Handler>::
run()
{
boost::asio::spawn(strand_, std::bind(&Door<Handler>::do_accept,
this->shared_from_this(), std::placeholders::_1));
}
template<class Handler>
void
Door<Handler>::
close()
{
if (! strand_.running_in_this_thread())
return strand_.post(std::bind(
&Door<Handler>::close, this->shared_from_this()));
error_code ec;
acceptor_.close(ec);
}
//------------------------------------------------------------------------------
template<class Handler>
template<class ConstBufferSequence>
void
Door<Handler>::
create(bool ssl, ConstBufferSequence const& buffers,
socket_type&& socket, endpoint_type remote_address)
{
if (ssl)
{
if (auto sp = ios().template emplace<SSLHTTPPeer<Handler>>(
port_, handler_, ioc_, j_, remote_address,
buffers, std::move(socket)))
sp->run();
return;
}
if (auto sp = ios().template emplace<PlainHTTPPeer<Handler>>(
port_, handler_, ioc_, j_, remote_address,
buffers, std::move(socket)))
sp->run();
}
template<class Handler>
void
Door<Handler>::
do_accept(boost::asio::yield_context do_yield)
{
while (acceptor_.is_open())
{
error_code ec;
endpoint_type remote_address;
socket_type socket (ioc_);
acceptor_.async_accept (socket, remote_address, do_yield[ec]);
if (ec && ec != boost::asio::error::operation_aborted)
{
JLOG(j_.error()) <<
"accept: " << ec.message();
}
if (ec == boost::asio::error::operation_aborted)
break;
if (ec)
continue;
if (ssl_ && plain_)
{
if (auto sp = ios().template emplace<Detector>(
port_, handler_, ioc_, std::move(socket),
remote_address, j_))
sp->run();
}
else if (ssl_ || plain_)
{
create(ssl_, boost::asio::null_buffers{},
std::move(socket), remote_address);
}
}
}
} // ripple
#endif