Debian Codegraph @

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

raw
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 #include <boost/asio/post.hpp>
35 #include <boost/foreach.hpp>
36 #include <boost/uuid/random_generator.hpp>
37 #include <boost/chrono.hpp>
38 #include <boost/utility/value_init.hpp>
39 #include <boost/asio/bind_executor.hpp>
40 #include <boost/asio/deadline_timer.hpp>
41 #include <boost/date_time/posix_time/posix_time.hpp> // TODO
42 #include <boost/thread/condition_variable.hpp> // TODO
43 #include <boost/make_shared.hpp>
44 #include <boost/thread.hpp>
45 #include "warnings.h"
46 #include "string_tools_lexical.h"
47 #include "misc_language.h"
48
49 #include <sstream>
50 #include <iomanip>
51 #include <algorithm>
52 #include <functional>
53 #include <random>
54
55 #undef MONERO_DEFAULT_LOG_CATEGORY
56 #define MONERO_DEFAULT_LOG_CATEGORY "net"
57
58 #define AGGRESSIVE_TIMEOUT_THRESHOLD 120 // sockets
59 #define NEW_CONNECTION_TIMEOUT_LOCAL 1200000 // 2 minutes
60 #define NEW_CONNECTION_TIMEOUT_REMOTE 10000 // 10 seconds
61 #define DEFAULT_TIMEOUT_MS_LOCAL 1800000 // 30 minutes
62 #define DEFAULT_TIMEOUT_MS_REMOTE 300000 // 5 minutes
63 #define TIMEOUT_EXTRA_MS_PER_BYTE 0.2
64
65
66 namespace epee
67 {
68 namespace net_utils
69 {
70 template<typename T>
71 T& check_and_get(std::shared_ptr<T>& ptr)
72 {
73 CHECK_AND_ASSERT_THROW_MES(bool(ptr), "shared_state cannot be null");
74 return *ptr;
75 }
76
77 /************************************************************************/
78 /* */
79 /************************************************************************/
80 template<typename T>
81 unsigned int connection<T>::host_count(int delta)
82 {
83 static std::mutex hosts_mutex;
84 std::lock_guard<std::mutex> guard(hosts_mutex);
85 static std::map<std::string, unsigned int> hosts;
86 unsigned int &val = hosts[m_host];
87 if (delta > 0)
88 MTRACE("New connection from host " << m_host << ": " << val);
89 else if (delta < 0)
90 MTRACE("Closed connection from host " << m_host << ": " << val);
91 CHECK_AND_ASSERT_THROW_MES(delta >= 0 || val >= (unsigned)-delta, "Count would go negative");
92 CHECK_AND_ASSERT_THROW_MES(delta <= 0 || val <= std::numeric_limits<unsigned int>::max() - (unsigned)delta, "Count would wrap");
93 val += delta;
94 return val;
95 }
96
97 template<typename T>
98 typename connection<T>::duration_t connection<T>::get_default_timeout()
99 {
100 unsigned count{};
101 try { count = host_count(); } catch (...) {}
102 const unsigned shift = (
103 connection_basic::get_state().sock_count > AGGRESSIVE_TIMEOUT_THRESHOLD ?
104 std::min(std::max(count, 1u) - 1, 8u) :
105 0
106 );
107 return (
108 m_local ?
109 std::chrono::milliseconds(DEFAULT_TIMEOUT_MS_LOCAL >> shift) :
110 std::chrono::milliseconds(DEFAULT_TIMEOUT_MS_REMOTE >> shift)
111 );
112 }
113
114 template<typename T>
115 typename connection<T>::duration_t connection<T>::get_timeout_from_bytes_read(size_t bytes) const
116 {
117 return std::chrono::duration_cast<connection<T>::duration_t>(
118 std::chrono::duration<double, std::chrono::milliseconds::period>(
119 bytes * TIMEOUT_EXTRA_MS_PER_BYTE
120 )
121 );
122 }
123
124 template<typename T>
125 void connection<T>::state_status_check()
126 {
127 switch (m_state.status)
128 {
129 case status_t::RUNNING:
130 interrupt();
131 break;
132 case status_t::INTERRUPTED:
133 on_interrupted();
134 break;
135 case status_t::TERMINATING:
136 on_terminating();
137 break;
138 default:
139 break;
140 }
141 }
142
143 template<typename T>
144 void connection<T>::start_timer(duration_t duration, bool add)
145 {
146 if (m_state.timers.general.wait_expire) {
147 m_state.timers.general.cancel_expire = true;
148 m_state.timers.general.reset_expire = true;
149 m_timers.general.expires_after(
150 std::min(
151 duration + (add ? (m_timers.general.expiry() - std::chrono::steady_clock::now()) : duration_t{}),
152 get_default_timeout()
153 )
154 );
155 }
156 else {
157 m_timers.general.expires_after(
158 std::min(
159 duration + (add ? (m_timers.general.expiry() - std::chrono::steady_clock::now()) : duration_t{}),
160 get_default_timeout()
161 )
162 );
163 async_wait_timer();
164 }
165 }
166
167 template<typename T>
168 void connection<T>::async_wait_timer()
169 {
170 if (m_state.timers.general.wait_expire)
171 return;
172 m_state.timers.general.wait_expire = true;
173 auto self = connection<T>::shared_from_this();
174 m_timers.general.async_wait([this, self](const ec_t & ec){
175 std::lock_guard<std::mutex> guard(m_state.lock);
176 m_state.timers.general.wait_expire = false;
177 if (m_state.timers.general.cancel_expire) {
178 m_state.timers.general.cancel_expire = false;
179 if (m_state.timers.general.reset_expire) {
180 m_state.timers.general.reset_expire = false;
181 async_wait_timer();
182 }
183 else if (m_state.status == status_t::INTERRUPTED)
184 on_interrupted();
185 else if (m_state.status == status_t::TERMINATING)
186 on_terminating();
187 }
188 else if (m_state.status == status_t::RUNNING)
189 interrupt();
190 else if (m_state.status == status_t::INTERRUPTED)
191 terminate();
192 });
193 }
194
195 template<typename T>
196 void connection<T>::cancel_timer()
197 {
198 if (!m_state.timers.general.wait_expire)
199 return;
200 m_state.timers.general.cancel_expire = true;
201 m_state.timers.general.reset_expire = false;
202 m_timers.general.cancel();
203 }
204
205 template<typename T>
206 void connection<T>::start_handshake()
207 {
208 if (m_state.socket.wait_handshake)
209 return;
210 static_assert(
211 epee::net_utils::get_ssl_magic_size() <= sizeof(m_state.data.read.buffer),
212 ""
213 );
214 auto self = connection<T>::shared_from_this();
215 if (!m_state.ssl.forced && !m_state.ssl.detected) {
216 m_state.socket.wait_read = true;
217 boost::asio::async_read(
218 connection_basic::socket_.next_layer(),
219 boost::asio::buffer(
220 m_state.data.read.buffer.data(),
221 m_state.data.read.buffer.size()
222 ),
223 boost::asio::transfer_exactly(epee::net_utils::get_ssl_magic_size()),
224 boost::asio::bind_executor(
225 m_strand,
226 [this, self](const ec_t &ec, size_t bytes_transferred){
227 std::lock_guard<std::mutex> guard(m_state.lock);
228 m_state.socket.wait_read = false;
229 if (m_state.socket.cancel_read) {
230 m_state.socket.cancel_read = false;
231 state_status_check();
232 }
233 else if (ec.value()) {
234 terminate();
235 }
236 else if (
237 !epee::net_utils::is_ssl(
238 static_cast<const unsigned char *>(
239 m_state.data.read.buffer.data()
240 ),
241 bytes_transferred
242 )
243 ) {
244 m_state.ssl.enabled = false;
245 m_state.socket.handle_read = true;
246 boost::asio::post(
247 connection_basic::strand_,
248 [this, self, bytes_transferred]{
249 bool success = m_handler.handle_recv(
250 reinterpret_cast<char *>(m_state.data.read.buffer.data()),
251 bytes_transferred
252 );
253 std::lock_guard<std::mutex> guard(m_state.lock);
254 m_state.socket.handle_read = false;
255 if (m_state.status == status_t::INTERRUPTED)
256 on_interrupted();
257 else if (m_state.status == status_t::TERMINATING)
258 on_terminating();
259 else if (!success)
260 interrupt();
261 else {
262 start_read();
263 }
264 }
265 );
266 }
267 else {
268 m_state.ssl.detected = true;
269 start_handshake();
270 }
271 }
272 )
273 );
274 return;
275 }
276
277 m_state.socket.wait_handshake = true;
278 auto on_handshake = [this, self](const ec_t &ec, size_t bytes_transferred){
279 std::lock_guard<std::mutex> guard(m_state.lock);
280 m_state.socket.wait_handshake = false;
281 if (m_state.socket.cancel_handshake) {
282 m_state.socket.cancel_handshake = false;
283 state_status_check();
284 }
285 else if (ec.value()) {
286 ec_t ec;
287 connection_basic::socket_.next_layer().shutdown(
288 socket_t::shutdown_both,
289 ec
290 );
291 connection_basic::socket_.next_layer().close(ec);
292 m_state.socket.connected = false;
293 interrupt();
294 }
295 else {
296 m_state.ssl.handshaked = true;
297 start_write();
298 start_read();
299 }
300 };
301 const auto handshake = handshake_t::server;
302 static_cast<shared_state&>(
303 connection_basic::get_state()
304 ).ssl_options().configure(connection_basic::socket_, handshake);
305 boost::asio::post(
306 m_strand,
307 [this, self, on_handshake]{
308 connection_basic::socket_.async_handshake(
309 handshake,
310 boost::asio::buffer(
311 m_state.data.read.buffer.data(),
312 m_state.ssl.forced ? 0 :
313 epee::net_utils::get_ssl_magic_size()
314 ),
315 boost::asio::bind_executor(m_strand, on_handshake)
316 );
317 }
318 );
319 }
320
321 template<typename T>
322 void connection<T>::start_read()
323 {
324 if (m_state.timers.throttle.in.wait_expire || m_state.socket.wait_read ||
325 m_state.socket.handle_read
326 ) {
327 return;
328 }
329 auto self = connection<T>::shared_from_this();
330 if (speed_limit_is_enabled()) {
331 auto calc_duration = []{
332 CRITICAL_REGION_LOCAL(
333 network_throttle_manager_t::m_lock_get_global_throttle_in
334 );
335 return std::chrono::duration_cast<connection<T>::duration_t>(
336 std::chrono::duration<double, std::chrono::seconds::period>(
337 std::min(
338 network_throttle_manager_t::get_global_throttle_in(
339 ).get_sleep_time_after_tick(1),
340 1.0
341 )
342 )
343 );
344 };
345 const auto duration = calc_duration();
346 if (duration > duration_t{}) {
347 m_timers.throttle.in.expires_after(duration);
348 m_state.timers.throttle.in.wait_expire = true;
349 m_timers.throttle.in.async_wait([this, self](const ec_t &ec){
350 std::lock_guard<std::mutex> guard(m_state.lock);
351 m_state.timers.throttle.in.wait_expire = false;
352 if (m_state.timers.throttle.in.cancel_expire) {
353 m_state.timers.throttle.in.cancel_expire = false;
354 state_status_check();
355 }
356 else if (ec.value())
357 interrupt();
358 else
359 start_read();
360 });
361 return;
362 }
363 }
364 m_state.socket.wait_read = true;
365 auto on_read = [this, self](const ec_t &ec, size_t bytes_transferred){
366 std::lock_guard<std::mutex> guard(m_state.lock);
367 m_state.socket.wait_read = false;
368 if (m_state.socket.cancel_read) {
369 m_state.socket.cancel_read = false;
370 state_status_check();
371 }
372 else if (ec.value())
373 terminate();
374 else {
375 {
376 m_state.stat.in.throttle.handle_trafic_exact(bytes_transferred);
377 const auto speed = m_state.stat.in.throttle.get_current_speed();
378 m_conn_context.m_current_speed_down = speed;
379 m_conn_context.m_max_speed_down = std::max(
380 m_conn_context.m_max_speed_down,
381 speed
382 );
383 if (speed_limit_is_enabled()) {
384 CRITICAL_REGION_LOCAL(
385 network_throttle_manager_t::m_lock_get_global_throttle_in
386 );
387 network_throttle_manager_t::get_global_throttle_in(
388 ).handle_trafic_exact(bytes_transferred);
389 }
390 connection_basic::logger_handle_net_read(bytes_transferred);
391 m_conn_context.m_last_recv = time(NULL);
392 m_conn_context.m_recv_cnt += bytes_transferred;
393 start_timer(get_timeout_from_bytes_read(bytes_transferred), true);
394 }
395
396 // Post handle_recv to a separate `strand_`, distinct from `m_strand`
397 // which is listening for reads/writes. This avoids a circular dep.
398 // handle_recv can queue many writes, and `m_strand` will process those
399 // writes until the connection terminates without deadlocking waiting
400 // for handle_recv.
401 m_state.socket.handle_read = true;
402 boost::asio::post(
403 connection_basic::strand_,
404 [this, self, bytes_transferred]{
405 bool success = m_handler.handle_recv(
406 reinterpret_cast<char *>(m_state.data.read.buffer.data()),
407 bytes_transferred
408 );
409 std::lock_guard<std::mutex> guard(m_state.lock);
410 m_state.socket.handle_read = false;
411 if (m_state.status == status_t::INTERRUPTED)
412 on_interrupted();
413 else if (m_state.status == status_t::TERMINATING)
414 on_terminating();
415 else if (!success)
416 interrupt();
417 else {
418 start_read();
419 }
420 }
421 );
422 }
423 };
424 if (!m_state.ssl.enabled)
425 connection_basic::socket_.next_layer().async_read_some(
426 boost::asio::buffer(
427 m_state.data.read.buffer.data(),
428 m_state.data.read.buffer.size()
429 ),
430 boost::asio::bind_executor(m_strand, on_read)
431 );
432 else
433 boost::asio::post(
434 m_strand,
435 [this, self, on_read]{
436 connection_basic::socket_.async_read_some(
437 boost::asio::buffer(
438 m_state.data.read.buffer.data(),
439 m_state.data.read.buffer.size()
440 ),
441 boost::asio::bind_executor(m_strand, on_read)
442 );
443 }
444 );
445 }
446
447 template<typename T>
448 void connection<T>::start_write()
449 {
450 if (m_state.timers.throttle.out.wait_expire || m_state.socket.wait_write ||
451 m_state.data.write.queue.empty() ||
452 (m_state.ssl.enabled && !m_state.ssl.handshaked)
453 ) {
454 return;
455 }
456 auto self = connection<T>::shared_from_this();
457 if (speed_limit_is_enabled()) {
458 auto calc_duration = [this]{
459 CRITICAL_REGION_LOCAL(
460 network_throttle_manager_t::m_lock_get_global_throttle_out
461 );
462 return std::chrono::duration_cast<connection<T>::duration_t>(
463 std::chrono::duration<double, std::chrono::seconds::period>(
464 std::min(
465 network_throttle_manager_t::get_global_throttle_out(
466 ).get_sleep_time_after_tick(
467 m_state.data.write.queue.back().size()
468 ),
469 1.0
470 )
471 )
472 );
473 };
474 const auto duration = calc_duration();
475 if (duration > duration_t{}) {
476 m_timers.throttle.out.expires_after(duration);
477 m_state.timers.throttle.out.wait_expire = true;
478 m_timers.throttle.out.async_wait([this, self](const ec_t &ec){
479 std::lock_guard<std::mutex> guard(m_state.lock);
480 m_state.timers.throttle.out.wait_expire = false;
481 if (m_state.timers.throttle.out.cancel_expire) {
482 m_state.timers.throttle.out.cancel_expire = false;
483 state_status_check();
484 }
485 else if (ec.value())
486 interrupt();
487 else
488 start_write();
489 });
490 }
491 }
492
493 m_state.socket.wait_write = true;
494 auto on_write = [this, self](const ec_t &ec, size_t bytes_transferred){
495 std::lock_guard<std::mutex> guard(m_state.lock);
496 m_state.socket.wait_write = false;
497 if (m_state.socket.cancel_write) {
498 m_state.socket.cancel_write = false;
499 m_state.data.write.queue.clear();
500 m_state.data.write.total_bytes = 0;
501 state_status_check();
502 }
503 else if (ec.value()) {
504 m_state.data.write.queue.clear();
505 m_state.data.write.total_bytes = 0;
506 interrupt();
507 }
508 else {
509 {
510 m_state.stat.out.throttle.handle_trafic_exact(bytes_transferred);
511 const auto speed = m_state.stat.out.throttle.get_current_speed();
512 m_conn_context.m_current_speed_up = speed;
513 m_conn_context.m_max_speed_down = std::max(
514 m_conn_context.m_max_speed_down,
515 speed
516 );
517 if (speed_limit_is_enabled()) {
518 CRITICAL_REGION_LOCAL(
519 network_throttle_manager_t::m_lock_get_global_throttle_out
520 );
521 network_throttle_manager_t::get_global_throttle_out(
522 ).handle_trafic_exact(bytes_transferred);
523 }
524 connection_basic::logger_handle_net_write(bytes_transferred);
525 m_conn_context.m_last_send = time(NULL);
526 m_conn_context.m_send_cnt += bytes_transferred;
527
528 start_timer(get_default_timeout(), true);
529 }
530 const std::size_t byte_count = m_state.data.write.queue.back().size();
531 assert(bytes_transferred == byte_count);
532 m_state.data.write.queue.pop_back();
533 m_state.data.write.total_bytes -=
534 std::min(m_state.data.write.total_bytes, byte_count);
535 m_state.condition.notify_all();
536 start_write();
537 }
538 };
539 if (!m_state.ssl.enabled)
540 boost::asio::async_write(
541 connection_basic::socket_.next_layer(),
542 boost::asio::buffer(
543 m_state.data.write.queue.back().data(),
544 m_state.data.write.queue.back().size()
545 ),
546 boost::asio::bind_executor(m_strand, on_write)
547 );
548 else
549 boost::asio::post(
550 m_strand,
551 [this, self, on_write]{
552 boost::asio::async_write(
553 connection_basic::socket_,
554 boost::asio::buffer(
555 m_state.data.write.queue.back().data(),
556 m_state.data.write.queue.back().size()
557 ),
558 boost::asio::bind_executor(m_strand, on_write)
559 );
560 }
561 );
562 }
563
564 template<typename T>
565 void connection<T>::start_shutdown()
566 {
567 if (m_state.socket.wait_shutdown)
568 return;
569 auto self = connection<T>::shared_from_this();
570 m_state.socket.wait_shutdown = true;
571 auto on_shutdown = [this, self](const ec_t &ec){
572 std::lock_guard<std::mutex> guard(m_state.lock);
573 m_state.socket.wait_shutdown = false;
574 if (m_state.socket.cancel_shutdown) {
575 m_state.socket.cancel_shutdown = false;
576 switch (m_state.status)
577 {
578 case status_t::RUNNING:
579 interrupt();
580 break;
581 case status_t::INTERRUPTED:
582 terminate();
583 break;
584 case status_t::TERMINATING:
585 on_terminating();
586 break;
587 default:
588 break;
589 }
590 }
591 else {
592 terminate();
593 }
594 };
595 boost::asio::post(
596 m_strand,
597 [this, self, on_shutdown]{
598 connection_basic::socket_.async_shutdown(
599 boost::asio::bind_executor(m_strand, on_shutdown)
600 );
601 }
602 );
603 start_timer(get_default_timeout());
604 }
605
606 template<typename T>
607 void connection<T>::cancel_socket()
608 {
609 bool wait_socket = false;
610 if (m_state.socket.wait_handshake)
611 wait_socket = m_state.socket.cancel_handshake = true;
612 if (m_state.timers.throttle.in.wait_expire) {
613 m_state.timers.throttle.in.cancel_expire = true;
614 m_timers.throttle.in.cancel();
615 }
616 if (m_state.socket.wait_read)
617 wait_socket = m_state.socket.cancel_read = true;
618 if (m_state.timers.throttle.out.wait_expire) {
619 m_state.timers.throttle.out.cancel_expire = true;
620 m_timers.throttle.out.cancel();
621 }
622 if (m_state.socket.wait_write)
623 wait_socket = m_state.socket.cancel_write = true;
624 if (m_state.socket.wait_shutdown)
625 wait_socket = m_state.socket.cancel_shutdown = true;
626 if (wait_socket) {
627 ec_t ec;
628 connection_basic::socket_.next_layer().cancel(ec);
629 }
630 }
631
632 template<typename T>
633 void connection<T>::cancel_handler()
634 {
635 if (m_state.protocol.released || m_state.protocol.wait_release)
636 return;
637 m_state.protocol.wait_release = true;
638 m_state.lock.unlock();
639 m_handler.release_protocol();
640 m_state.lock.lock();
641 m_state.protocol.wait_release = false;
642 m_state.protocol.released = true;
643 if (m_state.status == status_t::INTERRUPTED)
644 on_interrupted();
645 else if (m_state.status == status_t::TERMINATING)
646 on_terminating();
647 }
648
649 template<typename T>
650 void connection<T>::interrupt()
651 {
652 if (m_state.status != status_t::RUNNING)
653 return;
654 m_state.status = status_t::INTERRUPTED;
655 cancel_timer();
656 cancel_socket();
657 on_interrupted();
658 m_state.condition.notify_all();
659 cancel_handler();
660 }
661
662 template<typename T>
663 void connection<T>::on_interrupted()
664 {
665 assert(m_state.status == status_t::INTERRUPTED);
666 if (m_state.timers.general.wait_expire)
667 return;
668 if (m_state.socket.wait_handshake)
669 return;
670 if (m_state.timers.throttle.in.wait_expire)
671 return;
672 if (m_state.socket.wait_read)
673 return;
674 if (m_state.socket.handle_read)
675 return;
676 if (m_state.timers.throttle.out.wait_expire)
677 return;
678 // \NOTE See on_terminating() comments
679 //if (m_state.socket.wait_write)
680 // return;
681 if (m_state.socket.wait_shutdown)
682 return;
683 if (m_state.protocol.wait_init)
684 return;
685 if (m_state.protocol.wait_callback)
686 return;
687 if (m_state.protocol.wait_release)
688 return;
689 if (m_state.socket.connected) {
690 if (!m_state.ssl.enabled) {
691 ec_t ec;
692 connection_basic::socket_.next_layer().shutdown(
693 socket_t::shutdown_both,
694 ec
695 );
696 connection_basic::socket_.next_layer().close(ec);
697 m_state.socket.connected = false;
698 m_state.status = status_t::WASTED;
699 }
700 else
701 start_shutdown();
702 }
703 else
704 m_state.status = status_t::WASTED;
705 }
706
707 template<typename T>
708 void connection<T>::terminate()
709 {
710 if (m_state.status != status_t::RUNNING &&
711 m_state.status != status_t::INTERRUPTED
712 )
713 return;
714 m_state.status = status_t::TERMINATING;
715 cancel_timer();
716 cancel_socket();
717 on_terminating();
718 m_state.condition.notify_all();
719 cancel_handler();
720 }
721
722 template<typename T>
723 void connection<T>::on_terminating()
724 {
725 assert(m_state.status == status_t::TERMINATING);
726 if (m_state.timers.general.wait_expire)
727 return;
728 if (m_state.socket.wait_handshake)
729 return;
730 if (m_state.timers.throttle.in.wait_expire)
731 return;
732 if (m_state.socket.wait_read)
733 return;
734 if (m_state.socket.handle_read)
735 return;
736 if (m_state.timers.throttle.out.wait_expire)
737 return;
738 // Writes cannot be canceled due to `async_write` being a "composed"
739 // handler. ASIO has new cancellation routines, not available in 1.66, to
740 // handle this situation. The problem is that if cancel is called after an
741 // intermediate handler is queued, the op will not check the cancel flag in
742 // our code, and will instead queue up another write.
743 //if (m_state.socket.wait_write)
744 // return;
745 if (m_state.socket.wait_shutdown)
746 return;
747 if (m_state.protocol.wait_init)
748 return;
749 if (m_state.protocol.wait_callback)
750 return;
751 if (m_state.protocol.wait_release)
752 return;
753 if (m_state.socket.connected) {
754 ec_t ec;
755 connection_basic::socket_.next_layer().shutdown(
756 socket_t::shutdown_both,
757 ec
758 );
759 connection_basic::socket_.next_layer().close(ec);
760 m_state.socket.connected = false;
761 }
762 m_state.status = status_t::WASTED;
763 }
764
765 template<typename T>
766 bool connection<T>::send(epee::byte_slice message)
767 {
768 std::lock_guard<std::mutex> guard(m_state.lock);
769 if (m_state.status != status_t::RUNNING || m_state.socket.wait_handshake)
770 return false;
771 if (std::numeric_limits<std::size_t>::max() - m_state.data.write.total_bytes < message.size())
772 return false;
773
774 // Wait for the write queue to fall below the max. If it doesn't after a
775 // randomized delay, drop the connection.
776 auto wait_consume = [this] {
777 auto random_delay = []{
778 using engine = std::mt19937;
779 std::random_device dev;
780 std::seed_seq::result_type rand[
781 engine::state_size // Use complete bit space
782 ]{};
783 std::generate_n(rand, engine::state_size, std::ref(dev));
784 std::seed_seq seed(rand, rand + engine::state_size);
785 engine rng(seed);
786 return std::chrono::milliseconds(
787 std::uniform_int_distribution<>(5000, 6000)(rng)
788 );
789 };
790
791 // The bytes check intentionally does not include incoming message size.
792 // This allows for a soft overflow; a single http response will never fail
793 // this check, but multiple responses could. Clients can avoid this case
794 // by reading the entire response before making another request. P2P
795 // should never hit the MAX_BYTES check (when using default values).
796 if (m_state.data.write.queue.size() <= ABSTRACT_SERVER_SEND_QUE_MAX_COUNT &&
797 m_state.data.write.total_bytes <= static_cast<shared_state&>(connection_basic::get_state()).response_soft_limit)
798 return true;
799 m_state.data.write.wait_consume = true;
800 bool success = m_state.condition.wait_for(
801 m_state.lock,
802 random_delay(),
803 [this]{
804 return (
805 m_state.status != status_t::RUNNING ||
806 (
807 m_state.data.write.queue.size() <=
808 ABSTRACT_SERVER_SEND_QUE_MAX_COUNT &&
809 m_state.data.write.total_bytes <=
810 static_cast<shared_state&>(connection_basic::get_state()).response_soft_limit
811 )
812 );
813 }
814 );
815 m_state.data.write.wait_consume = false;
816 if (!success) {
817 // synchronize with intermediate writes on `m_strand`
818 auto self = connection<T>::shared_from_this();
819 boost::asio::post(m_strand, [this, self] {
820 std::lock_guard<std::mutex> guard(m_state.lock);
821 terminate();
822 });
823 return false;
824 }
825 else
826 return m_state.status == status_t::RUNNING;
827 };
828 auto wait_sender = [this] {
829 m_state.condition.wait(
830 m_state.lock,
831 [this] {
832 return (
833 m_state.status != status_t::RUNNING ||
834 !m_state.data.write.wait_consume
835 );
836 }
837 );
838 return m_state.status == status_t::RUNNING;
839 };
840 if (!wait_sender())
841 return false;
842 constexpr size_t CHUNK_SIZE = 32 * 1024;
843 if (m_connection_type == e_connection_type_RPC ||
844 message.size() <= 2 * CHUNK_SIZE
845 ) {
846 if (!wait_consume())
847 return false;
848 const std::size_t byte_count = message.size();
849 m_state.data.write.queue.emplace_front(std::move(message));
850 m_state.data.write.total_bytes += byte_count;
851 start_write();
852 }
853 else {
854 while (!message.empty()) {
855 if (!wait_consume())
856 return false;
857 m_state.data.write.queue.emplace_front(
858 message.take_slice(CHUNK_SIZE)
859 );
860 m_state.data.write.total_bytes += m_state.data.write.queue.front().size();
861 start_write();
862 }
863 }
864 m_state.condition.notify_all();
865 return true;
866 }
867
868 template<typename T>
869 bool connection<T>::start_internal(
870 bool is_income,
871 bool is_multithreaded,
872 boost::optional<network_address> real_remote
873 )
874 {
875 std::unique_lock<std::mutex> guard(m_state.lock);
876 if (m_state.status != status_t::TERMINATED)
877 return false;
878 if (!real_remote) {
879 ec_t ec;
880 auto endpoint = connection_basic::socket_.next_layer().remote_endpoint(
881 ec
882 );
883 if (ec.value())
884 return false;
885 real_remote = (
886 endpoint.address().is_v6() ?
887 network_address{
888 ipv6_network_address{endpoint.address().to_v6(), endpoint.port()}
889 } :
890 network_address{
891 ipv4_network_address{
892 uint32_t{
893 boost::asio::detail::socket_ops::host_to_network_long(
894 endpoint.address().to_v4().to_uint()
895 )
896 },
897 endpoint.port()
898 }
899 }
900 );
901 }
902 auto *filter = static_cast<shared_state&>(
903 connection_basic::get_state()
904 ).pfilter;
905 if (filter && !filter->is_remote_host_allowed(*real_remote))
906 return false;
907
908 auto *limit = static_cast<shared_state&>(
909 connection_basic::get_state()
910 ).plimit;
911 if (is_income && limit && limit->is_host_limit(*real_remote))
912 return false;
913
914 ec_t ec;
915 #if !defined(_WIN32) || !defined(__i686)
916 connection_basic::socket_.next_layer().set_option(
917 boost::asio::detail::socket_option::integer<IPPROTO_IP, IP_TOS>{
918 connection_basic::get_tos_flag()
919 },
920 ec
921 );
922 if (ec.value())
923 return false;
924 #endif
925 connection_basic::socket_.next_layer().set_option(
926 boost::asio::ip::tcp::no_delay{false},
927 ec
928 );
929 if (ec.value())
930 return false;
931 connection_basic::m_is_multithreaded = is_multithreaded;
932 m_conn_context.set_details(
933 boost::uuids::random_generator()(),
934 *real_remote,
935 is_income,
936 connection_basic::m_ssl_support == ssl_support_t::e_ssl_support_enabled
937 );
938 m_host = real_remote->host_str();
939 try { host_count(1); } catch(...) { /* ignore */ }
940 m_local = real_remote->is_loopback() || real_remote->is_local();
941 m_state.ssl.enabled = (
942 connection_basic::m_ssl_support != ssl_support_t::e_ssl_support_disabled
943 );
944 m_state.ssl.forced = (
945 connection_basic::m_ssl_support == ssl_support_t::e_ssl_support_enabled
946 );
947 m_state.socket.connected = true;
948 m_state.status = status_t::RUNNING;
949 start_timer(
950 std::chrono::milliseconds(
951 m_local ? NEW_CONNECTION_TIMEOUT_LOCAL : NEW_CONNECTION_TIMEOUT_REMOTE
952 )
953 );
954 m_state.protocol.wait_init = true;
955 guard.unlock();
956 m_handler.after_init_connection();
957 guard.lock();
958 m_state.protocol.wait_init = false;
959 m_state.protocol.initialized = true;
960 if (m_state.status == status_t::INTERRUPTED)
961 on_interrupted();
962 else if (m_state.status == status_t::TERMINATING)
963 on_terminating();
964 else if (!is_income || !m_state.ssl.enabled)
965 start_read();
966 else
967 start_handshake();
968 return true;
969 }
970
971 template<typename T>
972 connection<T>::connection(
973 io_context_t &io_context,
974 std::shared_ptr<shared_state> shared_state,
975 t_connection_type connection_type,
976 ssl_support_t ssl_support
977 ):
978 connection(
979 io_context,
980 socket_t{io_context},
981 std::move(shared_state),
982 connection_type,
983 ssl_support
984 )
985 {
986 }
987
988 template<typename T>
989 connection<T>::connection(
990 io_context_t &io_context,
991 socket_t &&socket,
992 std::shared_ptr<shared_state> shared_state,
993 t_connection_type connection_type,
994 ssl_support_t ssl_support
995 ):
996 connection_basic(io_context, std::move(socket), shared_state, ssl_support),
997 m_handler(this, *shared_state, m_conn_context),
998 m_connection_type(connection_type),
999 m_io_context{io_context},
1000 m_strand{m_io_context},
1001 m_timers{m_io_context}
1002 {
1003 }
1004
1005 template<typename T>
1006 connection<T>::~connection() noexcept(false)
1007 {
1008 std::lock_guard<std::mutex> guard(m_state.lock);
1009 assert(m_state.status == status_t::TERMINATED ||
1010 m_state.status == status_t::WASTED ||
1011 m_io_context.stopped()
1012 );
1013 if (m_state.status != status_t::WASTED)
1014 return;
1015 try { host_count(-1); } catch (...) { /* ignore */ }
1016 }
1017
1018 template<typename T>
1019 bool connection<T>::start(
1020 bool is_income,
1021 bool is_multithreaded
1022 )
1023 {
1024 return start_internal(is_income, is_multithreaded, {});
1025 }
1026
1027 template<typename T>
1028 bool connection<T>::start(
1029 bool is_income,
1030 bool is_multithreaded,
1031 network_address real_remote
1032 )
1033 {
1034 return start_internal(is_income, is_multithreaded, real_remote);
1035 }
1036
1037 template<typename T>
1038 void connection<T>::save_dbg_log()
1039 {
1040 std::lock_guard<std::mutex> guard(m_state.lock);
1041 std::string address;
1042 std::string port;
1043 ec_t ec;
1044 auto endpoint = connection_basic::socket().remote_endpoint(ec);
1045 if (ec.value()) {
1046 address = "<not connected>";
1047 port = "<not connected>";
1048 }
1049 else {
1050 address = endpoint.address().to_string();
1051 port = std::to_string(endpoint.port());
1052 }
1053 MDEBUG(
1054 " connection type " << std::to_string(m_connection_type) <<
1055 " " << connection_basic::socket().local_endpoint().address().to_string() <<
1056 ":" << connection_basic::socket().local_endpoint().port() <<
1057 " <--> " << m_conn_context.m_remote_address.str() <<
1058 " (via " << address << ":" << port << ")"
1059 );
1060 }
1061
1062 template<typename T>
1063 bool connection<T>::speed_limit_is_enabled() const
1064 {
1065 return m_connection_type == e_connection_type_P2P;
1066 }
1067
1068 template<typename T>
1069 bool connection<T>::cancel()
1070 {
1071 return close();
1072 }
1073
1074 template<typename T>
1075 bool connection<T>::do_send(byte_slice message)
1076 {
1077 return send(std::move(message));
1078 }
1079
1080 template<typename T>
1081 bool connection<T>::send_done()
1082 {
1083 return true;
1084 }
1085
1086 template<typename T>
1087 bool connection<T>::close()
1088 {
1089 std::lock_guard<std::mutex> guard(m_state.lock);
1090 if (m_state.status != status_t::RUNNING)
1091 return false;
1092 terminate();
1093 return true;
1094 }
1095
1096 template<typename T>
1097 bool connection<T>::call_run_once_service_io()
1098 {
1099 if(connection_basic::m_is_multithreaded) {
1100 if (!m_io_context.poll_one())
1101 misc_utils::sleep_no_w(1);
1102 }
1103 else {
1104 if (!m_io_context.run_one())
1105 return false;
1106 }
1107 return true;
1108 }
1109
1110 template<typename T>
1111 bool connection<T>::request_callback()
1112 {
1113 std::lock_guard<std::mutex> guard(m_state.lock);
1114 if (m_state.status != status_t::RUNNING)
1115 return false;
1116 auto self = connection<T>::shared_from_this();
1117 ++m_state.protocol.wait_callback;
1118 boost::asio::post(connection_basic::strand_, [this, self]{
1119 m_handler.handle_qued_callback();
1120 std::lock_guard<std::mutex> guard(m_state.lock);
1121 --m_state.protocol.wait_callback;
1122 if (m_state.status == status_t::INTERRUPTED)
1123 on_interrupted();
1124 else if (m_state.status == status_t::TERMINATING)
1125 on_terminating();
1126 });
1127 return true;
1128 }
1129
1130 template<typename T>
1131 typename connection<T>::io_context_t &connection<T>::get_io_context()
1132 {
1133 return m_io_context;
1134 }
1135
1136 template<typename T>
1137 bool connection<T>::add_ref()
1138 {
1139 try {
1140 auto self = connection<T>::shared_from_this();
1141 std::lock_guard<std::mutex> guard(m_state.lock);
1142 this->self = std::move(self);
1143 ++m_state.protocol.reference_counter;
1144 return true;
1145 }
1146 catch (boost::bad_weak_ptr &exception) {
1147 return false;
1148 }
1149 }
1150
1151 template<typename T>
1152 bool connection<T>::release()
1153 {
1154 connection_ptr self;
1155 std::lock_guard<std::mutex> guard(m_state.lock);
1156 if (!(--m_state.protocol.reference_counter))
1157 self = std::move(this->self);
1158 return true;
1159 }
1160
1161 template<typename T>
1162 void connection<T>::setRpcStation()
1163 {
1164 std::lock_guard<std::mutex> guard(m_state.lock);
1165 m_connection_type = e_connection_type_RPC;
1166 }
1167
1168 template<class t_protocol_handler>
1169 boosted_tcp_server<t_protocol_handler>::boosted_tcp_server( t_connection_type connection_type ) :
1170 m_state(std::make_shared<typename connection<t_protocol_handler>::shared_state>()),
1171 m_io_context_local_instance(new worker()),
1172 io_context_(m_io_context_local_instance->io_context),
1173 acceptor_(io_context_),
1174 acceptor_ipv6(io_context_),
1175 default_remote(),
1176 m_stop_signal_sent(false), m_port(0),
1177 m_threads_count(0),
1178 m_thread_index(0),
1179 m_connection_type( connection_type ),
1180 new_connection_(),
1181 new_connection_ipv6()
1182 {
1183 create_server_type_map();
1184 m_thread_name_prefix = "NET";
1185 }
1186
1187 template<class t_protocol_handler>
1188 boosted_tcp_server<t_protocol_handler>::boosted_tcp_server(boost::asio::io_context& extarnal_io_context, t_connection_type connection_type) :
1189 m_state(std::make_shared<typename connection<t_protocol_handler>::shared_state>()),
1190 io_context_(extarnal_io_context),
1191 acceptor_(io_context_),
1192 acceptor_ipv6(io_context_),
1193 default_remote(),
1194 m_stop_signal_sent(false), m_port(0),
1195 m_threads_count(0),
1196 m_thread_index(0),
1197 m_connection_type(connection_type),
1198 new_connection_(),
1199 new_connection_ipv6()
1200 {
1201 create_server_type_map();
1202 m_thread_name_prefix = "NET";
1203 }
1204 //---------------------------------------------------------------------------------
1205 template<class t_protocol_handler>
1206 boosted_tcp_server<t_protocol_handler>::~boosted_tcp_server()
1207 {
1208 this->send_stop_signal();
1209 timed_wait_server_stop(10000);
1210 }
1211 //---------------------------------------------------------------------------------
1212 template<class t_protocol_handler>
1213 void boosted_tcp_server<t_protocol_handler>::create_server_type_map()
1214 {
1215 server_type_map["NET"] = e_connection_type_NET;
1216 server_type_map["RPC"] = e_connection_type_RPC;
1217 server_type_map["P2P"] = e_connection_type_P2P;
1218 }
1219 //---------------------------------------------------------------------------------
1220 template<class t_protocol_handler>
1221 bool boosted_tcp_server<t_protocol_handler>::init_server(uint32_t port, const std::string& address,
1222 uint32_t port_ipv6, const std::string& address_ipv6, bool use_ipv6, bool require_ipv4,
1223 ssl_options_t ssl_options)
1224 {
1225 TRY_ENTRY();
1226 m_stop_signal_sent = false;
1227 m_port = port;
1228 m_port_ipv6 = port_ipv6;
1229 m_address = address;
1230 m_address_ipv6 = address_ipv6;
1231 m_use_ipv6 = use_ipv6;
1232 m_require_ipv4 = require_ipv4;
1233
1234 if (ssl_options)
1235 m_state->configure_ssl(std::move(ssl_options));
1236
1237 std::string ipv4_failed = "";
1238 std::string ipv6_failed = "";
1239
1240 boost::asio::ip::tcp::resolver resolver(io_context_);
1241
1242 try
1243 {
1244 const auto results = resolver.resolve(
1245 address, boost::lexical_cast<std::string>(port), boost::asio::ip::tcp::resolver::canonical_name
1246 );
1247 acceptor_.open(results.begin()->endpoint().protocol());
1248 #if !defined(_WIN32)
1249 acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
1250 #endif
1251 acceptor_.bind(*results.begin());
1252 acceptor_.listen();
1253 boost::asio::ip::tcp::endpoint binded_endpoint = acceptor_.local_endpoint();
1254 m_port = binded_endpoint.port();
1255 MDEBUG("start accept (IPv4)");
1256 new_connection_.reset(new connection<t_protocol_handler>(io_context_, m_state, m_connection_type, m_state->ssl_options().support));
1257 acceptor_.async_accept(new_connection_->socket(),
1258 boost::bind(&boosted_tcp_server<t_protocol_handler>::handle_accept_ipv4, this,
1259 boost::asio::placeholders::error));
1260 }
1261 catch (const std::exception &e)
1262 {
1263 ipv4_failed = e.what();
1264 }
1265
1266 if (ipv4_failed != "")
1267 {
1268 MERROR("Failed to bind IPv4: " << ipv4_failed);
1269 if (require_ipv4)
1270 {
1271 throw std::runtime_error("Failed to bind IPv4 (set to required)");
1272 }
1273 }
1274
1275 if (use_ipv6)
1276 {
1277 try
1278 {
1279 if (port_ipv6 == 0) port_ipv6 = port; // default arg means bind to same port as ipv4
1280
1281 const auto results = resolver.resolve(
1282 address_ipv6, boost::lexical_cast<std::string>(port_ipv6), boost::asio::ip::tcp::resolver::canonical_name
1283 );
1284
1285 acceptor_ipv6.open(results.begin()->endpoint().protocol());
1286 #if !defined(_WIN32)
1287 acceptor_ipv6.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
1288 #endif
1289 acceptor_ipv6.set_option(boost::asio::ip::v6_only(true));
1290 acceptor_ipv6.bind(*results.begin());
1291 acceptor_ipv6.listen();
1292 boost::asio::ip::tcp::endpoint binded_endpoint = acceptor_ipv6.local_endpoint();
1293 m_port_ipv6 = binded_endpoint.port();
1294 MDEBUG("start accept (IPv6)");
1295 new_connection_ipv6.reset(new connection<t_protocol_handler>(io_context_, m_state, m_connection_type, m_state->ssl_options().support));
1296 acceptor_ipv6.async_accept(new_connection_ipv6->socket(),
1297 boost::bind(&boosted_tcp_server<t_protocol_handler>::handle_accept_ipv6, this,
1298 boost::asio::placeholders::error));
1299 }
1300 catch (const std::exception &e)
1301 {
1302 ipv6_failed = e.what();
1303 }
1304 }
1305
1306 if (use_ipv6 && ipv6_failed != "")
1307 {
1308 MERROR("Failed to bind IPv6: " << ipv6_failed);
1309 if (ipv4_failed != "")
1310 {
1311 throw std::runtime_error("Failed to bind IPv4 and IPv6");
1312 }
1313 }
1314
1315 return true;
1316 }
1317 catch (const std::exception &e)
1318 {
1319 MFATAL("Error starting server: " << e.what());
1320 return false;
1321 }
1322 catch (...)
1323 {
1324 MFATAL("Error starting server");
1325 return false;
1326 }
1327 }
1328 //-----------------------------------------------------------------------------
1329 template<class t_protocol_handler>
1330 bool boosted_tcp_server<t_protocol_handler>::init_server(const std::string port, const std::string& address,
1331 const std::string port_ipv6, const std::string address_ipv6, bool use_ipv6, bool require_ipv4,
1332 ssl_options_t ssl_options)
1333 {
1334 uint32_t p = 0;
1335 uint32_t p_ipv6 = 0;
1336
1337 if (port.size() && !string_tools::get_xtype_from_string(p, port)) {
1338 MERROR("Failed to convert port no = " << port);
1339 return false;
1340 }
1341
1342 if (port_ipv6.size() && !string_tools::get_xtype_from_string(p_ipv6, port_ipv6)) {
1343 MERROR("Failed to convert port no = " << port_ipv6);
1344 return false;
1345 }
1346 return this->init_server(p, address, p_ipv6, address_ipv6, use_ipv6, require_ipv4, std::move(ssl_options));
1347 }
1348 //---------------------------------------------------------------------------------
1349 template<class t_protocol_handler>
1350 bool boosted_tcp_server<t_protocol_handler>::worker_thread()
1351 {
1352 TRY_ENTRY();
1353 const uint32_t local_thr_index = m_thread_index++; // atomically increment, getting value before increment
1354 std::string thread_name = std::string("[") + m_thread_name_prefix;
1355 thread_name += boost::to_string(local_thr_index) + "]";
1356 MLOG_SET_THREAD_NAME(thread_name);
1357 // _fact("Thread name: " << m_thread_name_prefix);
1358 while(!m_stop_signal_sent)
1359 {
1360 try
1361 {
1362 io_context_.run();
1363 return true;
1364 }
1365 catch(const std::exception& ex)
1366 {
1367 _erro("Exception at server worker thread, what=" << ex.what());
1368 }
1369 catch(...)
1370 {
1371 _erro("Exception at server worker thread, unknown execption");
1372 }
1373 }
1374 //_info("Worker thread finished");
1375 return true;
1376 CATCH_ENTRY_L0("boosted_tcp_server<t_protocol_handler>::worker_thread", false);
1377 }
1378 //---------------------------------------------------------------------------------
1379 template<class t_protocol_handler>
1380 void boosted_tcp_server<t_protocol_handler>::set_threads_prefix(const std::string& prefix_name)
1381 {
1382 m_thread_name_prefix = prefix_name;
1383 auto it = server_type_map.find(m_thread_name_prefix);
1384 if (it==server_type_map.end()) throw std::runtime_error("Unknown prefix/server type:" + std::string(prefix_name));
1385 auto connection_type = it->second; // the value of type
1386 MINFO("Set server type to: " << connection_type << " from name: " << m_thread_name_prefix << ", prefix_name = " << prefix_name);
1387 }
1388 //---------------------------------------------------------------------------------
1389 template<class t_protocol_handler>
1390 void boosted_tcp_server<t_protocol_handler>::set_connection_filter(i_connection_filter* pfilter)
1391 {
1392 assert(m_state != nullptr); // always set in constructor
1393 m_state->pfilter = pfilter;
1394 }
1395 //---------------------------------------------------------------------------------
1396 template<class t_protocol_handler>
1397 void boosted_tcp_server<t_protocol_handler>::set_connection_limit(i_connection_limit* plimit)
1398 {
1399 assert(m_state != nullptr); // always set in constructor
1400 m_state->plimit = plimit;
1401 }
1402 //---------------------------------------------------------------------------------
1403 template<class t_protocol_handler>
1404 void boosted_tcp_server<t_protocol_handler>::set_response_soft_limit(const std::size_t limit)
1405 {
1406 assert(m_state != nullptr); // always set in constructor
1407 m_state->response_soft_limit = limit;
1408 }
1409 //---------------------------------------------------------------------------------
1410 template<class t_protocol_handler>
1411 bool boosted_tcp_server<t_protocol_handler>::run_server(size_t threads_count, bool wait, const boost::thread::attributes& attrs)
1412 {
1413 TRY_ENTRY();
1414 m_threads_count = threads_count;
1415 m_main_thread_id = boost::this_thread::get_id();
1416 MLOG_SET_THREAD_NAME("[SRV_MAIN]");
1417 while(!m_stop_signal_sent)
1418 {
1419
1420 // Create a pool of threads to run all of the io_contexts.
1421 CRITICAL_REGION_BEGIN(m_threads_lock);
1422 for (std::size_t i = 0; i < threads_count; ++i)
1423 {
1424 boost::shared_ptr<boost::thread> thread(new boost::thread(
1425 attrs, boost::bind(&boosted_tcp_server<t_protocol_handler>::worker_thread, this)));
1426 _note("Run server thread name: " << m_thread_name_prefix);
1427 m_threads.push_back(thread);
1428 }
1429 CRITICAL_REGION_END();
1430 // Wait for all threads in the pool to exit.
1431 if (wait)
1432 {
1433 _fact("JOINING all threads");
1434 for (std::size_t i = 0; i < m_threads.size(); ++i) {
1435 m_threads[i]->join();
1436 }
1437 _fact("JOINING all threads - almost");
1438 m_threads.clear();
1439 _fact("JOINING all threads - DONE");
1440
1441 }
1442 else {
1443 _dbg1("Reiniting OK.");
1444 return true;
1445 }
1446
1447 if(wait && !m_stop_signal_sent)
1448 {
1449 //some problems with the listening socket ?..
1450 _dbg1("Net service stopped without stop request, restarting...");
1451 if(!this->init_server(m_port, m_address, m_port_ipv6, m_address_ipv6, m_use_ipv6, m_require_ipv4))
1452 {
1453 _dbg1("Reiniting service failed, exit.");
1454 return false;
1455 }else
1456 {
1457 _dbg1("Reiniting OK.");
1458 }
1459 }
1460 }
1461 return true;
1462 CATCH_ENTRY_L0("boosted_tcp_server<t_protocol_handler>::run_server", false);
1463 }
1464 //---------------------------------------------------------------------------------
1465 template<class t_protocol_handler>
1466 bool boosted_tcp_server<t_protocol_handler>::is_thread_worker()
1467 {
1468 TRY_ENTRY();
1469 CRITICAL_REGION_LOCAL(m_threads_lock);
1470 BOOST_FOREACH(boost::shared_ptr<boost::thread>& thp, m_threads)
1471 {
1472 if(thp->get_id() == boost::this_thread::get_id())
1473 return true;
1474 }
1475 if(m_threads_count == 1 && boost::this_thread::get_id() == m_main_thread_id)
1476 return true;
1477 return false;
1478 CATCH_ENTRY_L0("boosted_tcp_server<t_protocol_handler>::is_thread_worker", false);
1479 }
1480 //---------------------------------------------------------------------------------
1481 template<class t_protocol_handler>
1482 bool boosted_tcp_server<t_protocol_handler>::timed_wait_server_stop(uint64_t wait_mseconds)
1483 {
1484 TRY_ENTRY();
1485 boost::chrono::milliseconds ms(wait_mseconds);
1486 for (std::size_t i = 0; i < m_threads.size(); ++i)
1487 {
1488 if(m_threads[i]->joinable() && !m_threads[i]->try_join_for(ms))
1489 {
1490 _dbg1("Interrupting thread " << m_threads[i]->native_handle());
1491 m_threads[i]->interrupt();
1492 }
1493 }
1494 return true;
1495 CATCH_ENTRY_L0("boosted_tcp_server<t_protocol_handler>::timed_wait_server_stop", false);
1496 }
1497 //---------------------------------------------------------------------------------
1498 template<class t_protocol_handler>
1499 void boosted_tcp_server<t_protocol_handler>::send_stop_signal()
1500 {
1501 m_stop_signal_sent = true;
1502 typename connection<t_protocol_handler>::shared_state *state = static_cast<typename connection<t_protocol_handler>::shared_state*>(m_state.get());
1503 state->stop_signal_sent = true;
1504 TRY_ENTRY();
1505 connections_mutex.lock();
1506 for (auto &c: connections_)
1507 {
1508 c->cancel();
1509 }
1510 connections_.clear();
1511 connections_mutex.unlock();
1512 io_context_.stop();
1513 CATCH_ENTRY_L0("boosted_tcp_server<t_protocol_handler>::send_stop_signal()", void());
1514 }
1515 //---------------------------------------------------------------------------------
1516 template<class t_protocol_handler>
1517 void boosted_tcp_server<t_protocol_handler>::handle_accept_ipv4(const boost::system::error_code& e)
1518 {
1519 this->handle_accept(e, false);
1520 }
1521 //---------------------------------------------------------------------------------
1522 template<class t_protocol_handler>
1523 void boosted_tcp_server<t_protocol_handler>::handle_accept_ipv6(const boost::system::error_code& e)
1524 {
1525 this->handle_accept(e, true);
1526 }
1527 //---------------------------------------------------------------------------------
1528 template<class t_protocol_handler>
1529 void boosted_tcp_server<t_protocol_handler>::handle_accept(const boost::system::error_code& e, bool ipv6)
1530 {
1531 MDEBUG("handle_accept");
1532
1533 boost::asio::ip::tcp::acceptor* current_acceptor = &acceptor_;
1534 connection_ptr* current_new_connection = &new_connection_;
1535 auto accept_function_pointer = &boosted_tcp_server<t_protocol_handler>::handle_accept_ipv4;
1536 if (ipv6)
1537 {
1538 current_acceptor = &acceptor_ipv6;
1539 current_new_connection = &new_connection_ipv6;
1540 accept_function_pointer = &boosted_tcp_server<t_protocol_handler>::handle_accept_ipv6;
1541 }
1542
1543 try
1544 {
1545 if (!e)
1546 {
1547 if (m_connection_type == e_connection_type_RPC) {
1548 const char *ssl_message = "unknown";
1549 switch ((*current_new_connection)->get_ssl_support())
1550 {
1551 case epee::net_utils::ssl_support_t::e_ssl_support_disabled: ssl_message = "disabled"; break;
1552 case epee::net_utils::ssl_support_t::e_ssl_support_enabled: ssl_message = "enabled"; break;
1553 case epee::net_utils::ssl_support_t::e_ssl_support_autodetect: ssl_message = "autodetection"; break;
1554 }
1555 MDEBUG("New server for RPC connections, SSL " << ssl_message);
1556 (*current_new_connection)->setRpcStation(); // hopefully this is not needed actually
1557 }
1558 connection_ptr conn(std::move((*current_new_connection)));
1559 (*current_new_connection).reset(new connection<t_protocol_handler>(io_context_, m_state, m_connection_type, conn->get_ssl_support()));
1560 current_acceptor->async_accept((*current_new_connection)->socket(),
1561 boost::bind(accept_function_pointer, this,
1562 boost::asio::placeholders::error));
1563
1564 boost::asio::socket_base::keep_alive opt(true);
1565 conn->socket().set_option(opt);
1566
1567 bool res;
1568 if (default_remote.get_type_id() == net_utils::address_type::invalid)
1569 res = conn->start(true, 1 < m_threads_count);
1570 else
1571 res = conn->start(true, 1 < m_threads_count, default_remote);
1572 if (!res)
1573 {
1574 conn->cancel();
1575 return;
1576 }
1577 conn->save_dbg_log();
1578 return;
1579 }
1580 else
1581 {
1582 MERROR("Error in boosted_tcp_server<t_protocol_handler>::handle_accept: " << e);
1583 }
1584 }
1585 catch (const std::exception &e)
1586 {
1587 MERROR("Exception in boosted_tcp_server<t_protocol_handler>::handle_accept: " << e.what());
1588 }
1589
1590 // error path, if e or exception
1591 assert(m_state != nullptr); // always set in constructor
1592 _erro("Some problems at accept: " << e.message() << ", connections_count = " << m_state->sock_count);
1593 misc_utils::sleep_no_w(100);
1594 (*current_new_connection).reset(new connection<t_protocol_handler>(io_context_, m_state, m_connection_type, (*current_new_connection)->get_ssl_support()));
1595 current_acceptor->async_accept((*current_new_connection)->socket(),
1596 boost::bind(accept_function_pointer, this,
1597 boost::asio::placeholders::error));
1598 }
1599 //---------------------------------------------------------------------------------
1600 template<class t_protocol_handler>
1601 bool boosted_tcp_server<t_protocol_handler>::add_connection(t_connection_context& out, boost::asio::ip::tcp::socket&& sock, network_address real_remote, epee::net_utils::ssl_support_t ssl_support)
1602 {
1603 if(std::addressof(get_io_context()) == std::addressof(sock.get_executor().context()))
1604 {
1605 connection_ptr conn(new connection<t_protocol_handler>(io_context_, std::move(sock), m_state, m_connection_type, ssl_support));
1606 if(conn->start(false, 1 < m_threads_count, std::move(real_remote)))
1607 {
1608 conn->get_context(out);
1609 conn->save_dbg_log();
1610 return true;
1611 }
1612 }
1613 else
1614 {
1615 MWARNING(out << " was not added, socket/io_context mismatch");
1616 }
1617 return false;
1618 }
1619 //---------------------------------------------------------------------------------
1620 template<class t_protocol_handler>
1621 typename boosted_tcp_server<t_protocol_handler>::try_connect_result_t boosted_tcp_server<t_protocol_handler>::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)
1622 {
1623 TRY_ENTRY();
1624
1625 sock_.open(remote_endpoint.protocol());
1626 if(bind_ip != "0.0.0.0" && bind_ip != "0" && bind_ip != "" )
1627 {
1628 boost::asio::ip::tcp::endpoint local_endpoint(boost::asio::ip::make_address(bind_ip), 0);
1629 boost::system::error_code ec;
1630 sock_.bind(local_endpoint, ec);
1631 if (ec)
1632 {
1633 MERROR("Error binding to " << bind_ip << ": " << ec.message());
1634 if (sock_.is_open())
1635 sock_.close();
1636 return CONNECT_FAILURE;
1637 }
1638 }
1639
1640 /*
1641 NOTICE: be careful to make sync connection from event handler: in case if all threads suddenly do sync connect, there will be no thread to dispatch events from io service.
1642 */
1643
1644 boost::system::error_code ec = boost::asio::error::would_block;
1645
1646 //have another free thread(s), work in wait mode, without event handling
1647 struct local_async_context
1648 {
1649 boost::system::error_code ec;
1650 boost::mutex connect_mut;
1651 boost::condition_variable cond;
1652 };
1653
1654 boost::shared_ptr<local_async_context> local_shared_context(new local_async_context());
1655 local_shared_context->ec = boost::asio::error::would_block;
1656 boost::unique_lock<boost::mutex> lock(local_shared_context->connect_mut);
1657 auto connect_callback = [](boost::system::error_code ec_, boost::shared_ptr<local_async_context> shared_context)
1658 {
1659 shared_context->connect_mut.lock(); shared_context->ec = ec_; shared_context->cond.notify_one(); shared_context->connect_mut.unlock();
1660 };
1661
1662 sock_.async_connect(remote_endpoint, std::bind<void>(connect_callback, std::placeholders::_1, local_shared_context));
1663 while(local_shared_context->ec == boost::asio::error::would_block)
1664 {
1665 bool r = local_shared_context->cond.timed_wait(lock, boost::get_system_time() + boost::posix_time::milliseconds(conn_timeout));
1666 if (m_stop_signal_sent)
1667 {
1668 if (sock_.is_open())
1669 sock_.close();
1670 return CONNECT_FAILURE;
1671 }
1672 if(local_shared_context->ec == boost::asio::error::would_block && !r)
1673 {
1674 //timeout
1675 sock_.close();
1676 _dbg3("Failed to connect to " << adr << ":" << port << ", because of timeout (" << conn_timeout << ")");
1677 return CONNECT_FAILURE;
1678 }
1679 }
1680 ec = local_shared_context->ec;
1681
1682 if (ec || !sock_.is_open())
1683 {
1684 _dbg3("Some problems at connect, message: " << ec.message());
1685 if (sock_.is_open())
1686 sock_.close();
1687 return CONNECT_FAILURE;
1688 }
1689
1690 _dbg3("Connected success to " << adr << ':' << port);
1691
1692 const ssl_support_t ssl_support = new_connection_l->get_ssl_support();
1693 if (ssl_support == epee::net_utils::ssl_support_t::e_ssl_support_enabled || ssl_support == epee::net_utils::ssl_support_t::e_ssl_support_autodetect)
1694 {
1695 // Handshake
1696 MDEBUG("Handshaking SSL...");
1697 if (!new_connection_l->handshake(boost::asio::ssl::stream_base::client))
1698 {
1699 if (ssl_support == epee::net_utils::ssl_support_t::e_ssl_support_autodetect)
1700 {
1701 boost::system::error_code ignored_ec;
1702 sock_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec);
1703 sock_.close();
1704 return CONNECT_NO_SSL;
1705 }
1706 MERROR("SSL handshake failed");
1707 if (sock_.is_open())
1708 sock_.close();
1709 return CONNECT_FAILURE;
1710 }
1711 }
1712
1713 return CONNECT_SUCCESS;
1714
1715 CATCH_ENTRY_L0("boosted_tcp_server<t_protocol_handler>::try_connect", CONNECT_FAILURE);
1716 }
1717 //---------------------------------------------------------------------------------
1718 template<class t_protocol_handler>
1719 bool boosted_tcp_server<t_protocol_handler>::connect(const std::string& adr, const std::string& port, uint32_t conn_timeout, t_connection_context& conn_context, const std::string& bind_ip, epee::net_utils::ssl_support_t ssl_support)
1720 {
1721 TRY_ENTRY();
1722
1723 connection_ptr new_connection_l(new connection<t_protocol_handler>(io_context_, m_state, m_connection_type, ssl_support) );
1724 connections_mutex.lock();
1725 connections_.insert(new_connection_l);
1726 MDEBUG("connections_ size now " << connections_.size());
1727 connections_mutex.unlock();
1728 epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){ CRITICAL_REGION_LOCAL(connections_mutex); connections_.erase(new_connection_l); });
1729 boost::asio::ip::tcp::socket& sock_ = new_connection_l->socket();
1730
1731 bool try_ipv6 = false;
1732
1733 boost::asio::ip::tcp::resolver resolver(io_context_);
1734 boost::asio::ip::tcp::resolver::results_type results{};
1735 boost::system::error_code resolve_error;
1736
1737 try
1738 {
1739 //resolving ipv4 address as ipv6 throws, catch here and move on
1740 results = resolver.resolve(
1741 boost::asio::ip::tcp::v4(), adr, port, boost::asio::ip::tcp::resolver::canonical_name, resolve_error
1742 );
1743 }
1744 catch (const boost::system::system_error& e)
1745 {
1746 if (!m_use_ipv6 || (resolve_error != boost::asio::error::host_not_found &&
1747 resolve_error != boost::asio::error::host_not_found_try_again))
1748 {
1749 throw;
1750 }
1751 try_ipv6 = true;
1752 }
1753 catch (...)
1754 {
1755 throw;
1756 }
1757
1758 std::string bind_ip_to_use;
1759
1760 if(results.empty())
1761 {
1762 if (!m_use_ipv6)
1763 {
1764 _erro("Failed to resolve " << adr);
1765 return false;
1766 }
1767 else
1768 {
1769 try_ipv6 = true;
1770 MINFO("Resolving address as IPv4 failed, trying IPv6");
1771 }
1772 }
1773 else
1774 {
1775 bind_ip_to_use = bind_ip;
1776 }
1777
1778 if (try_ipv6)
1779 {
1780 results = resolver.resolve(
1781 boost::asio::ip::tcp::v6(), adr, port, boost::asio::ip::tcp::resolver::canonical_name, resolve_error
1782 );
1783
1784 if(results.empty())
1785 {
1786 _erro("Failed to resolve " << adr);
1787 return false;
1788 }
1789 else
1790 {
1791 if (bind_ip == "0.0.0.0")
1792 {
1793 bind_ip_to_use = "::";
1794 }
1795 else
1796 {
1797 bind_ip_to_use = "";
1798 }
1799
1800 }
1801
1802 }
1803
1804 const auto iterator = results.begin();
1805
1806 MDEBUG("Trying to connect to " << adr << ":" << port << ", bind_ip = " << bind_ip_to_use);
1807
1808 //boost::asio::ip::tcp::endpoint remote_endpoint(boost::asio::ip::address::from_string(addr.c_str()), port);
1809 boost::asio::ip::tcp::endpoint remote_endpoint(*iterator);
1810
1811 auto try_connect_result = try_connect(new_connection_l, adr, port, sock_, remote_endpoint, bind_ip_to_use, conn_timeout, ssl_support);
1812 if (try_connect_result == CONNECT_FAILURE)
1813 return false;
1814 if (ssl_support == epee::net_utils::ssl_support_t::e_ssl_support_autodetect && try_connect_result == CONNECT_NO_SSL)
1815 {
1816 // we connected, but could not connect with SSL, try without
1817 MERROR("SSL handshake failed on an autodetect connection, reconnecting without SSL");
1818 new_connection_l->disable_ssl();
1819 try_connect_result = try_connect(new_connection_l, adr, port, sock_, remote_endpoint, bind_ip_to_use, conn_timeout, epee::net_utils::ssl_support_t::e_ssl_support_disabled);
1820 if (try_connect_result != CONNECT_SUCCESS)
1821 return false;
1822 }
1823
1824 // start adds the connection to the config object's list, so we don't need to have it locally anymore
1825 connections_mutex.lock();
1826 connections_.erase(new_connection_l);
1827 connections_mutex.unlock();
1828 bool r = new_connection_l->start(false, 1 < m_threads_count);
1829 if (r)
1830 {
1831 new_connection_l->get_context(conn_context);
1832 }
1833 else
1834 {
1835 assert(m_state != nullptr); // always set in constructor
1836 _erro("[sock " << new_connection_l->socket().native_handle() << "] Failed to start connection, connections_count = " << m_state->sock_count);
1837 }
1838
1839 new_connection_l->save_dbg_log();
1840
1841 return r;
1842
1843 CATCH_ENTRY_L0("boosted_tcp_server<t_protocol_handler>::connect", false);
1844 }
1845 //---------------------------------------------------------------------------------
1846 template<class t_protocol_handler> template<class t_callback>
1847 bool boosted_tcp_server<t_protocol_handler>::connect_async(const std::string& adr, const std::string& port, uint32_t conn_timeout, const t_callback &cb, const std::string& bind_ip, epee::net_utils::ssl_support_t ssl_support)
1848 {
1849 TRY_ENTRY();
1850 connection_ptr new_connection_l(new connection<t_protocol_handler>(io_context_, m_state, m_connection_type, ssl_support) );
1851 connections_mutex.lock();
1852 connections_.insert(new_connection_l);
1853 MDEBUG("connections_ size now " << connections_.size());
1854 connections_mutex.unlock();
1855 epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){ CRITICAL_REGION_LOCAL(connections_mutex); connections_.erase(new_connection_l); });
1856 boost::asio::ip::tcp::socket& sock_ = new_connection_l->socket();
1857
1858 bool try_ipv6 = false;
1859
1860 boost::asio::ip::tcp::resolver resolver(io_context_);
1861 boost::asio::ip::tcp::resolver::results_type results{};
1862 boost::system::error_code resolve_error;
1863
1864 try
1865 {
1866 //resolving ipv4 address as ipv6 throws, catch here and move on
1867 results = resolver.resolve(
1868 boost::asio::ip::tcp::v4(), adr, port, boost::asio::ip::tcp::resolver::canonical_name, resolve_error
1869 );
1870 }
1871 catch (const boost::system::system_error& e)
1872 {
1873 if (!m_use_ipv6 || (resolve_error != boost::asio::error::host_not_found &&
1874 resolve_error != boost::asio::error::host_not_found_try_again))
1875 {
1876 throw;
1877 }
1878 try_ipv6 = true;
1879 }
1880 catch (...)
1881 {
1882 throw;
1883 }
1884
1885 if(results.empty())
1886 {
1887 if (!try_ipv6)
1888 {
1889 _erro("Failed to resolve " << adr);
1890 return false;
1891 }
1892 else
1893 {
1894 MINFO("Resolving address as IPv4 failed, trying IPv6");
1895 }
1896 }
1897
1898 if (try_ipv6)
1899 {
1900 results = resolver.resolve(
1901 boost::asio::ip::tcp::v6(), adr, port, boost::asio::ip::tcp::resolver::canonical_name, resolve_error
1902 );
1903
1904 if(results.empty())
1905 {
1906 _erro("Failed to resolve " << adr);
1907 return false;
1908 }
1909 }
1910
1911 boost::asio::ip::tcp::endpoint remote_endpoint(*results.begin());
1912
1913 sock_.open(remote_endpoint.protocol());
1914 if(bind_ip != "0.0.0.0" && bind_ip != "0" && bind_ip != "" )
1915 {
1916 boost::asio::ip::tcp::endpoint local_endpoint(boost::asio::ip::make_address(bind_ip.c_str()), 0);
1917 boost::system::error_code ec;
1918 sock_.bind(local_endpoint, ec);
1919 if (ec)
1920 {
1921 MERROR("Error binding to " << bind_ip << ": " << ec.message());
1922 if (sock_.is_open())
1923 sock_.close();
1924 return false;
1925 }
1926 }
1927
1928 boost::shared_ptr<boost::asio::deadline_timer> sh_deadline(new boost::asio::deadline_timer(io_context_));
1929 //start deadline
1930 sh_deadline->expires_from_now(boost::posix_time::milliseconds(conn_timeout));
1931 sh_deadline->async_wait([=](const boost::system::error_code& error)
1932 {
1933 if(error != boost::asio::error::operation_aborted)
1934 {
1935 _dbg3("Failed to connect to " << adr << ':' << port << ", because of timeout (" << conn_timeout << ")");
1936 new_connection_l->socket().close();
1937 }
1938 });
1939 //start async connect
1940 sock_.async_connect(remote_endpoint, [=](const boost::system::error_code& ec_)
1941 {
1942 t_connection_context conn_context = AUTO_VAL_INIT(conn_context);
1943 boost::system::error_code ignored_ec;
1944 boost::asio::ip::tcp::socket::endpoint_type lep = new_connection_l->socket().local_endpoint(ignored_ec);
1945 if(!ec_)
1946 {//success
1947 if(!sh_deadline->cancel())
1948 {
1949 cb(conn_context, boost::asio::error::operation_aborted);//this mean that deadline timer already queued callback with cancel operation, rare situation
1950 }else
1951 {
1952 _dbg3("[sock " << new_connection_l->socket().native_handle() << "] Connected success to " << adr << ':' << port <<
1953 " from " << lep.address().to_string() << ':' << lep.port());
1954
1955 // start adds the connection to the config object's list, so we don't need to have it locally anymore
1956 connections_mutex.lock();
1957 connections_.erase(new_connection_l);
1958 connections_mutex.unlock();
1959 bool r = new_connection_l->start(false, 1 < m_threads_count);
1960 if (r)
1961 {
1962 new_connection_l->get_context(conn_context);
1963 cb(conn_context, ec_);
1964 }
1965 else
1966 {
1967 _dbg3("[sock " << new_connection_l->socket().native_handle() << "] Failed to start connection to " << adr << ':' << port);
1968 cb(conn_context, boost::asio::error::fault);
1969 }
1970 }
1971 }else
1972 {
1973 _dbg3("[sock " << new_connection_l->socket().native_handle() << "] Failed to connect to " << adr << ':' << port <<
1974 " from " << lep.address().to_string() << ':' << lep.port() << ": " << ec_.message() << ':' << ec_.value());
1975 cb(conn_context, ec_);
1976 }
1977 });
1978 return true;
1979 CATCH_ENTRY_L0("boosted_tcp_server<t_protocol_handler>::connect_async", false);
1980 }
1981
1982 } // namespace
1983 } // namespace