Debian Codegraph @

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

raw symbols SCIP
1 // Copyright (c) 2006-2013, Andrey N. Sabelnikov, www.sabelnikov.net
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are met:
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above copyright
9 // notice, this list of conditions and the following disclaimer in the
10 // documentation and/or other materials provided with the distribution.
11 // * Neither the name of the Andrey N. Sabelnikov nor the
12 // names of its contributors may be used to endorse or promote products
13 // derived from this software without specific prior written permission.
14 //
15 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
16 // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17 // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18 // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER BE LIABLE FOR ANY
19 // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20 // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
22 // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 //
26
27
28
29
30 #pragma once
31
32 //#include <Winsock2.h>
33 //#include <Ws2tcpip.h>
34 #include <atomic>
35 #include <string>
36 #include <boost/version.hpp>
37 #include <boost/asio/io_context.hpp>
38 #include <boost/asio/ip/tcp.hpp>
39 #include <boost/asio/read.hpp>
40 #include <boost/asio/ssl.hpp>
41 #include <boost/asio/steady_timer.hpp>
42 #include <boost/thread/future.hpp>
43 #include <boost/lambda/bind.hpp>
44 #include <boost/lambda/lambda.hpp>
45 #include <boost/system/error_code.hpp>
46 #include <boost/utility/string_ref.hpp>
47 #include <functional>
48 #include "net/net_utils_base.h"
49 #include "net/net_ssl.h"
50 #include "misc_language.h"
51
52 #undef MONERO_DEFAULT_LOG_CATEGORY
53 #define MONERO_DEFAULT_LOG_CATEGORY "net"
54
55 #ifndef MAKE_IP
56 #define MAKE_IP( a1, a2, a3, a4 ) (a1|(a2<<8)|(a3<<16)|(a4<<24))
57 #endif
58
59
60 namespace epee
61 {
62 namespace net_utils
63 {
64 struct direct_connect
65 {
66 boost::unique_future<boost::asio::ip::tcp::socket>
67 operator()(const std::string& addr, const std::string& port, boost::asio::steady_timer&) const;
68 };
69
70
71 class blocked_mode_client
72 {
73 enum try_connect_result_t
74 {
75 CONNECT_SUCCESS,
76 CONNECT_FAILURE,
77 CONNECT_NO_SSL,
78 };
79
80
81
82 struct handler_obj
83 {
84 handler_obj(boost::system::error_code& error, size_t& bytes_transferred):ref_error(error), ref_bytes_transferred(bytes_transferred)
85 {}
86 handler_obj(const handler_obj& other_obj):ref_error(other_obj.ref_error), ref_bytes_transferred(other_obj.ref_bytes_transferred)
87 {}
88
89 boost::system::error_code& ref_error;
90 size_t& ref_bytes_transferred;
91
92 void operator()(const boost::system::error_code& error, // Result of operation.
93 std::size_t bytes_transferred // Number of bytes read.
94 )
95 {
96 ref_error = error;
97 ref_bytes_transferred = bytes_transferred;
98 }
99 };
100
101 public:
102 inline
103 blocked_mode_client() :
104 m_io_service(),
105 m_ctx(boost::asio::ssl::context::tlsv12),
106 m_ssl_socket(new boost::asio::ssl::stream<boost::asio::ip::tcp::socket>(m_io_service, m_ctx)),
107 m_connector(direct_connect{}),
108 m_ssl_options(epee::net_utils::ssl_support_t::e_ssl_support_autodetect),
109 m_initialized(true),
110 m_connected(false),
111 m_deadline(m_io_service, std::chrono::steady_clock::time_point::max()),
112 m_shutdowned(false),
113 m_cancel_read(false),
114 m_bytes_sent(0),
115 m_bytes_received(0)
116 {
117 check_deadline();
118 }
119
120 /*! The first/second parameters are host/port respectively. The third
121 parameter is for setting the timeout callback - the timer is
122 already set by the caller, the callee only needs to set the
123 behavior.
124
125 Additional asynchronous operations should be queued using the
126 `io_service` from the timer. The implementation should assume
127 multi-threaded I/O processing.
128
129 If the callee cannot start an asynchronous operation, an exception
130 should be thrown to signal an immediate failure.
131
132 The return value is a future to a connected socket. Asynchronous
133 failures should use the `set_exception` method. */
134 using connect_func = boost::unique_future<boost::asio::ip::tcp::socket>(const std::string&, const std::string&, boost::asio::steady_timer&);
135
136 inline
137 ~blocked_mode_client()
138 {
139 //profile_tools::local_coast lc("~blocked_mode_client()", 3);
140 try { shutdown(); }
141 catch(...) { /* ignore */ }
142 }
143
144 inline void set_ssl(ssl_options_t ssl_options)
145 {
146 if (ssl_options)
147 m_ctx = ssl_options.create_context();
148 else
149 m_ctx = boost::asio::ssl::context(boost::asio::ssl::context::tlsv12);
150 m_ssl_options = std::move(ssl_options);
151 }
152
153 inline
154 bool connect(const std::string& addr, int port, std::chrono::milliseconds timeout)
155 {
156 return connect(addr, std::to_string(port), timeout);
157 }
158
159 inline
160 try_connect_result_t try_connect(const std::string& addr, const std::string& port, std::chrono::milliseconds timeout)
161 {
162 m_deadline.expires_after(timeout);
163 boost::unique_future<boost::asio::ip::tcp::socket> connection = m_connector(addr, port, m_deadline);
164 for (;;)
165 {
166 m_io_service.restart();
167 m_io_service.run_one();
168
169 if (connection.is_ready())
170 break;
171 }
172
173 m_ssl_socket->next_layer() = connection.get();
174 m_deadline.cancel();
175 if (m_ssl_socket->next_layer().is_open())
176 {
177 m_connected = true;
178 m_deadline.expires_at(std::chrono::steady_clock::time_point::max());
179 // SSL Options
180 if (m_ssl_options.support == epee::net_utils::ssl_support_t::e_ssl_support_enabled || m_ssl_options.support == epee::net_utils::ssl_support_t::e_ssl_support_autodetect)
181 {
182 if (!m_ssl_options.handshake(m_io_service, *m_ssl_socket, boost::asio::ssl::stream_base::client, {}, addr, timeout))
183 {
184 if (m_ssl_options.support == epee::net_utils::ssl_support_t::e_ssl_support_autodetect)
185 {
186 boost::system::error_code ignored_ec;
187 m_ssl_socket->next_layer().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec);
188 m_ssl_socket->next_layer().close();
189 m_connected = false;
190 return CONNECT_NO_SSL;
191 }
192 else
193 {
194 MWARNING("Failed to establish SSL connection");
195 m_connected = false;
196 return CONNECT_FAILURE;
197 }
198 }
199 }
200 return CONNECT_SUCCESS;
201 }else
202 {
203 MWARNING("Some problems at connect, expected open socket");
204 return CONNECT_FAILURE;
205 }
206
207 }
208
209 inline
210 bool connect(const std::string& addr, const std::string& port, std::chrono::milliseconds timeout)
211 {
212 m_connected = false;
213 try
214 {
215 m_ssl_socket->next_layer().close();
216
217 // Set SSL options
218 // disable sslv2
219 m_ssl_socket.reset(new boost::asio::ssl::stream<boost::asio::ip::tcp::socket>(m_io_service, m_ctx));
220
221 // Get a list of endpoints corresponding to the server name.
222
223 try_connect_result_t try_connect_result = try_connect(addr, port, timeout);
224 if (try_connect_result == CONNECT_FAILURE)
225 return false;
226 if (m_ssl_options.support == epee::net_utils::ssl_support_t::e_ssl_support_autodetect)
227 {
228 if (try_connect_result == CONNECT_NO_SSL)
229 {
230 MERROR("SSL handshake failed on an autodetect connection, reconnecting without SSL");
231 m_ssl_options.support = epee::net_utils::ssl_support_t::e_ssl_support_disabled;
232 if (try_connect(addr, port, timeout) != CONNECT_SUCCESS)
233 return false;
234 }
235 }
236 }
237 catch(const boost::system::system_error& er)
238 {
239 MDEBUG("Some problems at connect, message: " << er.what());
240 return false;
241 }
242 catch(...)
243 {
244 MDEBUG("Some fatal problems.");
245 return false;
246 }
247
248 return true;
249 }
250 //! Change the connection routine (proxy, etc.)
251 void set_connector(std::function<connect_func> connector)
252 {
253 m_connector = std::move(connector);
254 }
255
256 inline
257 bool disconnect()
258 {
259 try
260 {
261 if(m_connected)
262 {
263 m_connected = false;
264 if(m_ssl_options)
265 shutdown_ssl();
266 m_ssl_socket->next_layer().shutdown(boost::asio::ip::tcp::socket::shutdown_both);
267 }
268 }
269 catch(const boost::system::system_error& er)
270 {
271 LOG_ERROR("Some problems at disconnect, message: " << er.what());
272 return false;
273 }
274 catch(...)
275 {
276 LOG_ERROR("Some fatal problems.");
277 return false;
278 }
279 return true;
280 }
281
282
283 inline
284 bool send(const boost::string_ref buff, std::chrono::milliseconds timeout)
285 {
286
287 try
288 {
289 m_deadline.expires_after(timeout);
290
291 // Set up the variable that receives the result of the asynchronous
292 // operation. The error code is set to would_block to signal that the
293 // operation is incomplete. Asio guarantees that its asynchronous
294 // operations will never fail with would_block, so any other value in
295 // ec indicates completion.
296 boost::system::error_code ec = boost::asio::error::would_block;
297
298 // Start the asynchronous operation itself. The boost::lambda function
299 // object is used as a callback and will update the ec variable when the
300 // operation completes. The blocking_udp_client.cpp example shows how you
301 // can use boost::bind rather than boost::lambda.
302 async_write(buff.data(), buff.size(), ec);
303
304 // Block until the asynchronous operation has completed.
305 while (ec == boost::asio::error::would_block)
306 {
307 m_io_service.restart();
308 m_io_service.run_one();
309 }
310
311 if (ec)
312 {
313 LOG_PRINT_L3("Problems at write: " << ec.message());
314 m_connected = false;
315 return false;
316 }else
317 {
318 m_deadline.expires_at(std::chrono::steady_clock::time_point::max());
319 m_bytes_sent += buff.size();
320 }
321 }
322
323 catch(const boost::system::system_error& er)
324 {
325 LOG_ERROR("Some problems at connect, message: " << er.what());
326 return false;
327 }
328 catch(...)
329 {
330 LOG_ERROR("Some fatal problems.");
331 return false;
332 }
333
334 return true;
335 }
336
337 inline
338 bool send(const void* data, size_t sz)
339 {
340 try
341 {
342 /*
343 m_deadline.expires_from_now(boost::posix_time::milliseconds(m_reciev_timeout));
344
345 // Set up the variable that receives the result of the asynchronous
346 // operation. The error code is set to would_block to signal that the
347 // operation is incomplete. Asio guarantees that its asynchronous
348 // operations will never fail with would_block, so any other value in
349 // ec indicates completion.
350 boost::system::error_code ec = boost::asio::error::would_block;
351
352 // Start the asynchronous operation itself. The boost::lambda function
353 // object is used as a callback and will update the ec variable when the
354 // operation completes. The blocking_udp_client.cpp example shows how you
355 // can use boost::bind rather than boost::lambda.
356 boost::asio::async_write(m_socket, boost::asio::buffer(data, sz), boost::lambda::var(ec) = boost::lambda::_1);
357
358 // Block until the asynchronous operation has completed.
359 while (ec == boost::asio::error::would_block)
360 {
361 m_io_service.run_one();
362 }
363 */
364 boost::system::error_code ec;
365
366 size_t writen = write(data, sz, ec);
367
368 if (!writen || ec)
369 {
370 LOG_PRINT_L3("Problems at write: " << ec.message());
371 m_connected = false;
372 return false;
373 }else
374 {
375 m_deadline.expires_at(std::chrono::steady_clock::time_point::max());
376 m_bytes_sent += sz;
377 }
378 }
379
380 catch(const boost::system::system_error& er)
381 {
382 LOG_ERROR("Some problems at send, message: " << er.what());
383 m_connected = false;
384 return false;
385 }
386 catch(...)
387 {
388 LOG_ERROR("Some fatal problems.");
389 return false;
390 }
391
392 return true;
393 }
394
395 bool is_connected(bool *ssl = NULL)
396 {
397 if (!m_connected || !m_ssl_socket->next_layer().is_open())
398 return false;
399 if (ssl)
400 *ssl = m_ssl_options.support != ssl_support_t::e_ssl_support_disabled;
401 return true;
402 }
403
404 inline
405 bool recv(std::string& buff, std::chrono::milliseconds timeout)
406 {
407
408 try
409 {
410 // Set a deadline for the asynchronous operation. Since this function uses
411 // a composed operation (async_read_until), the deadline applies to the
412 // entire operation, rather than individual reads from the socket.
413 m_deadline.expires_after(timeout);
414
415 // Set up the variable that receives the result of the asynchronous
416 // operation. The error code is set to would_block to signal that the
417 // operation is incomplete. Asio guarantees that its asynchronous
418 // operations will never fail with would_block, so any other value in
419 // ec indicates completion.
420 //boost::system::error_code ec = boost::asio::error::would_block;
421
422 // Start the asynchronous operation itself. The boost::lambda function
423 // object is used as a callback and will update the ec variable when the
424 // operation completes. The blocking_udp_client.cpp example shows how you
425 // can use boost::bind rather than boost::lambda.
426
427 boost::system::error_code ec = boost::asio::error::would_block;
428 size_t bytes_transfered = 0;
429
430 handler_obj hndlr(ec, bytes_transfered);
431
432 static const size_t max_size = 16384;
433 buff.resize(max_size);
434
435 async_read(&buff[0], max_size, boost::asio::transfer_at_least(1), hndlr);
436
437 // Block until the asynchronous operation has completed.
438 while (ec == boost::asio::error::would_block && !m_shutdowned)
439 {
440 m_io_service.restart();
441 m_io_service.run_one();
442 }
443
444 if (m_cancel_read)
445 {
446 LOG_ERROR("Cancelling read, returning false");
447 m_connected = false;
448 return false;
449 }
450
451 if (ec)
452 {
453 MTRACE("READ ENDS: Connection err_code " << ec.value());
454 if(ec == boost::asio::error::eof)
455 {
456 MTRACE("Connection err_code eof.");
457 //connection closed there, empty
458 buff.clear();
459 return true;
460 }
461
462 MDEBUG("Problems at read: " << ec.message());
463 m_connected = false;
464 return false;
465 }else
466 {
467 MTRACE("READ ENDS: Success. bytes_tr: " << bytes_transfered);
468 m_deadline.expires_at(std::chrono::steady_clock::time_point::max());
469 }
470
471 /*if(!bytes_transfered)
472 return false;*/
473
474 m_bytes_received += bytes_transfered;
475 buff.resize(bytes_transfered);
476 return true;
477 }
478
479 catch(const boost::system::system_error& er)
480 {
481 LOG_ERROR("Some problems at read, message: " << er.what());
482 m_connected = false;
483 return false;
484 }
485 catch(...)
486 {
487 LOG_ERROR("Some fatal problems at read.");
488 return false;
489 }
490
491
492
493 return false;
494
495 }
496
497 inline bool recv_n(std::string& buff, int64_t sz, std::chrono::milliseconds timeout)
498 {
499
500 try
501 {
502 // Set a deadline for the asynchronous operation. Since this function uses
503 // a composed operation (async_read_until), the deadline applies to the
504 // entire operation, rather than individual reads from the socket.
505 m_deadline.expires_after(timeout);
506
507 // Set up the variable that receives the result of the asynchronous
508 // operation. The error code is set to would_block to signal that the
509 // operation is incomplete. Asio guarantees that its asynchronous
510 // operations will never fail with would_block, so any other value in
511 // ec indicates completion.
512 //boost::system::error_code ec = boost::asio::error::would_block;
513
514 // Start the asynchronous operation itself. The boost::lambda function
515 // object is used as a callback and will update the ec variable when the
516 // operation completes. The blocking_udp_client.cpp example shows how you
517 // can use boost::bind rather than boost::lambda.
518
519 buff.resize(static_cast<size_t>(sz));
520 boost::system::error_code ec = boost::asio::error::would_block;
521 size_t bytes_transfered = 0;
522
523
524 handler_obj hndlr(ec, bytes_transfered);
525 async_read((char*)buff.data(), buff.size(), boost::asio::transfer_at_least(buff.size()), hndlr);
526
527 // Block until the asynchronous operation has completed.
528 while (ec == boost::asio::error::would_block && !m_shutdowned)
529 {
530 m_io_service.run_one();
531 }
532
533 if (ec)
534 {
535 LOG_PRINT_L3("Problems at read: " << ec.message());
536 m_connected = false;
537 return false;
538 }else
539 {
540 m_deadline.expires_at(std::chrono::steady_clock::time_point::max());
541 }
542
543 m_bytes_received += bytes_transfered;
544 if(bytes_transfered != buff.size())
545 {
546 LOG_ERROR("Transferred mismatch with transfer_at_least value: m_bytes_transferred=" << bytes_transfered << " at_least value=" << buff.size());
547 return false;
548 }
549
550 return true;
551 }
552
553 catch(const boost::system::system_error& er)
554 {
555 LOG_ERROR("Some problems at read, message: " << er.what());
556 m_connected = false;
557 return false;
558 }
559 catch(...)
560 {
561 LOG_ERROR("Some fatal problems at read.");
562 return false;
563 }
564
565
566
567 return false;
568 }
569
570 bool shutdown()
571 {
572 m_deadline.cancel();
573 boost::system::error_code ec;
574 if(m_ssl_options)
575 shutdown_ssl();
576 m_ssl_socket->next_layer().cancel(ec);
577 if(ec)
578 MDEBUG("Problems at cancel: " << ec.message());
579 m_ssl_socket->next_layer().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
580 if(ec)
581 MDEBUG("Problems at shutdown: " << ec.message());
582 m_ssl_socket->next_layer().close(ec);
583 if(ec)
584 MDEBUG("Problems at close: " << ec.message());
585 m_shutdowned = true;
586 m_connected = false;
587 return true;
588 }
589
590 bool cancel_read()
591 {
592 MDEBUG("Cancelling read");
593 m_cancel_read = true;
594 return true;
595 }
596
597 boost::asio::io_context& get_io_service()
598 {
599 return m_io_service;
600 }
601
602 boost::asio::ip::tcp::socket& get_socket()
603 {
604 return m_ssl_socket->next_layer();
605 }
606
607 uint64_t get_bytes_sent() const
608 {
609 return m_bytes_sent;
610 }
611
612 uint64_t get_bytes_received() const
613 {
614 return m_bytes_received;
615 }
616
617 private:
618
619 void check_deadline()
620 {
621 // Check whether the deadline has passed. We compare the deadline against
622 // the current time since a new asynchronous operation may have moved the
623 // deadline before this actor had a chance to run.
624 if (m_deadline.expiry() <= std::chrono::steady_clock::now())
625 {
626 // The deadline has passed. The socket is closed so that any outstanding
627 // asynchronous operations are cancelled. This allows the blocked
628 // connect(), read_line() or write_line() functions to return.
629 LOG_PRINT_L3("Timed out socket");
630 m_connected = false;
631 m_ssl_socket->next_layer().close();
632
633 // There is no longer an active deadline. The expiry is set to positive
634 // infinity so that the actor takes no action until a new deadline is set.
635 m_deadline.expires_at(std::chrono::steady_clock::time_point::max());
636 }
637
638 // Put the actor back to sleep.
639 m_deadline.async_wait(boost::bind(&blocked_mode_client::check_deadline, this));
640 }
641
642 void shutdown_ssl() {
643 // ssl socket shutdown blocks if server doesn't respond. We close after 2 secs
644 boost::system::error_code ec = boost::asio::error::would_block;
645 m_deadline.expires_after(std::chrono::milliseconds(2000));
646 m_ssl_socket->async_shutdown(boost::lambda::var(ec) = boost::lambda::_1);
647 while (ec == boost::asio::error::would_block)
648 {
649 m_io_service.restart();
650 m_io_service.run_one();
651 }
652 // Ignore "short read" error
653 if (ec.category() == boost::asio::error::get_ssl_category() &&
654 ec.value() !=
655 #if BOOST_VERSION >= 106200
656 boost::asio::ssl::error::stream_truncated
657 #else // older Boost supports only OpenSSL 1.0, so 1.0-only macros are appropriate
658 ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SHORT_READ)
659 #endif
660 )
661 MDEBUG("Problems at ssl shutdown: " << ec.message());
662 }
663
664 protected:
665 bool write(const void* data, size_t sz, boost::system::error_code& ec)
666 {
667 bool success;
668 if(m_ssl_options.support != ssl_support_t::e_ssl_support_disabled)
669 success = boost::asio::write(*m_ssl_socket, boost::asio::buffer(data, sz), ec);
670 else
671 success = boost::asio::write(m_ssl_socket->next_layer(), boost::asio::buffer(data, sz), ec);
672 return success;
673 }
674
675 void async_write(const void* data, size_t sz, boost::system::error_code& ec)
676 {
677 if(m_ssl_options.support != ssl_support_t::e_ssl_support_disabled)
678 boost::asio::async_write(*m_ssl_socket, boost::asio::buffer(data, sz), boost::lambda::var(ec) = boost::lambda::_1);
679 else
680 boost::asio::async_write(m_ssl_socket->next_layer(), boost::asio::buffer(data, sz), boost::lambda::var(ec) = boost::lambda::_1);
681 }
682
683 void async_read(char* buff, size_t sz, boost::asio::detail::transfer_at_least_t transfer_at_least, handler_obj& hndlr)
684 {
685 if(m_ssl_options.support == ssl_support_t::e_ssl_support_disabled)
686 boost::asio::async_read(m_ssl_socket->next_layer(), boost::asio::buffer(buff, sz), transfer_at_least, hndlr);
687 else
688 boost::asio::async_read(*m_ssl_socket, boost::asio::buffer(buff, sz), transfer_at_least, hndlr);
689
690 }
691
692 protected:
693 boost::asio::io_context m_io_service;
694 boost::asio::ssl::context m_ctx;
695 std::shared_ptr<boost::asio::ssl::stream<boost::asio::ip::tcp::socket>> m_ssl_socket;
696 std::function<connect_func> m_connector;
697 ssl_options_t m_ssl_options;
698 bool m_initialized;
699 bool m_connected;
700 boost::asio::steady_timer m_deadline;
701 std::atomic<bool> m_shutdowned;
702 std::atomic<bool> m_cancel_read;
703 std::atomic<uint64_t> m_bytes_sent;
704 std::atomic<uint64_t> m_bytes_received;
705 };
706 }
707 }
708