Debian Codegraph @

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 handle_read(size_t bytes_transferred);
132 void start_write();
133 void start_shutdown();
134 void cancel_socket();
135
136 void cancel_handler();
137
138 void interrupt();
139 void on_interrupted();
140
141 void terminate();
142 void on_terminating();
143 void terminate_async();
144
145 bool send(epee::byte_slice message);
146 bool start_internal(
147 bool is_income,
148 bool is_multithreaded,
149 boost::optional<network_address> real_remote
150 );
151
152 enum status_t {
153 TERMINATED,
154 RUNNING,
155 INTERRUPTED,
156 TERMINATING,
157 WASTED,
158 };
159
160 struct state_t {
161 struct stat_t {
162 struct {
163 network_throttle_t throttle{"speed_in", "throttle_speed_in"};
164 } in;
165 struct {
166 network_throttle_t throttle{"speed_out", "throttle_speed_out"};
167 } out;
168 };
169
170 struct data_t {
171 struct {
172 std::array<uint8_t, 0x2000> buffer;
173 } read;
174 struct {
175 std::deque<epee::byte_slice> queue;
176 std::size_t total_bytes;
177 bool wait_consume;
178 } write;
179 };
180
181 struct ssl_t {
182 bool enabled;
183 bool forced;
184 bool detected;
185 bool handshaked;
186 };
187
188 struct socket_status_t {
189 bool connected;
190
191 bool wait_handshake;
192 bool cancel_handshake;
193
194 bool wait_read;
195 bool handle_read;
196 bool cancel_read;
197 bool shutdown_read;
198
199 bool wait_write;
200 bool handle_write;
201 bool cancel_write;
202
203 bool wait_shutdown;
204 bool cancel_shutdown;
205 };
206
207 struct timer_status_t {
208 bool wait_expire;
209 bool cancel_expire;
210 bool reset_expire;
211 };
212
213 struct timers_status_t {
214 struct throttle_t {
215 timer_status_t in;
216 timer_status_t out;
217 };
218
219 timer_status_t general;
220 throttle_t throttle;
221 };
222
223 struct protocol_t {
224 size_t reference_counter;
225 bool released;
226 bool initialized;
227
228 bool wait_release;
229 bool wait_init;
230 size_t wait_callback;
231 };
232
233 std::mutex lock;
234 std::condition_variable_any condition;
235 status_t status;
236 socket_status_t socket;
237 ssl_t ssl;
238 timers_status_t timers;
239 protocol_t protocol;
240 stat_t stat;
241 data_t data;
242 };
243
244 struct timers_t {
245 timers_t(io_context_t &io_context):
246 general(io_context),
247 throttle(io_context)
248 {}
249 struct throttle_t {
250 throttle_t(io_context_t &io_context):
251 in(io_context),
252 out(io_context)
253 {}
254 timer_t in;
255 timer_t out;
256 };
257
258 timer_t general;
259 throttle_t throttle;
260 };
261
262 io_context_t &m_io_context;
263 t_connection_type m_connection_type;
264 t_connection_context m_conn_context{};
265 strand_t m_strand;
266 timers_t m_timers;
267 connection_ptr self{};
268 bool m_local{};
269 std::string m_host{};
270 state_t m_state{};
271 t_protocol_handler m_handler;
272 public:
273 struct shared_state : connection_basic_shared_state, t_protocol_handler::config_type
274 {
275 shared_state()
276 : connection_basic_shared_state(),
277 t_protocol_handler::config_type(),
278 pfilter(nullptr),
279 plimit(nullptr),
280 response_soft_limit(ABSTRACT_SERVER_SEND_QUE_MAX_BYTES_DEFAULT),
281 stop_signal_sent(false)
282 {}
283
284 i_connection_filter* pfilter;
285 i_connection_limit* plimit;
286 std::size_t response_soft_limit;
287 bool stop_signal_sent;
288 };
289
290 /// Construct a connection with the given io_context.
291 explicit connection( io_context_t& io_context,
292 std::shared_ptr<shared_state> state,
293 t_connection_type connection_type,
294 epee::net_utils::ssl_support_t ssl_support,
295 t_connection_context&& initial = t_connection_context{});
296
297 explicit connection( io_context_t& io_context,
298 boost::asio::ip::tcp::socket&& sock,
299 std::shared_ptr<shared_state> state,
300 t_connection_type connection_type,
301 epee::net_utils::ssl_support_t ssl_support,
302 t_connection_context&& initial = t_connection_context{});
303
304
305
306 virtual ~connection() noexcept(false);
307
308 /// Start the first asynchronous operation for the connection.
309 bool start(bool is_income, bool is_multithreaded);
310
311 // `real_remote` is the actual endpoint (if connection is to proxy, etc.)
312 bool start(bool is_income, bool is_multithreaded, network_address real_remote);
313
314 void get_context(t_connection_context& context_){context_ = m_conn_context;}
315
316 void call_back_starter();
317
318 void save_dbg_log();
319
320
321 bool speed_limit_is_enabled() const; ///< tells us should we be sleeping here (e.g. do not sleep on RPC connections)
322
323 bool cancel();
324
325 private:
326 //----------------- i_service_endpoint ---------------------
327 virtual bool do_send(byte_slice message); ///< (see do_send from i_service_endpoint)
328 virtual bool send_done();
329 virtual bool close(const bool wait_for_shutdown);
330 virtual bool call_run_once_service_io();
331 virtual bool request_callback();
332 virtual io_context_t& get_io_context();
333 virtual bool add_ref();
334 virtual bool release();
335 //------------------------------------------------------
336 public:
337 void setRpcStation();
338 };
339
340
341 /************************************************************************/
342 /* */
343 /************************************************************************/
344 template<class t_protocol_handler>
345 class boosted_tcp_server
346 : private boost::noncopyable
347 {
348 enum try_connect_result_t
349 {
350 CONNECT_SUCCESS,
351 CONNECT_FAILURE,
352 CONNECT_NO_SSL,
353 };
354
355 public:
356 typedef boost::shared_ptr<connection<t_protocol_handler> > connection_ptr;
357 typedef typename t_protocol_handler::connection_context t_connection_context;
358 /// Construct the server to listen on the specified TCP address and port, and
359 /// serve up files from the given directory.
360
361 boosted_tcp_server(t_connection_type connection_type);
362 explicit boosted_tcp_server(boost::asio::io_context& external_io_context, t_connection_type connection_type);
363 ~boosted_tcp_server();
364
365 std::map<std::string, t_connection_type> server_type_map;
366 void create_server_type_map();
367
368 bool init_server(uint32_t port, const std::string& address = "0.0.0.0",
369 uint32_t port_ipv6 = 0, const std::string& address_ipv6 = "::", bool use_ipv6 = false, bool require_ipv4 = true,
370 ssl_options_t ssl_options = ssl_support_t::e_ssl_support_autodetect);
371 bool init_server(const std::string port, const std::string& address = "0.0.0.0",
372 const std::string port_ipv6 = "", const std::string address_ipv6 = "::", bool use_ipv6 = false, bool require_ipv4 = true,
373 ssl_options_t ssl_options = ssl_support_t::e_ssl_support_autodetect);
374
375 /// Run the server's io_context loop.
376 bool run_server(size_t threads_count, bool wait = true, const boost::thread::attributes& attrs = boost::thread::attributes());
377
378 /// wait for service workers stop
379 bool timed_wait_server_stop(uint64_t wait_mseconds);
380
381 /// Stop the server.
382 void send_stop_signal(std::function<void()> close_all_connections = [](){});
383
384 bool is_stop_signal_sent() const noexcept { return m_stop_signal_sent; };
385
386 const std::atomic<bool>& get_stop_signal() const noexcept { return m_stop_signal_sent; }
387
388 void set_threads_prefix(const std::string& prefix_name);
389
390 bool deinit_server(){return true;}
391
392 size_t get_threads_count(){return m_threads_count;}
393
394 void set_connection_filter(i_connection_filter* pfilter);
395 void set_connection_limit(i_connection_limit* plimit);
396 void set_response_soft_limit(std::size_t limit);
397
398 void set_default_remote(epee::net_utils::network_address remote)
399 {
400 default_remote = std::move(remote);
401 }
402
403 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);
404 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);
405 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);
406 template<class t_callback>
407 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, t_connection_context&& initial = t_connection_context{});
408
409 boost::asio::ssl::context& get_ssl_context() noexcept
410 {
411 assert(m_state != nullptr);
412 return m_state->ssl_context;
413 }
414
415 typename t_protocol_handler::config_type& get_config_object()
416 {
417 assert(m_state != nullptr); // always set in constructor
418 return *m_state;
419 }
420
421 std::shared_ptr<typename t_protocol_handler::config_type> get_config_shared()
422 {
423 assert(m_state != nullptr); // always set in constructor
424 return {m_state};
425 }
426
427 int get_binded_port(){return m_port;}
428 int get_binded_port_ipv6(){return m_port_ipv6;}
429
430 long get_connections_count() const
431 {
432 assert(m_state != nullptr); // always set in constructor
433 auto connections_count = m_state->sock_count > 0 ? (m_state->sock_count - 1) : 0; // Socket count minus listening socket
434 return connections_count;
435 }
436
437 boost::asio::io_context& get_io_context(){return io_context_;}
438
439 struct idle_callback_conext_base
440 {
441 virtual ~idle_callback_conext_base(){}
442
443 virtual bool call_handler(){return true;}
444
445 idle_callback_conext_base(boost::asio::io_context& io_serice):
446 m_timer(io_serice)
447 {}
448 boost::asio::deadline_timer m_timer;
449 };
450
451 template <class t_handler>
452 struct idle_callback_conext: public idle_callback_conext_base
453 {
454 idle_callback_conext(boost::asio::io_context& io_serice, t_handler& h, uint64_t period):
455 idle_callback_conext_base(io_serice),
456 m_handler(h)
457 {this->m_period = period;}
458
459 t_handler m_handler;
460 virtual bool call_handler()
461 {
462 return m_handler();
463 }
464 uint64_t m_period;
465 };
466
467 template<class t_handler>
468 bool add_idle_handler(t_handler t_callback, uint64_t timeout_ms)
469 {
470 boost::shared_ptr<idle_callback_conext<t_handler>> ptr(new idle_callback_conext<t_handler>(io_context_, t_callback, timeout_ms));
471 //needed call handler here ?...
472 ptr->m_timer.expires_from_now(boost::posix_time::milliseconds(ptr->m_period));
473 ptr->m_timer.async_wait(boost::bind(&boosted_tcp_server<t_protocol_handler>::global_timer_handler<t_handler>, this, ptr));
474 return true;
475 }
476
477 template<class t_handler>
478 bool global_timer_handler(/*const boost::system::error_code& err, */boost::shared_ptr<idle_callback_conext<t_handler>> ptr)
479 {
480 //if handler return false - he don't want to be called anymore
481 if(!ptr->call_handler())
482 return true;
483 ptr->m_timer.expires_from_now(boost::posix_time::milliseconds(ptr->m_period));
484 ptr->m_timer.async_wait(boost::bind(&boosted_tcp_server<t_protocol_handler>::global_timer_handler<t_handler>, this, ptr));
485 return true;
486 }
487
488 template<class t_handler>
489 bool async_call(t_handler&& t_callback)
490 {
491 boost::asio::post(io_context_, std::forward<t_handler>(t_callback));
492 return true;
493 }
494
495 private:
496 /// Run the server's io_context loop.
497 bool worker_thread();
498 /// Handle completion of an asynchronous accept operation.
499 void handle_accept_ipv4(const boost::system::error_code& e);
500 void handle_accept_ipv6(const boost::system::error_code& e);
501 void handle_accept(const boost::system::error_code& e, bool ipv6 = false);
502
503 bool is_thread_worker();
504
505 const std::shared_ptr<typename connection<t_protocol_handler>::shared_state> m_state;
506
507 /// The io_context used to perform asynchronous operations.
508 struct worker
509 {
510 worker()
511 : io_context(), work(io_context.get_executor())
512 {}
513
514 boost::asio::io_context io_context;
515 boost::asio::executor_work_guard<boost::asio::io_context::executor_type> work;
516 };
517 std::unique_ptr<worker> m_io_context_local_instance;
518 boost::asio::io_context& io_context_;
519
520 /// Acceptor used to listen for incoming connections.
521 boost::asio::ip::tcp::acceptor acceptor_;
522 boost::asio::ip::tcp::acceptor acceptor_ipv6;
523 epee::net_utils::network_address default_remote;
524
525 std::atomic<bool> m_stop_signal_sent;
526 uint32_t m_port;
527 uint32_t m_port_ipv6;
528 std::string m_address;
529 std::string m_address_ipv6;
530 bool m_use_ipv6;
531 bool m_require_ipv4;
532 std::string m_thread_name_prefix; //TODO: change to enum server_type, now used
533 size_t m_threads_count;
534 std::vector<boost::shared_ptr<boost::thread> > m_threads;
535 boost::thread::id m_main_thread_id;
536 critical_section m_threads_lock;
537 std::atomic<uint32_t> m_thread_index;
538
539 t_connection_type m_connection_type;
540
541 /// The next connection to be accepted
542 connection_ptr new_connection_;
543 connection_ptr new_connection_ipv6;
544
545
546 boost::mutex connections_mutex;
547 std::set<connection_ptr> connections_;
548 }; // class <>boosted_tcp_server
549
550
551 } // namespace
552 } // namespace
553
554 #include "abstract_tcp_server2.inl"
555
556 #endif