Debian Codegraph @

monero/contrib/epee/include/net/abstract_tcp_server2.h

raw symbols SCIP
1 /**
2 @file
3 @author from CrypoNote (see copyright below; Andrey N. Sabelnikov)
4 @monero rfree
5 @brief the connection templated-class for one peer connection
6 */
7 // Copyright (c) 2006-2013, Andrey N. Sabelnikov, www.sabelnikov.net
8 // All rights reserved.
9 //
10 // Redistribution and use in source and binary forms, with or without
11 // modification, are permitted provided that the following conditions are met:
12 // * Redistributions of source code must retain the above copyright
13 // notice, this list of conditions and the following disclaimer.
14 // * Redistributions in binary form must reproduce the above copyright
15 // notice, this list of conditions and the following disclaimer in the
16 // documentation and/or other materials provided with the distribution.
17 // * Neither the name of the Andrey N. Sabelnikov nor the
18 // names of its contributors may be used to endorse or promote products
19 // derived from this software without specific prior written permission.
20 //
21 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
22 // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23 // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
24 // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER BE LIABLE FOR ANY
25 // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26 // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
28 // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
30 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 //
32
33
34
35 #ifndef _ABSTRACT_TCP_SERVER2_H_
36 #define _ABSTRACT_TCP_SERVER2_H_
37
38
39 #include <string>
40 #include <vector>
41 #include <boost/noncopyable.hpp>
42 #include <boost/shared_ptr.hpp>
43 #include <atomic>
44 #include <cassert>
45 #include <map>
46 #include <memory>
47 #include <condition_variable>
48
49 #include <boost/asio.hpp>
50 #include <boost/asio/post.hpp>
51 #include <boost/asio/ssl.hpp>
52 #include <boost/asio/strand.hpp>
53 #include <boost/asio/steady_timer.hpp>
54 #include <boost/array.hpp>
55 #include <boost/enable_shared_from_this.hpp>
56 #include <boost/thread/thread.hpp>
57 #include <boost/optional.hpp>
58 #include "byte_slice.h"
59 #include "net_utils_base.h"
60 #include "syncobj.h"
61 #include "connection_basic.hpp"
62 #include "network_throttle-detail.hpp"
63
64 #undef MONERO_DEFAULT_LOG_CATEGORY
65 #define MONERO_DEFAULT_LOG_CATEGORY "net"
66
67 #define ABSTRACT_SERVER_SEND_QUE_MAX_COUNT 1000
68 #define ABSTRACT_SERVER_SEND_QUE_MAX_BYTES_DEFAULT 100 * 1024 * 1024
69
70 namespace epee
71 {
72 namespace net_utils
73 {
74
75 struct i_connection_filter
76 {
77 virtual bool is_remote_host_allowed(const epee::net_utils::network_address &address, time_t *t = NULL)=0;
78 protected:
79 virtual ~i_connection_filter(){}
80 };
81
82 struct i_connection_limit
83 {
84 virtual bool is_host_limit(const epee::net_utils::network_address &address)=0;
85 protected:
86 virtual ~i_connection_limit(){}
87 };
88
89
90 /************************************************************************/
91 /* */
92 /************************************************************************/
93 /// Represents a single connection from a client.
94 template<class t_protocol_handler>
95 class connection
96 : public boost::enable_shared_from_this<connection<t_protocol_handler> >,
97 private boost::noncopyable,
98 public i_service_endpoint,
99 public connection_basic
100 {
101 public:
102 typedef typename t_protocol_handler::connection_context t_connection_context;
103 private:
104 using connection_t = connection<t_protocol_handler>;
105 using connection_ptr = boost::shared_ptr<connection_t>;
106 using ssl_support_t = epee::net_utils::ssl_support_t;
107 using timer_t = boost::asio::steady_timer;
108 using duration_t = timer_t::duration;
109 using ec_t = boost::system::error_code;
110 using handshake_t = boost::asio::ssl::stream_base::handshake_type;
111
112 using io_context_t = boost::asio::io_context;
113 using strand_t = io_context_t::strand;
114 using socket_t = boost::asio::ip::tcp::socket;
115
116 using network_throttle_t = epee::net_utils::network_throttle;
117 using network_throttle_manager_t = epee::net_utils::network_throttle_manager;
118
119 unsigned int host_count(int delta = 0);
120 duration_t get_default_timeout();
121 duration_t get_timeout_from_bytes_read(size_t bytes) const;
122
123 void state_status_check();
124
125 void start_timer(duration_t duration, bool add = {});
126 void async_wait_timer();
127 void cancel_timer();
128
129 void start_handshake();
130 void start_read();
131 void start_write();
132 void start_shutdown();
133 void cancel_socket();
134
135 void cancel_handler();
136
137 void interrupt();
138 void on_interrupted();
139
140 void terminate();
141 void on_terminating();
142
143 bool send(epee::byte_slice message);
144 bool start_internal(
145 bool is_income,
146 bool is_multithreaded,
147 boost::optional<network_address> real_remote
148 );
149
150 enum status_t {
151 TERMINATED,
152 RUNNING,
153 INTERRUPTED,
154 TERMINATING,
155 WASTED,
156 };
157
158 struct state_t {
159 struct stat_t {
160 struct {
161 network_throttle_t throttle{"speed_in", "throttle_speed_in"};
162 } in;
163 struct {
164 network_throttle_t throttle{"speed_out", "throttle_speed_out"};
165 } out;
166 };
167
168 struct data_t {
169 struct {
170 std::array<uint8_t, 0x2000> buffer;
171 } read;
172 struct {
173 std::deque<epee::byte_slice> queue;
174 std::size_t total_bytes;
175 bool wait_consume;
176 } write;
177 };
178
179 struct ssl_t {
180 bool enabled;
181 bool forced;
182 bool detected;
183 bool handshaked;
184 };
185
186 struct socket_status_t {
187 bool connected;
188
189 bool wait_handshake;
190 bool cancel_handshake;
191
192 bool wait_read;
193 bool handle_read;
194 bool cancel_read;
195
196 bool wait_write;
197 bool handle_write;
198 bool cancel_write;
199
200 bool wait_shutdown;
201 bool cancel_shutdown;
202 };
203
204 struct timer_status_t {
205 bool wait_expire;
206 bool cancel_expire;
207 bool reset_expire;
208 };
209
210 struct timers_status_t {
211 struct throttle_t {
212 timer_status_t in;
213 timer_status_t out;
214 };
215
216 timer_status_t general;
217 throttle_t throttle;
218 };
219
220 struct protocol_t {
221 size_t reference_counter;
222 bool released;
223 bool initialized;
224
225 bool wait_release;
226 bool wait_init;
227 size_t wait_callback;
228 };
229
230 std::mutex lock;
231 std::condition_variable_any condition;
232 status_t status;
233 socket_status_t socket;
234 ssl_t ssl;
235 timers_status_t timers;
236 protocol_t protocol;
237 stat_t stat;
238 data_t data;
239 };
240
241 struct timers_t {
242 timers_t(io_context_t &io_context):
243 general(io_context),
244 throttle(io_context)
245 {}
246 struct throttle_t {
247 throttle_t(io_context_t &io_context):
248 in(io_context),
249 out(io_context)
250 {}
251 timer_t in;
252 timer_t out;
253 };
254
255 timer_t general;
256 throttle_t throttle;
257 };
258
259 io_context_t &m_io_context;
260 t_connection_type m_connection_type;
261 t_connection_context m_conn_context{};
262 strand_t m_strand;
263 timers_t m_timers;
264 connection_ptr self{};
265 bool m_local{};
266 std::string m_host{};
267 state_t m_state{};
268 t_protocol_handler m_handler;
269 public:
270 struct shared_state : connection_basic_shared_state, t_protocol_handler::config_type
271 {
272 shared_state()
273 : connection_basic_shared_state(),
274 t_protocol_handler::config_type(),
275 pfilter(nullptr),
276 plimit(nullptr),
277 response_soft_limit(ABSTRACT_SERVER_SEND_QUE_MAX_BYTES_DEFAULT),
278 stop_signal_sent(false)
279 {}
280
281 i_connection_filter* pfilter;
282 i_connection_limit* plimit;
283 std::size_t response_soft_limit;
284 bool stop_signal_sent;
285 };
286
287 /// Construct a connection with the given io_context.
288 explicit connection( io_context_t& io_context,
289 std::shared_ptr<shared_state> state,
290 t_connection_type connection_type,
291 epee::net_utils::ssl_support_t ssl_support);
292
293 explicit connection( io_context_t& io_context,
294 boost::asio::ip::tcp::socket&& sock,
295 std::shared_ptr<shared_state> state,
296 t_connection_type connection_type,
297 epee::net_utils::ssl_support_t ssl_support);
298
299
300
301 virtual ~connection() noexcept(false);
302
303 /// Start the first asynchronous operation for the connection.
304 bool start(bool is_income, bool is_multithreaded);
305
306 // `real_remote` is the actual endpoint (if connection is to proxy, etc.)
307 bool start(bool is_income, bool is_multithreaded, network_address real_remote);
308
309 void get_context(t_connection_context& context_){context_ = m_conn_context;}
310
311 void call_back_starter();
312
313 void save_dbg_log();
314
315
316 bool speed_limit_is_enabled() const; ///< tells us should we be sleeping here (e.g. do not sleep on RPC connections)
317
318 bool cancel();
319
320 private:
321 //----------------- i_service_endpoint ---------------------
322 virtual bool do_send(byte_slice message); ///< (see do_send from i_service_endpoint)
323 virtual bool send_done();
324 virtual bool close();
325 virtual bool call_run_once_service_io();
326 virtual bool request_callback();
327 virtual io_context_t& get_io_context();
328 virtual bool add_ref();
329 virtual bool release();
330 //------------------------------------------------------
331 public:
332 void setRpcStation();
333 };
334
335
336 /************************************************************************/
337 /* */
338 /************************************************************************/
339 template<class t_protocol_handler>
340 class boosted_tcp_server
341 : private boost::noncopyable
342 {
343 enum try_connect_result_t
344 {
345 CONNECT_SUCCESS,
346 CONNECT_FAILURE,
347 CONNECT_NO_SSL,
348 };
349
350 public:
351 typedef boost::shared_ptr<connection<t_protocol_handler> > connection_ptr;
352 typedef typename t_protocol_handler::connection_context t_connection_context;
353 /// Construct the server to listen on the specified TCP address and port, and
354 /// serve up files from the given directory.
355
356 boosted_tcp_server(t_connection_type connection_type);
357 explicit boosted_tcp_server(boost::asio::io_context& external_io_context, t_connection_type connection_type);
358 ~boosted_tcp_server();
359
360 std::map<std::string, t_connection_type> server_type_map;
361 void create_server_type_map();
362
363 bool init_server(uint32_t port, const std::string& address = "0.0.0.0",
364 uint32_t port_ipv6 = 0, const std::string& address_ipv6 = "::", bool use_ipv6 = false, bool require_ipv4 = true,
365 ssl_options_t ssl_options = ssl_support_t::e_ssl_support_autodetect);
366 bool init_server(const std::string port, const std::string& address = "0.0.0.0",
367 const std::string port_ipv6 = "", const std::string address_ipv6 = "::", bool use_ipv6 = false, bool require_ipv4 = true,
368 ssl_options_t ssl_options = ssl_support_t::e_ssl_support_autodetect);
369
370 /// Run the server's io_context loop.
371 bool run_server(size_t threads_count, bool wait = true, const boost::thread::attributes& attrs = boost::thread::attributes());
372
373 /// wait for service workers stop
374 bool timed_wait_server_stop(uint64_t wait_mseconds);
375
376 /// Stop the server.
377 void send_stop_signal();
378
379 bool is_stop_signal_sent() const noexcept { return m_stop_signal_sent; };
380
381 const std::atomic<bool>& get_stop_signal() const noexcept { return m_stop_signal_sent; }
382
383 void set_threads_prefix(const std::string& prefix_name);
384
385 bool deinit_server(){return true;}
386
387 size_t get_threads_count(){return m_threads_count;}
388
389 void set_connection_filter(i_connection_filter* pfilter);
390 void set_connection_limit(i_connection_limit* plimit);
391 void set_response_soft_limit(std::size_t limit);
392
393 void set_default_remote(epee::net_utils::network_address remote)
394 {
395 default_remote = std::move(remote);
396 }
397
398 bool add_connection(t_connection_context& out, boost::asio::ip::tcp::socket&& sock, network_address real_remote, epee::net_utils::ssl_support_t ssl_support = epee::net_utils::ssl_support_t::e_ssl_support_autodetect);
399 try_connect_result_t try_connect(connection_ptr new_connection_l, const std::string& adr, const std::string& port, boost::asio::ip::tcp::socket &sock_, const boost::asio::ip::tcp::endpoint &remote_endpoint, const std::string &bind_ip, uint32_t conn_timeout, epee::net_utils::ssl_support_t ssl_support);
400 bool connect(const std::string& adr, const std::string& port, uint32_t conn_timeot, t_connection_context& cn, const std::string& bind_ip = "0.0.0.0", epee::net_utils::ssl_support_t ssl_support = epee::net_utils::ssl_support_t::e_ssl_support_autodetect);
401 template<class t_callback>
402 bool connect_async(const std::string& adr, const std::string& port, uint32_t conn_timeot, const t_callback &cb, const std::string& bind_ip = "0.0.0.0", epee::net_utils::ssl_support_t ssl_support = epee::net_utils::ssl_support_t::e_ssl_support_autodetect);
403
404 boost::asio::ssl::context& get_ssl_context() noexcept
405 {
406 assert(m_state != nullptr);
407 return m_state->ssl_context;
408 }
409
410 typename t_protocol_handler::config_type& get_config_object()
411 {
412 assert(m_state != nullptr); // always set in constructor
413 return *m_state;
414 }
415
416 std::shared_ptr<typename t_protocol_handler::config_type> get_config_shared()
417 {
418 assert(m_state != nullptr); // always set in constructor
419 return {m_state};
420 }
421
422 int get_binded_port(){return m_port;}
423 int get_binded_port_ipv6(){return m_port_ipv6;}
424
425 long get_connections_count() const
426 {
427 assert(m_state != nullptr); // always set in constructor
428 auto connections_count = m_state->sock_count > 0 ? (m_state->sock_count - 1) : 0; // Socket count minus listening socket
429 return connections_count;
430 }
431
432 boost::asio::io_context& get_io_context(){return io_context_;}
433
434 struct idle_callback_conext_base
435 {
436 virtual ~idle_callback_conext_base(){}
437
438 virtual bool call_handler(){return true;}
439
440 idle_callback_conext_base(boost::asio::io_context& io_serice):
441 m_timer(io_serice)
442 {}
443 boost::asio::deadline_timer m_timer;
444 };
445
446 template <class t_handler>
447 struct idle_callback_conext: public idle_callback_conext_base
448 {
449 idle_callback_conext(boost::asio::io_context& io_serice, t_handler& h, uint64_t period):
450 idle_callback_conext_base(io_serice),
451 m_handler(h)
452 {this->m_period = period;}
453
454 t_handler m_handler;
455 virtual bool call_handler()
456 {
457 return m_handler();
458 }
459 uint64_t m_period;
460 };
461
462 template<class t_handler>
463 bool add_idle_handler(t_handler t_callback, uint64_t timeout_ms)
464 {
465 boost::shared_ptr<idle_callback_conext<t_handler>> ptr(new idle_callback_conext<t_handler>(io_context_, t_callback, timeout_ms));
466 //needed call handler here ?...
467 ptr->m_timer.expires_from_now(boost::posix_time::milliseconds(ptr->m_period));
468 ptr->m_timer.async_wait(boost::bind(&boosted_tcp_server<t_protocol_handler>::global_timer_handler<t_handler>, this, ptr));
469 return true;
470 }
471
472 template<class t_handler>
473 bool global_timer_handler(/*const boost::system::error_code& err, */boost::shared_ptr<idle_callback_conext<t_handler>> ptr)
474 {
475 //if handler return false - he don't want to be called anymore
476 if(!ptr->call_handler())
477 return true;
478 ptr->m_timer.expires_from_now(boost::posix_time::milliseconds(ptr->m_period));
479 ptr->m_timer.async_wait(boost::bind(&boosted_tcp_server<t_protocol_handler>::global_timer_handler<t_handler>, this, ptr));
480 return true;
481 }
482
483 template<class t_handler>
484 bool async_call(t_handler&& t_callback)
485 {
486 boost::asio::post(io_context_, std::forward<t_handler>(t_callback));
487 return true;
488 }
489
490 private:
491 /// Run the server's io_context loop.
492 bool worker_thread();
493 /// Handle completion of an asynchronous accept operation.
494 void handle_accept_ipv4(const boost::system::error_code& e);
495 void handle_accept_ipv6(const boost::system::error_code& e);
496 void handle_accept(const boost::system::error_code& e, bool ipv6 = false);
497
498 bool is_thread_worker();
499
500 const std::shared_ptr<typename connection<t_protocol_handler>::shared_state> m_state;
501
502 /// The io_context used to perform asynchronous operations.
503 struct worker
504 {
505 worker()
506 : io_context(), work(io_context.get_executor())
507 {}
508
509 boost::asio::io_context io_context;
510 boost::asio::executor_work_guard<boost::asio::io_context::executor_type> work;
511 };
512 std::unique_ptr<worker> m_io_context_local_instance;
513 boost::asio::io_context& io_context_;
514
515 /// Acceptor used to listen for incoming connections.
516 boost::asio::ip::tcp::acceptor acceptor_;
517 boost::asio::ip::tcp::acceptor acceptor_ipv6;
518 epee::net_utils::network_address default_remote;
519
520 std::atomic<bool> m_stop_signal_sent;
521 uint32_t m_port;
522 uint32_t m_port_ipv6;
523 std::string m_address;
524 std::string m_address_ipv6;
525 bool m_use_ipv6;
526 bool m_require_ipv4;
527 std::string m_thread_name_prefix; //TODO: change to enum server_type, now used
528 size_t m_threads_count;
529 std::vector<boost::shared_ptr<boost::thread> > m_threads;
530 boost::thread::id m_main_thread_id;
531 critical_section m_threads_lock;
532 std::atomic<uint32_t> m_thread_index;
533
534 t_connection_type m_connection_type;
535
536 /// The next connection to be accepted
537 connection_ptr new_connection_;
538 connection_ptr new_connection_ipv6;
539
540
541 boost::mutex connections_mutex;
542 std::set<connection_ptr> connections_;
543 }; // class <>boosted_tcp_server
544
545
546 } // namespace
547 } // namespace
548
549 #include "abstract_tcp_server2.inl"
550
551 #endif