Debian Codegraph @

monero/src/p2p/net_node.inl

raw
1 // Copyright (c) 2014-2022, The Monero Project
2 //
3 // All rights reserved.
4 //
5 // Redistribution and use in source and binary forms, with or without modification, are
6 // permitted provided that the following conditions are met:
7 //
8 // 1. Redistributions of source code must retain the above copyright notice, this list of
9 // conditions and the following disclaimer.
10 //
11 // 2. Redistributions in binary form must reproduce the above copyright notice, this list
12 // of conditions and the following disclaimer in the documentation and/or other
13 // materials provided with the distribution.
14 //
15 // 3. Neither the name of the copyright holder nor the names of its contributors may be
16 // used to endorse or promote products derived from this software without specific
17 // prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
20 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
22 // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
27 // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 //
29 // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
30
31 // IP blocking adapted from Boolberry
32
33 #include <algorithm>
34 #include <boost/bind/bind.hpp>
35 #include <boost/date_time/posix_time/posix_time.hpp>
36 #include <boost/filesystem/operations.hpp>
37 #include <boost/optional/optional.hpp>
38 #include <boost/thread/thread.hpp>
39 #include <boost/uuid/uuid_io.hpp>
40 #include <boost/algorithm/string.hpp>
41 #include <atomic>
42 #include <functional>
43 #include <limits>
44 #include <memory>
45 #include <tuple>
46 #include <vector>
47
48 #include "version.h"
49 #include "string_tools.h"
50 #include "common/util.h"
51 #include "common/dns_utils.h"
52 #include "common/pruning.h"
53 #include "net/error.h"
54 #include "net/net_helper.h"
55 #include "math_helper.h"
56 #include "misc_log_ex.h"
57 #include "p2p_protocol_defs.h"
58 #include "crypto/crypto.h"
59 #include "storages/levin_abstract_invoke2.h"
60 #include "cryptonote_core/cryptonote_core.h"
61 #include "net/parse.h"
62
63 #include <miniupnp/miniupnpc/miniupnpc.h>
64 #include <miniupnp/miniupnpc/upnpcommands.h>
65 #include <miniupnp/miniupnpc/upnperrors.h>
66
67 #undef MONERO_DEFAULT_LOG_CATEGORY
68 #define MONERO_DEFAULT_LOG_CATEGORY "net.p2p"
69
70 #define NET_MAKE_IP(b1,b2,b3,b4) ((LPARAM)(((DWORD)(b1)<<24)+((DWORD)(b2)<<16)+((DWORD)(b3)<<8)+((DWORD)(b4))))
71
72 #define MIN_WANTED_SEED_NODES 12
73
74 static inline boost::asio::ip::address_v4 make_address_v4_from_v6(const boost::asio::ip::address_v6& a)
75 {
76 const auto &bytes = a.to_bytes();
77 uint32_t v4 = 0;
78 v4 = (v4 << 8) | bytes[12];
79 v4 = (v4 << 8) | bytes[13];
80 v4 = (v4 << 8) | bytes[14];
81 v4 = (v4 << 8) | bytes[15];
82 return boost::asio::ip::address_v4(v4);
83 }
84
85 namespace nodetool
86 {
87 template<class t_payload_net_handler>
88 node_server<t_payload_net_handler>::~node_server()
89 {
90 // tcp server uses io_context in destructor, and every zone uses
91 // io_service from public zone.
92 for (auto current = m_network_zones.begin(); current != m_network_zones.end(); /* below */)
93 {
94 if (current->first != epee::net_utils::zone::public_)
95 current = m_network_zones.erase(current);
96 else
97 ++current;
98 }
99 }
100 //-----------------------------------------------------------------------------------
101 inline bool append_net_address(std::vector<epee::net_utils::network_address> & seed_nodes, std::string const & addr, uint16_t default_port);
102 //-----------------------------------------------------------------------------------
103 template<class t_payload_net_handler>
104 void node_server<t_payload_net_handler>::init_options(boost::program_options::options_description& desc)
105 {
106 command_line::add_arg(desc, arg_p2p_bind_ip);
107 command_line::add_arg(desc, arg_p2p_bind_ipv6_address);
108 command_line::add_arg(desc, arg_p2p_bind_port, false);
109 command_line::add_arg(desc, arg_p2p_bind_port_ipv6, false);
110 command_line::add_arg(desc, arg_p2p_use_ipv6);
111 command_line::add_arg(desc, arg_p2p_ignore_ipv4);
112 command_line::add_arg(desc, arg_p2p_external_port);
113 command_line::add_arg(desc, arg_p2p_allow_local_ip);
114 command_line::add_arg(desc, arg_p2p_add_peer);
115 command_line::add_arg(desc, arg_p2p_add_priority_node);
116 command_line::add_arg(desc, arg_p2p_add_exclusive_node);
117 command_line::add_arg(desc, arg_p2p_seed_node);
118 command_line::add_arg(desc, arg_tx_proxy);
119 command_line::add_arg(desc, arg_anonymous_inbound);
120 command_line::add_arg(desc, arg_ban_list);
121 command_line::add_arg(desc, arg_p2p_hide_my_port);
122 command_line::add_arg(desc, arg_no_sync);
123 command_line::add_arg(desc, arg_enable_dns_blocklist);
124 command_line::add_arg(desc, arg_no_igd);
125 command_line::add_arg(desc, arg_igd);
126 command_line::add_arg(desc, arg_out_peers);
127 command_line::add_arg(desc, arg_in_peers);
128 command_line::add_arg(desc, arg_tos_flag);
129 command_line::add_arg(desc, arg_limit_rate_up);
130 command_line::add_arg(desc, arg_limit_rate_down);
131 command_line::add_arg(desc, arg_limit_rate);
132 command_line::add_arg(desc, arg_pad_transactions);
133 command_line::add_arg(desc, arg_max_connections_per_ip);
134 }
135 //-----------------------------------------------------------------------------------
136 template<class t_payload_net_handler>
137 bool node_server<t_payload_net_handler>::init_config()
138 {
139 TRY_ENTRY();
140 auto storage = peerlist_storage::open(m_config_folder + "/" + P2P_NET_DATA_FILENAME);
141 if (storage)
142 m_peerlist_storage = std::move(*storage);
143
144 network_zone& public_zone = m_network_zones[epee::net_utils::zone::public_];
145 public_zone.m_config.m_support_flags = P2P_SUPPORT_FLAGS;
146 public_zone.m_config.m_peer_id = crypto::rand<uint64_t>();
147 m_first_connection_maker_call = true;
148
149 CATCH_ENTRY_L0("node_server::init_config", false);
150 return true;
151 }
152 //-----------------------------------------------------------------------------------
153 template<class t_payload_net_handler>
154 void node_server<t_payload_net_handler>::for_each_connection(std::function<bool(typename t_payload_net_handler::connection_context&, peerid_type, uint32_t)> f)
155 {
156 for(auto& zone : m_network_zones)
157 {
158 zone.second.m_net_server.get_config_object().foreach_connection([&](p2p_connection_context& cntx){
159 return f(cntx, cntx.peer_id, cntx.support_flags);
160 });
161 }
162 }
163 //-----------------------------------------------------------------------------------
164 template<class t_payload_net_handler>
165 bool node_server<t_payload_net_handler>::for_connection(const boost::uuids::uuid &connection_id, std::function<bool(typename t_payload_net_handler::connection_context&, peerid_type, uint32_t)> f)
166 {
167 for(auto& zone : m_network_zones)
168 {
169 const bool result = zone.second.m_net_server.get_config_object().for_connection(connection_id, [&](p2p_connection_context& cntx){
170 return f(cntx, cntx.peer_id, cntx.support_flags);
171 });
172 if (result)
173 return true;
174 }
175 return false;
176 }
177 //-----------------------------------------------------------------------------------
178 template<class t_payload_net_handler>
179 bool node_server<t_payload_net_handler>::is_remote_host_allowed(const epee::net_utils::network_address &address, time_t *t)
180 {
181 CRITICAL_REGION_LOCAL(m_blocked_hosts_lock);
182
183 const time_t now = time(nullptr);
184
185 // look in the hosts list
186 auto it = m_blocked_hosts.find(address.host_str());
187 if (it != m_blocked_hosts.end())
188 {
189 if (now >= it->second)
190 {
191 m_blocked_hosts.erase(it);
192 MCLOG_CYAN(el::Level::Info, "global", "Host " << address.host_str() << " unblocked.");
193 it = m_blocked_hosts.end();
194 }
195 else
196 {
197 if (t)
198 *t = it->second - now;
199 return false;
200 }
201 }
202
203 // manually loop in subnets
204 if (address.get_type_id() == epee::net_utils::address_type::ipv4)
205 {
206 auto ipv4_address = address.template as<epee::net_utils::ipv4_network_address>();
207 std::map<epee::net_utils::ipv4_network_subnet, time_t>::iterator it;
208 for (it = m_blocked_subnets.begin(); it != m_blocked_subnets.end(); )
209 {
210 if (now >= it->second)
211 {
212 it = m_blocked_subnets.erase(it);
213 MCLOG_CYAN(el::Level::Info, "global", "Subnet " << it->first.host_str() << " unblocked.");
214 continue;
215 }
216 if (it->first.matches(ipv4_address))
217 {
218 if (t)
219 *t = it->second - now;
220 return false;
221 }
222 ++it;
223 }
224 }
225
226 // not found in hosts or subnets, allowed
227 return true;
228 }
229 //-----------------------------------------------------------------------------------
230 template<class t_payload_net_handler>
231 bool node_server<t_payload_net_handler>::is_host_limit(const epee::net_utils::network_address &address)
232 {
233 const network_zone& zone = m_network_zones.at(address.get_zone());
234 if (zone.m_current_number_of_in_peers >= zone.m_config.m_net_config.max_in_connection_count) // in peers limit
235 {
236 MWARNING("Exceeded max incoming connections, so dropping this one.");
237 return true;
238 }
239
240 if(has_too_many_connections(address))
241 {
242 MWARNING("CONNECTION FROM " << address.host_str() << " REFUSED, too many connections from the same address");
243 return true;
244 }
245
246 return false;
247 }
248
249 //-----------------------------------------------------------------------------------
250 template<class t_payload_net_handler>
251 bool node_server<t_payload_net_handler>::block_host(epee::net_utils::network_address addr, time_t seconds, bool add_only)
252 {
253 if(!addr.is_blockable())
254 return false;
255
256 const time_t now = time(nullptr);
257 bool added = false;
258
259 CRITICAL_REGION_LOCAL(m_blocked_hosts_lock);
260 time_t limit;
261 if (now > std::numeric_limits<time_t>::max() - seconds)
262 limit = std::numeric_limits<time_t>::max();
263 else
264 limit = now + seconds;
265 const std::string host_str = addr.host_str();
266 auto it = m_blocked_hosts.find(host_str);
267 if (it == m_blocked_hosts.end())
268 {
269 m_blocked_hosts[host_str] = limit;
270
271 // if the host was already blocked due to being in a blocked subnet, let it be silent
272 bool matches_blocked_subnet = false;
273 if (addr.get_type_id() == epee::net_utils::address_type::ipv4)
274 {
275 auto ipv4_address = addr.template as<epee::net_utils::ipv4_network_address>();
276 for (auto jt = m_blocked_subnets.begin(); jt != m_blocked_subnets.end(); ++jt)
277 {
278 if (jt->first.matches(ipv4_address))
279 {
280 matches_blocked_subnet = true;
281 break;
282 }
283 }
284 }
285 if (!matches_blocked_subnet)
286 added = true;
287 }
288 else if (it->second < limit || !add_only)
289 it->second = limit;
290
291 // drop any connection to that address. This should only have to look into
292 // the zone related to the connection, but really make sure everything is
293 // swept ...
294 std::vector<boost::uuids::uuid> conns;
295 for(auto& zone : m_network_zones)
296 {
297 zone.second.m_net_server.get_config_object().foreach_connection([&](const p2p_connection_context& cntxt)
298 {
299 if (cntxt.m_remote_address.is_same_host(addr))
300 {
301 conns.push_back(cntxt.m_connection_id);
302 }
303 return true;
304 });
305
306 peerlist_entry pe{};
307 pe.adr = addr;
308 if (addr.port() == 0)
309 {
310 zone.second.m_peerlist.evict_host_from_peerlist(true, pe);
311 zone.second.m_peerlist.evict_host_from_peerlist(false, pe);
312 }
313 else
314 {
315 zone.second.m_peerlist.remove_from_peer_white(pe);
316 zone.second.m_peerlist.remove_from_peer_gray(pe);
317 zone.second.m_peerlist.remove_from_peer_anchor(addr);
318 }
319
320 for (const auto &c: conns)
321 zone.second.m_net_server.get_config_object().close(c);
322
323 conns.clear();
324 }
325
326 if (added)
327 MCLOG_CYAN(el::Level::Info, "global", "Host " << host_str << " blocked.");
328 else
329 MINFO("Host " << host_str << " block time updated.");
330 return true;
331 }
332 //-----------------------------------------------------------------------------------
333 template<class t_payload_net_handler>
334 bool node_server<t_payload_net_handler>::unblock_host(const epee::net_utils::network_address &address)
335 {
336 CRITICAL_REGION_LOCAL(m_blocked_hosts_lock);
337 auto i = m_blocked_hosts.find(address.host_str());
338 if (i == m_blocked_hosts.end())
339 return false;
340 m_blocked_hosts.erase(i);
341 MCLOG_CYAN(el::Level::Info, "global", "Host " << address.host_str() << " unblocked.");
342 return true;
343 }
344 //-----------------------------------------------------------------------------------
345 template<class t_payload_net_handler>
346 bool node_server<t_payload_net_handler>::block_subnet(const epee::net_utils::ipv4_network_subnet &subnet, time_t seconds)
347 {
348 const time_t now = time(nullptr);
349
350 CRITICAL_REGION_LOCAL(m_blocked_hosts_lock);
351 time_t limit;
352 if (now > std::numeric_limits<time_t>::max() - seconds)
353 limit = std::numeric_limits<time_t>::max();
354 else
355 limit = now + seconds;
356 const bool added = m_blocked_subnets.find(subnet) == m_blocked_subnets.end();
357 m_blocked_subnets[subnet] = limit;
358
359 // drop any connection to that subnet. This should only have to look into
360 // the zone related to the connection, but really make sure everything is
361 // swept ...
362 std::vector<boost::uuids::uuid> conns;
363 for(auto& zone : m_network_zones)
364 {
365 zone.second.m_net_server.get_config_object().foreach_connection([&](const p2p_connection_context& cntxt)
366 {
367 if (cntxt.m_remote_address.get_type_id() != epee::net_utils::ipv4_network_address::get_type_id())
368 return true;
369 auto ipv4_address = cntxt.m_remote_address.template as<epee::net_utils::ipv4_network_address>();
370 if (subnet.matches(ipv4_address))
371 {
372 conns.push_back(cntxt.m_connection_id);
373 }
374 return true;
375 });
376 for (const auto &c: conns)
377 zone.second.m_net_server.get_config_object().close(c);
378
379 for (int i = 0; i < 2; ++i)
380 zone.second.m_peerlist.filter(i == 0, [&subnet](const peerlist_entry &pe){
381 if (pe.adr.get_type_id() != epee::net_utils::ipv4_network_address::get_type_id())
382 return false;
383 return subnet.matches(pe.adr.as<const epee::net_utils::ipv4_network_address>());
384 });
385
386 conns.clear();
387 }
388
389 if (added)
390 MCLOG_CYAN(el::Level::Info, "global", "Subnet " << subnet.host_str() << " blocked.");
391 else
392 MINFO("Subnet " << subnet.host_str() << " blocked.");
393 return true;
394 }
395 //-----------------------------------------------------------------------------------
396 template<class t_payload_net_handler>
397 bool node_server<t_payload_net_handler>::unblock_subnet(const epee::net_utils::ipv4_network_subnet &subnet)
398 {
399 CRITICAL_REGION_LOCAL(m_blocked_hosts_lock);
400 auto i = m_blocked_subnets.find(subnet);
401 if (i == m_blocked_subnets.end())
402 return false;
403 m_blocked_subnets.erase(i);
404 MCLOG_CYAN(el::Level::Info, "global", "Subnet " << subnet.host_str() << " unblocked.");
405 return true;
406 }
407 //-----------------------------------------------------------------------------------
408 template<class t_payload_net_handler>
409 bool node_server<t_payload_net_handler>::add_host_fail(const epee::net_utils::network_address &address, unsigned int score)
410 {
411 if(!address.is_blockable())
412 return false;
413
414 CRITICAL_REGION_LOCAL(m_host_fails_score_lock);
415 uint64_t fails = m_host_fails_score[address.host_str()] += score;
416 MDEBUG("Host " << address.host_str() << " fail score=" << fails);
417 if(fails > P2P_IP_FAILS_BEFORE_BLOCK)
418 {
419 auto it = m_host_fails_score.find(address.host_str());
420 CHECK_AND_ASSERT_MES(it != m_host_fails_score.end(), false, "internal error");
421 it->second = P2P_IP_FAILS_BEFORE_BLOCK/2;
422 block_host(address);
423 }
424 return true;
425 }
426 //-----------------------------------------------------------------------------------
427 template<class t_payload_net_handler>
428 bool node_server<t_payload_net_handler>::handle_command_line(
429 const boost::program_options::variables_map& vm
430 )
431 {
432 bool testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on);
433 bool stagenet = command_line::get_arg(vm, cryptonote::arg_stagenet_on);
434 const bool pad_txs = command_line::get_arg(vm, arg_pad_transactions);
435 m_nettype = testnet ? cryptonote::TESTNET : stagenet ? cryptonote::STAGENET : cryptonote::MAINNET;
436
437 network_zone& public_zone = m_network_zones[epee::net_utils::zone::public_];
438 public_zone.m_connect = &public_connect;
439 public_zone.m_bind_ip = command_line::get_arg(vm, arg_p2p_bind_ip);
440 public_zone.m_bind_ipv6_address = command_line::get_arg(vm, arg_p2p_bind_ipv6_address);
441 public_zone.m_port = command_line::get_arg(vm, arg_p2p_bind_port);
442 public_zone.m_port_ipv6 = command_line::get_arg(vm, arg_p2p_bind_port_ipv6);
443 public_zone.m_can_pingback = true;
444 m_external_port = command_line::get_arg(vm, arg_p2p_external_port);
445 m_allow_local_ip = command_line::get_arg(vm, arg_p2p_allow_local_ip);
446 const bool has_no_igd = command_line::get_arg(vm, arg_no_igd);
447 const std::string sigd = command_line::get_arg(vm, arg_igd);
448 if (sigd == "enabled")
449 {
450 if (has_no_igd)
451 {
452 MFATAL("Cannot have both --" << arg_no_igd.name << " and --" << arg_igd.name << " enabled");
453 return false;
454 }
455 m_igd = igd;
456 }
457 else if (sigd == "disabled")
458 {
459 m_igd = no_igd;
460 }
461 else if (sigd == "delayed")
462 {
463 if (has_no_igd && !command_line::is_arg_defaulted(vm, arg_igd))
464 {
465 MFATAL("Cannot have both --" << arg_no_igd.name << " and --" << arg_igd.name << " delayed");
466 return false;
467 }
468 m_igd = has_no_igd ? no_igd : delayed_igd;
469 }
470 else
471 {
472 MFATAL("Invalid value for --" << arg_igd.name << ", expected enabled, disabled or delayed");
473 return false;
474 }
475 m_offline = command_line::get_arg(vm, cryptonote::arg_offline);
476 m_use_ipv6 = command_line::get_arg(vm, arg_p2p_use_ipv6);
477 m_require_ipv4 = !command_line::get_arg(vm, arg_p2p_ignore_ipv4);
478 public_zone.m_notifier = cryptonote::levin::notify{
479 public_zone.m_net_server.get_io_context(), public_zone.m_net_server.get_config_shared(), nullptr, epee::net_utils::zone::public_, pad_txs, m_payload_handler.get_core()
480 };
481
482 if (command_line::has_arg(vm, arg_p2p_add_peer))
483 {
484 std::vector<std::string> perrs = command_line::get_arg(vm, arg_p2p_add_peer);
485 for(const std::string& pr_str: perrs)
486 {
487 nodetool::peerlist_entry pe = AUTO_VAL_INIT(pe);
488 pe.id = crypto::rand<uint64_t>();
489 const uint16_t default_port = cryptonote::get_config(m_nettype).P2P_DEFAULT_PORT;
490 expect<epee::net_utils::network_address> adr = net::get_network_address(pr_str, default_port);
491 if (adr)
492 {
493 add_zone(adr->get_zone());
494 pe.adr = std::move(*adr);
495 m_command_line_peers.push_back(std::move(pe));
496 continue;
497 }
498 CHECK_AND_ASSERT_MES(
499 adr == net::error::unsupported_address, false, "Bad address (\"" << pr_str << "\"): " << adr.error().message()
500 );
501
502 std::vector<epee::net_utils::network_address> resolved_addrs;
503 bool r = append_net_address(resolved_addrs, pr_str, default_port);
504 CHECK_AND_ASSERT_MES(r, false, "Failed to parse or resolve address from string: " << pr_str);
505 for (const epee::net_utils::network_address& addr : resolved_addrs)
506 {
507 pe.id = crypto::rand<uint64_t>();
508 pe.adr = addr;
509 m_command_line_peers.push_back(pe);
510 }
511 }
512 }
513
514 if (command_line::has_arg(vm,arg_p2p_add_exclusive_node))
515 {
516 if (!parse_peers_and_add_to_container(vm, arg_p2p_add_exclusive_node, m_exclusive_peers))
517 return false;
518 }
519
520 if (command_line::has_arg(vm, arg_p2p_add_priority_node))
521 {
522 if (!parse_peers_and_add_to_container(vm, arg_p2p_add_priority_node, m_priority_peers))
523 return false;
524 }
525
526 if (command_line::has_arg(vm, arg_p2p_seed_node))
527 {
528 boost::unique_lock<boost::shared_mutex> lock(public_zone.m_seed_nodes_lock);
529
530 if (!parse_peers_and_add_to_container(vm, arg_p2p_seed_node, public_zone.m_seed_nodes))
531 return false;
532 }
533
534 if (!command_line::is_arg_defaulted(vm, arg_ban_list))
535 {
536 const std::string ban_list = command_line::get_arg(vm, arg_ban_list);
537
538 const boost::filesystem::path ban_list_path(ban_list);
539 boost::system::error_code ec;
540 if (!boost::filesystem::exists(ban_list_path, ec))
541 {
542 throw std::runtime_error("Can't find ban list file " + ban_list + " - " + ec.message());
543 }
544
545 std::string banned_ips;
546 if (!epee::file_io_utils::load_file_to_string(ban_list_path.string(), banned_ips))
547 {
548 throw std::runtime_error("Failed to read ban list file " + ban_list);
549 }
550
551 std::istringstream iss(banned_ips);
552 for (std::string line; std::getline(iss, line); )
553 {
554 // ignore comments after '#' character
555 const size_t pound_idx = line.find('#');
556 if (pound_idx != std::string::npos)
557 line.resize(pound_idx);
558
559 // trim whitespace and ignore empty lines
560 boost::trim(line);
561 if (line.empty())
562 continue;
563
564 auto subnet = net::get_ipv4_subnet_address(line);
565 if (subnet)
566 {
567 block_subnet(*subnet, std::numeric_limits<time_t>::max());
568 continue;
569 }
570 const expect<epee::net_utils::network_address> parsed_addr = net::get_network_address(line, 0);
571 if (parsed_addr)
572 {
573 block_host(*parsed_addr, std::numeric_limits<time_t>::max());
574 continue;
575 }
576 MERROR("Invalid IP address or IPv4 subnet: " << line);
577 }
578 }
579
580 if(command_line::has_arg(vm, arg_p2p_hide_my_port))
581 m_hide_my_port = true;
582
583 if (command_line::has_arg(vm, arg_no_sync))
584 m_payload_handler.set_no_sync(true);
585
586 m_enable_dns_blocklist = command_line::get_arg(vm, arg_enable_dns_blocklist);
587
588 if ( !set_max_out_peers(public_zone, command_line::get_arg(vm, arg_out_peers) ) )
589 return false;
590 else
591 m_payload_handler.set_max_out_peers(epee::net_utils::zone::public_, public_zone.m_config.m_net_config.max_out_connection_count);
592
593
594 if ( !set_max_in_peers(public_zone, command_line::get_arg(vm, arg_in_peers) ) )
595 return false;
596
597 if ( !set_tos_flag(vm, command_line::get_arg(vm, arg_tos_flag) ) )
598 return false;
599
600 if ( !set_rate_up_limit(vm, command_line::get_arg(vm, arg_limit_rate_up) ) )
601 return false;
602
603 if ( !set_rate_down_limit(vm, command_line::get_arg(vm, arg_limit_rate_down) ) )
604 return false;
605
606 if ( !set_rate_limit(vm, command_line::get_arg(vm, arg_limit_rate) ) )
607 return false;
608
609
610 epee::byte_slice noise = nullptr;
611 auto proxies = get_proxies(vm);
612 if (!proxies)
613 return false;
614
615 for (auto& proxy : *proxies)
616 {
617 network_zone& zone = add_zone(proxy.zone);
618 if (zone.m_connect != nullptr)
619 {
620 MERROR("Listed --" << arg_tx_proxy.name << " twice with " << epee::net_utils::zone_to_string(proxy.zone));
621 return false;
622 }
623 zone.m_connect = &socks_connect;
624 zone.m_proxy_address = std::move(proxy.address);
625
626 if (!set_max_out_peers(zone, proxy.max_connections))
627 return false;
628 else
629 m_payload_handler.set_max_out_peers(proxy.zone, proxy.max_connections);
630
631 epee::byte_slice this_noise = nullptr;
632 if (proxy.noise)
633 {
634 static_assert(sizeof(epee::levin::bucket_head2) < CRYPTONOTE_NOISE_BYTES, "noise bytes too small");
635 if (noise.empty())
636 noise = epee::levin::make_noise_notify(CRYPTONOTE_NOISE_BYTES);
637
638 this_noise = noise.clone();
639 }
640
641 zone.m_notifier = cryptonote::levin::notify{
642 zone.m_net_server.get_io_context(), zone.m_net_server.get_config_shared(), std::move(this_noise), proxy.zone, pad_txs, m_payload_handler.get_core()
643 };
644 }
645
646 for (const auto& zone : m_network_zones)
647 {
648 if (zone.second.m_connect == nullptr)
649 {
650 MERROR("Set outgoing peer for " << epee::net_utils::zone_to_string(zone.first) << " but did not set --" << arg_tx_proxy.name);
651 return false;
652 }
653 }
654
655 auto inbounds = get_anonymous_inbounds(vm);
656 if (!inbounds)
657 return false;
658
659 const std::size_t tx_relay_zones = m_network_zones.size();
660 for (auto& inbound : *inbounds)
661 {
662 network_zone& zone = add_zone(inbound.our_address.get_zone());
663
664 if (!zone.m_bind_ip.empty())
665 {
666 MERROR("Listed --" << arg_anonymous_inbound.name << " twice with " << epee::net_utils::zone_to_string(inbound.our_address.get_zone()) << " network");
667 return false;
668 }
669
670 if (zone.m_connect == nullptr && tx_relay_zones <= 1)
671 {
672 MERROR("Listed --" << arg_anonymous_inbound.name << " without listing any --" << arg_tx_proxy.name << ". The latter is necessary for sending local txes over anonymity networks");
673 return false;
674 }
675
676 zone.m_bind_ip = std::move(inbound.local_ip);
677 zone.m_port = std::move(inbound.local_port);
678 zone.m_net_server.set_default_remote(std::move(inbound.default_remote));
679 zone.m_our_address = std::move(inbound.our_address);
680
681 if (!set_max_in_peers(zone, inbound.max_connections))
682 return false;
683 }
684
685 max_connections = command_line::get_arg(vm, arg_max_connections_per_ip);
686
687 return true;
688 }
689 //-----------------------------------------------------------------------------------
690 inline bool append_net_address(
691 std::vector<epee::net_utils::network_address> & seed_nodes
692 , std::string const & addr
693 , uint16_t default_port
694 )
695 {
696 using namespace boost::asio;
697
698 // Split addr string into host string and port string
699 std::string host;
700 std::string port = std::to_string(default_port);
701 net::get_network_address_host_and_port(addr, host, port);
702 MINFO("Resolving node address: host=" << host << ", port=" << port);
703
704 boost::system::error_code ec;
705 io_context io_srv;
706 ip::tcp::resolver resolver(io_srv);
707 const auto results = resolver.resolve(host, port, boost::asio::ip::tcp::resolver::canonical_name, ec);
708 CHECK_AND_ASSERT_MES(!ec && !results.empty(), false, "Failed to resolve host name '" << host << "': " << ec.message() << ':' << ec.value());
709
710 for (const auto& result : results)
711 {
712 const auto& endpoint = result.endpoint();
713 if (endpoint.address().is_v4())
714 {
715 epee::net_utils::network_address na{epee::net_utils::ipv4_network_address{boost::asio::detail::socket_ops::host_to_network_long(endpoint.address().to_v4().to_uint()), endpoint.port()}};
716 seed_nodes.push_back(na);
717 MINFO("Added node: " << na.str());
718 }
719 else
720 {
721 epee::net_utils::network_address na{epee::net_utils::ipv6_network_address{endpoint.address().to_v6(), endpoint.port()}};
722 seed_nodes.push_back(na);
723 MINFO("Added node: " << na.str());
724 }
725 }
726 return true;
727 }
728
729 //-----------------------------------------------------------------------------------
730 template<class t_payload_net_handler>
731 std::set<std::string> node_server<t_payload_net_handler>::get_ip_seed_nodes() const
732 {
733 std::set<std::string> full_addrs;
734 if (m_nettype == cryptonote::TESTNET)
735 {
736 full_addrs.insert("176.9.0.187:28080");
737 full_addrs.insert("51.79.173.165:28080");
738 full_addrs.insert("192.99.8.110:28080");
739 full_addrs.insert("37.187.74.171:28080");
740 full_addrs.insert("88.99.195.15:28080");
741 }
742 else if (m_nettype == cryptonote::STAGENET)
743 {
744 full_addrs.insert("176.9.0.187:38080");
745 full_addrs.insert("51.79.173.165:38080");
746 full_addrs.insert("192.99.8.110:38080");
747 full_addrs.insert("37.187.74.171:38080");
748 full_addrs.insert("88.99.195.15:38080");
749 }
750 else if (m_nettype == cryptonote::FAKECHAIN)
751 {
752 }
753 else
754 {
755 full_addrs.insert("176.9.0.187:18080");
756 full_addrs.insert("88.198.163.90:18080");
757 full_addrs.insert("66.85.74.134:18080");
758 full_addrs.insert("51.79.173.165:18080");
759 full_addrs.insert("192.99.8.110:18080");
760 full_addrs.insert("37.187.74.171:18080");
761 full_addrs.insert("88.99.195.15:18080");
762 }
763 return full_addrs;
764 }
765 //-----------------------------------------------------------------------------------
766 template<class t_payload_net_handler>
767 std::set<std::string> node_server<t_payload_net_handler>::get_dns_seed_nodes()
768 {
769 if (!m_exclusive_peers.empty() || m_offline)
770 {
771 return {};
772 }
773 if (m_nettype == cryptonote::TESTNET)
774 {
775 return get_ip_seed_nodes();
776 }
777 if (m_nettype == cryptonote::STAGENET)
778 {
779 return get_ip_seed_nodes();
780 }
781 if (!m_enable_dns_seed_nodes)
782 {
783 // TODO: a domain can be set through socks, so that the remote side does the lookup for the DNS seed nodes.
784 m_fallback_seed_nodes_added.test_and_set();
785 return get_ip_seed_nodes();
786 }
787
788 std::set<std::string> full_addrs;
789
790 // for each hostname in the seed nodes list, attempt to DNS resolve and
791 // add the result addresses as seed nodes
792 // TODO: at some point add IPv6 support, but that won't be relevant
793 // for some time yet.
794
795 std::vector<std::vector<std::string>> dns_results;
796 dns_results.resize(m_seed_nodes_list.size());
797
798 // some libc implementation provide only a very small stack
799 // for threads, e.g. musl only gives +- 80kb, which is not
800 // enough to do a resolve with unbound. we request a stack
801 // of 1 mb, which should be plenty
802 boost::thread::attributes thread_attributes;
803 thread_attributes.set_stack_size(1024*1024);
804
805 std::list<boost::thread> dns_threads;
806 uint64_t result_index = 0;
807 for (const std::string& addr_str : m_seed_nodes_list)
808 {
809 boost::thread th = boost::thread(thread_attributes, [=, &dns_results, &addr_str]
810 {
811 MDEBUG("dns_threads[" << result_index << "] created for: " << addr_str);
812 // TODO: care about dnssec avail/valid
813 bool avail, valid;
814 std::vector<std::string> addr_list;
815
816 try
817 {
818 addr_list = tools::DNSResolver::instance().get_ipv4(addr_str, avail, valid);
819 MDEBUG("dns_threads[" << result_index << "] DNS resolve done");
820 boost::this_thread::interruption_point();
821 }
822 catch(const boost::thread_interrupted&)
823 {
824 // thread interruption request
825 // even if we now have results, finish thread without setting
826 // result variables, which are now out of scope in main thread
827 MWARNING("dns_threads[" << result_index << "] interrupted");
828 return;
829 }
830
831 MINFO("dns_threads[" << result_index << "] addr_str: " << addr_str << " number of results: " << addr_list.size());
832 dns_results[result_index] = addr_list;
833 });
834
835 dns_threads.push_back(std::move(th));
836 ++result_index;
837 }
838
839 MDEBUG("dns_threads created, now waiting for completion or timeout of " << CRYPTONOTE_DNS_TIMEOUT_MS << "ms");
840 boost::chrono::system_clock::time_point deadline = boost::chrono::system_clock::now() + boost::chrono::milliseconds(CRYPTONOTE_DNS_TIMEOUT_MS);
841 uint64_t i = 0;
842 for (boost::thread& th : dns_threads)
843 {
844 if (! th.try_join_until(deadline))
845 {
846 MWARNING("dns_threads[" << i << "] timed out, sending interrupt");
847 th.interrupt();
848 }
849 ++i;
850 }
851
852 i = 0;
853 for (const auto& result : dns_results)
854 {
855 MDEBUG("DNS lookup for " << m_seed_nodes_list[i] << ": " << result.size() << " results");
856 // if no results for node, thread's lookup likely timed out
857 if (result.size())
858 {
859 for (const auto& addr_string : result)
860 full_addrs.insert(addr_string + ":" + std::to_string(cryptonote::get_config(m_nettype).P2P_DEFAULT_PORT));
861 }
862 ++i;
863 }
864
865 // append the fallback nodes if we have too few seed nodes to start with
866 if (full_addrs.size() < MIN_WANTED_SEED_NODES)
867 {
868 if (full_addrs.empty())
869 MINFO("DNS seed node lookup either timed out or failed, falling back to defaults");
870 else
871 MINFO("Not enough DNS seed nodes found, using fallback defaults too");
872
873 for (const auto &peer: get_ip_seed_nodes())
874 full_addrs.insert(peer);
875 m_fallback_seed_nodes_added.test_and_set();
876 }
877
878 return full_addrs;
879 }
880 //-----------------------------------------------------------------------------------
881 template<class t_payload_net_handler>
882 std::set<std::string> node_server<t_payload_net_handler>::get_seed_nodes(epee::net_utils::zone zone)
883 {
884 switch (zone)
885 {
886 case epee::net_utils::zone::public_:
887 return get_dns_seed_nodes();
888 case epee::net_utils::zone::tor:
889 if (m_nettype == cryptonote::MAINNET)
890 {
891 return {
892 "zbjkbsxc5munw3qusl7j2hpcmikhqocdf4pqhnhtpzw5nt5jrmofptid.onion:18083",
893 "qz43zul2x56jexzoqgkx2trzwcfnr6l3hbtfcfx54g4r3eahy3bssjyd.onion:18083",
894 "plowsof3t5hogddwabaeiyrno25efmzfxyro2vligremt7sxpsclfaid.onion:18083",
895 "plowsoffjexmxalw73tkjmf422gq6575fc7vicuu4javzn2ynnte6tyd.onion:18083",
896 "plowsofe6cleftfmk2raiw5h2x66atrik3nja4bfd3zrfa2hdlgworad.onion:18083",
897 "aclc4e2jhhtr44guufbnwk5bzwhaecinax4yip4wr4tjn27sjsfg6zqd.onion:18083",
898 };
899 }
900 return {};
901 case epee::net_utils::zone::i2p:
902 if (m_nettype == cryptonote::MAINNET)
903 {
904 return {
905 "uqj3aphckqtjsitz7kxx5flqpwjlq5ppr3chazfued7xucv3nheq.b32.i2p",
906 "vdmnehdjkpkg57nthgnjfuaqgku673r5bpbqg56ix6fyqoywgqrq.b32.i2p",
907 "ugnlcdciyhghh2zert7c3kl4biwkirc43ke33jiy5slnd3mv2trq.b32.i2p",
908 };
909 }
910 return {};
911 default:
912 break;
913 }
914 throw std::logic_error{"Bad zone given to get_seed_nodes"};
915 }
916 //-----------------------------------------------------------------------------------
917 template<class t_payload_net_handler>
918 typename node_server<t_payload_net_handler>::network_zone& node_server<t_payload_net_handler>::add_zone(const epee::net_utils::zone zone)
919 {
920 const auto zone_ = m_network_zones.lower_bound(zone);
921 if (zone_ != m_network_zones.end() && zone_->first == zone)
922 return zone_->second;
923
924 network_zone& public_zone = m_network_zones[epee::net_utils::zone::public_];
925 return m_network_zones.emplace_hint(zone_, std::piecewise_construct, std::make_tuple(zone), std::tie(public_zone.m_net_server.get_io_context()))->second;
926 }
927 //-----------------------------------------------------------------------------------
928 template<class t_payload_net_handler>
929 bool node_server<t_payload_net_handler>::init(const boost::program_options::variables_map& vm, const std::string& proxy, bool proxy_dns_leaks_allowed)
930 {
931 bool res = handle_command_line(vm);
932 CHECK_AND_ASSERT_MES(res, false, "Failed to handle command line");
933 if (proxy.size())
934 {
935 const auto endpoint = net::get_tcp_endpoint(proxy);
936 CHECK_AND_ASSERT_MES(endpoint, false, "Failed to parse proxy: " << proxy << " - " << endpoint.error());
937 network_zone& public_zone = m_network_zones[epee::net_utils::zone::public_];
938 public_zone.m_connect = &socks_connect;
939 public_zone.m_proxy_address = *endpoint;
940 public_zone.m_can_pingback = false;
941 m_enable_dns_seed_nodes &= proxy_dns_leaks_allowed;
942 m_enable_dns_blocklist &= proxy_dns_leaks_allowed;
943 }
944
945 if (m_nettype == cryptonote::TESTNET)
946 {
947 memcpy(&m_network_id, &::config::testnet::NETWORK_ID, 16);
948 }
949 else if (m_nettype == cryptonote::STAGENET)
950 {
951 memcpy(&m_network_id, &::config::stagenet::NETWORK_ID, 16);
952 }
953 else
954 {
955 memcpy(&m_network_id, &::config::NETWORK_ID, 16);
956 }
957
958 m_config_folder = command_line::get_arg(vm, cryptonote::arg_data_dir);
959 network_zone& public_zone = m_network_zones.at(epee::net_utils::zone::public_);
960
961 if ((m_nettype == cryptonote::MAINNET && public_zone.m_port != std::to_string(::config::P2P_DEFAULT_PORT))
962 || (m_nettype == cryptonote::TESTNET && public_zone.m_port != std::to_string(::config::testnet::P2P_DEFAULT_PORT))
963 || (m_nettype == cryptonote::STAGENET && public_zone.m_port != std::to_string(::config::stagenet::P2P_DEFAULT_PORT))) {
964 m_config_folder = m_config_folder + "/" + public_zone.m_port;
965 }
966
967 res = init_config();
968 CHECK_AND_ASSERT_MES(res, false, "Failed to init config.");
969
970 for (auto& zone : m_network_zones)
971 {
972 res = zone.second.m_peerlist.init(m_peerlist_storage.take_zone(zone.first), m_allow_local_ip);
973 CHECK_AND_ASSERT_MES(res, false, "Failed to init peerlist.");
974 }
975
976 for(const auto& p: m_command_line_peers)
977 m_network_zones.at(p.adr.get_zone()).m_peerlist.append_with_peer_white(p);
978
979 //only in case if we really sure that we have external visible ip
980 m_have_address = true;
981
982 //configure self
983
984 public_zone.m_net_server.set_threads_prefix("P2P"); // all zones use these threads/asio::io_service
985
986 // from here onwards, it's online stuff
987 if (m_offline)
988 return res;
989
990 //try to bind
991 m_ssl_support = epee::net_utils::ssl_support_t::e_ssl_support_disabled;
992 for (auto& zone : m_network_zones)
993 {
994 zone.second.m_net_server.get_config_object().set_handler(this);
995 zone.second.m_net_server.get_config_object().m_invoke_timeout = P2P_DEFAULT_INVOKE_TIMEOUT;
996
997 if (!zone.second.m_bind_ip.empty())
998 {
999 std::string ipv6_addr = "";
1000 std::string ipv6_port = "";
1001 zone.second.m_net_server.set_connection_filter(this);
1002 zone.second.m_net_server.set_connection_limit(this);
1003 MINFO("Binding (IPv4) on " << zone.second.m_bind_ip << ":" << zone.second.m_port);
1004 if (!zone.second.m_bind_ipv6_address.empty() && m_use_ipv6)
1005 {
1006 ipv6_addr = zone.second.m_bind_ipv6_address;
1007 ipv6_port = zone.second.m_port_ipv6;
1008 MINFO("Binding (IPv6) on " << zone.second.m_bind_ipv6_address << ":" << zone.second.m_port_ipv6);
1009 }
1010 res = zone.second.m_net_server.init_server(zone.second.m_port, zone.second.m_bind_ip, ipv6_port, ipv6_addr, m_use_ipv6, m_require_ipv4, epee::net_utils::ssl_support_t::e_ssl_support_disabled);
1011 CHECK_AND_ASSERT_MES(res, false, "Failed to bind server");
1012 }
1013 }
1014
1015 m_listening_port = public_zone.m_net_server.get_binded_port();
1016 MLOG_GREEN(el::Level::Info, "Net service bound (IPv4) to " << public_zone.m_bind_ip << ":" << m_listening_port);
1017 if (m_use_ipv6)
1018 {
1019 m_listening_port_ipv6 = public_zone.m_net_server.get_binded_port_ipv6();
1020 MLOG_GREEN(el::Level::Info, "Net service bound (IPv6) to " << public_zone.m_bind_ipv6_address << ":" << m_listening_port_ipv6);
1021 }
1022 if(m_external_port)
1023 MDEBUG("External port defined as " << m_external_port);
1024
1025 // add UPnP port mapping
1026 if(m_igd == igd)
1027 {
1028 add_upnp_port_mapping_v4(m_listening_port);
1029 if (m_use_ipv6)
1030 {
1031 add_upnp_port_mapping_v6(m_listening_port_ipv6);
1032 }
1033 }
1034
1035 return res;
1036 }
1037 //-----------------------------------------------------------------------------------
1038 template<class t_payload_net_handler>
1039 typename node_server<t_payload_net_handler>::payload_net_handler& node_server<t_payload_net_handler>::get_payload_object()
1040 {
1041 return m_payload_handler;
1042 }
1043 //-----------------------------------------------------------------------------------
1044 template<class t_payload_net_handler>
1045 bool node_server<t_payload_net_handler>::run()
1046 {
1047 // creating thread to log number of connections
1048 mPeersLoggerThread.reset(new boost::thread([&]()
1049 {
1050 _note("Thread monitor number of peers - start");
1051 const network_zone& public_zone = m_network_zones.at(epee::net_utils::zone::public_);
1052 while (!is_closing && !public_zone.m_net_server.is_stop_signal_sent())
1053 { // main loop of thread
1054 //number_of_peers = m_net_server.get_config_object().get_connections_count();
1055 for (auto& zone : m_network_zones)
1056 {
1057 unsigned int number_of_in_peers = 0;
1058 unsigned int number_of_out_peers = 0;
1059 zone.second.m_net_server.get_config_object().foreach_connection([&](const p2p_connection_context& cntxt)
1060 {
1061 if (cntxt.m_is_income)
1062 {
1063 ++number_of_in_peers;
1064 }
1065 else
1066 {
1067 ++number_of_out_peers;
1068 }
1069 return true;
1070 }); // lambda
1071 zone.second.m_current_number_of_in_peers = number_of_in_peers;
1072 zone.second.m_current_number_of_out_peers = number_of_out_peers;
1073 }
1074 boost::this_thread::sleep_for(boost::chrono::seconds(1));
1075 } // main loop of thread
1076 _note("Thread monitor number of peers - done");
1077 })); // lambda
1078
1079 network_zone& public_zone = m_network_zones.at(epee::net_utils::zone::public_);
1080 public_zone.m_net_server.add_idle_handler(boost::bind(&node_server<t_payload_net_handler>::idle_worker, this), 1000);
1081 public_zone.m_net_server.add_idle_handler(boost::bind(&t_payload_net_handler::on_idle, &m_payload_handler), 1000);
1082
1083 //here you can set worker threads count
1084 int thrds_count = 10;
1085 boost::thread::attributes attrs;
1086 attrs.set_stack_size(THREAD_STACK_SIZE);
1087 //go to loop
1088 MINFO("Run net_service loop( " << thrds_count << " threads)...");
1089 if(!public_zone.m_net_server.run_server(thrds_count, true, attrs))
1090 {
1091 LOG_ERROR("Failed to run net tcp server!");
1092 }
1093
1094 MINFO("net_service loop stopped.");
1095 return true;
1096 }
1097 //-----------------------------------------------------------------------------------
1098 template<class t_payload_net_handler>
1099 uint64_t node_server<t_payload_net_handler>::get_public_connections_count()
1100 {
1101 auto public_zone = m_network_zones.find(epee::net_utils::zone::public_);
1102 if (public_zone == m_network_zones.end())
1103 return 0;
1104 return public_zone->second.m_net_server.get_config_object().get_connections_count();
1105 }
1106 //-----------------------------------------------------------------------------------
1107 template<class t_payload_net_handler>
1108 bool node_server<t_payload_net_handler>::deinit()
1109 {
1110 kill();
1111
1112 if (!m_offline)
1113 {
1114 for(auto& zone : m_network_zones)
1115 zone.second.m_net_server.deinit_server();
1116 // remove UPnP port mapping
1117 if(m_igd == igd)
1118 delete_upnp_port_mapping(m_listening_port);
1119 }
1120 return store_config();
1121 }
1122 //-----------------------------------------------------------------------------------
1123 template<class t_payload_net_handler>
1124 bool node_server<t_payload_net_handler>::store_config()
1125 {
1126 TRY_ENTRY();
1127
1128 if (!tools::create_directories_if_necessary(m_config_folder))
1129 {
1130 MWARNING("Failed to create data directory \"" << m_config_folder);
1131 return false;
1132 }
1133
1134 peerlist_types active{};
1135 for (auto& zone : m_network_zones)
1136 zone.second.m_peerlist.get_peerlist(active);
1137
1138 const std::string state_file_path = m_config_folder + "/" + P2P_NET_DATA_FILENAME;
1139 if (!m_peerlist_storage.store(state_file_path, active))
1140 {
1141 MWARNING("Failed to save config to file " << state_file_path);
1142 return false;
1143 }
1144 CATCH_ENTRY_L0("node_server::store", false);
1145 return true;
1146 }
1147 //-----------------------------------------------------------------------------------
1148 template<class t_payload_net_handler>
1149 bool node_server<t_payload_net_handler>::send_stop_signal()
1150 {
1151 MDEBUG("[node] sending stop signal");
1152 for (auto& zone : m_network_zones)
1153 zone.second.m_net_server.send_stop_signal();
1154 MDEBUG("[node] Stop signal sent");
1155
1156 for (auto& zone : m_network_zones)
1157 {
1158 std::list<boost::uuids::uuid> connection_ids;
1159 zone.second.m_net_server.get_config_object().foreach_connection([&](const p2p_connection_context& cntxt) {
1160 connection_ids.push_back(cntxt.m_connection_id);
1161 return true;
1162 });
1163 for (const auto &connection_id: connection_ids)
1164 zone.second.m_net_server.get_config_object().close(connection_id);
1165 }
1166 m_payload_handler.stop();
1167 return true;
1168 }
1169 //-----------------------------------------------------------------------------------
1170 template<class t_payload_net_handler>
1171 bool node_server<t_payload_net_handler>::do_handshake_with_peer(peerid_type& pi, p2p_connection_context& context_, bool just_take_peerlist)
1172 {
1173 network_zone& zone = m_network_zones.at(context_.m_remote_address.get_zone());
1174
1175 typename COMMAND_HANDSHAKE::request arg;
1176 typename COMMAND_HANDSHAKE::response rsp;
1177 get_local_node_data(arg.node_data, zone);
1178 m_payload_handler.get_payload_sync_data(arg.payload_data);
1179
1180 epee::simple_event ev;
1181 std::atomic<bool> hsh_result(false);
1182 bool timeout = false;
1183
1184 bool r = epee::net_utils::async_invoke_remote_command2<typename COMMAND_HANDSHAKE::response>(context_, COMMAND_HANDSHAKE::ID, arg, zone.m_net_server.get_config_object(),
1185 [this, &pi, &ev, &hsh_result, &just_take_peerlist, &context_, &timeout](int code, const typename COMMAND_HANDSHAKE::response& rsp, p2p_connection_context& context)
1186 {
1187 epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([&](){ev.raise();});
1188
1189 if(code < 0)
1190 {
1191 LOG_WARNING_CC(context, "COMMAND_HANDSHAKE invoke failed. (" << code << ", " << epee::levin::get_err_descr(code) << ")");
1192 if (code == LEVIN_ERROR_CONNECTION_TIMEDOUT || code == LEVIN_ERROR_CONNECTION_DESTROYED)
1193 timeout = true;
1194 return;
1195 }
1196
1197 if(rsp.node_data.network_id != m_network_id)
1198 {
1199 LOG_WARNING_CC(context, "COMMAND_HANDSHAKE Failed, wrong network! (" << rsp.node_data.network_id << "), closing connection.");
1200 return;
1201 }
1202
1203 if(!handle_remote_peerlist(rsp.local_peerlist_new, context))
1204 {
1205 LOG_WARNING_CC(context, "COMMAND_HANDSHAKE: failed to handle_remote_peerlist(...), closing connection.");
1206 add_host_fail(context.m_remote_address);
1207 return;
1208 }
1209 hsh_result = true;
1210 if(!just_take_peerlist)
1211 {
1212 if(!m_payload_handler.process_payload_sync_data(rsp.payload_data, context, true))
1213 {
1214 LOG_WARNING_CC(context, "COMMAND_HANDSHAKE invoked, but process_payload_sync_data returned false, dropping connection.");
1215 hsh_result = false;
1216 return;
1217 }
1218
1219 pi = context.peer_id = rsp.node_data.peer_id;
1220 context.m_rpc_port = rsp.node_data.rpc_port;
1221 context.m_rpc_credits_per_hash = rsp.node_data.rpc_credits_per_hash;
1222 context.support_flags = rsp.node_data.support_flags;
1223 const auto azone = context.m_remote_address.get_zone();
1224 network_zone& zone = m_network_zones.at(azone);
1225 zone.m_peerlist.set_peer_just_seen(rsp.node_data.peer_id, context.m_remote_address, context.m_pruning_seed, context.m_rpc_port, context.m_rpc_credits_per_hash);
1226
1227 // move
1228 if(azone == epee::net_utils::zone::public_ && rsp.node_data.peer_id == zone.m_config.m_peer_id)
1229 {
1230 LOG_DEBUG_CC(context, "Connection to self detected, dropping connection");
1231 hsh_result = false;
1232 return;
1233 }
1234 LOG_INFO_CC(context, "New connection handshaked, pruning seed " << epee::string_tools::to_string_hex(context.m_pruning_seed));
1235 LOG_DEBUG_CC(context, " COMMAND_HANDSHAKE INVOKED OK");
1236 }else
1237 {
1238 LOG_DEBUG_CC(context, " COMMAND_HANDSHAKE(AND CLOSE) INVOKED OK");
1239 }
1240 context_ = context;
1241 }, P2P_DEFAULT_HANDSHAKE_INVOKE_TIMEOUT);
1242
1243 if(r)
1244 {
1245 ev.wait();
1246 }
1247
1248 if(!hsh_result)
1249 {
1250 LOG_WARNING_CC(context_, "COMMAND_HANDSHAKE Failed");
1251 if (!timeout)
1252 zone.m_net_server.get_config_object().close(context_.m_connection_id);
1253 }
1254 else if (!just_take_peerlist)
1255 {
1256 if (context_.support_flags == 0)
1257 try_get_support_flags(context_, [](p2p_connection_context& flags_context, const uint32_t& support_flags)
1258 {
1259 flags_context.support_flags = support_flags;
1260 });
1261 }
1262
1263 return hsh_result;
1264 }
1265 //-----------------------------------------------------------------------------------
1266 template<class t_payload_net_handler>
1267 bool node_server<t_payload_net_handler>::do_peer_timed_sync(const epee::net_utils::connection_context_base& context_, peerid_type peer_id)
1268 {
1269 typename COMMAND_TIMED_SYNC::request arg = AUTO_VAL_INIT(arg);
1270 m_payload_handler.get_payload_sync_data(arg.payload_data);
1271
1272 network_zone& zone = m_network_zones.at(context_.m_remote_address.get_zone());
1273 bool r = epee::net_utils::async_invoke_remote_command2<typename COMMAND_TIMED_SYNC::response>(context_, COMMAND_TIMED_SYNC::ID, arg, zone.m_net_server.get_config_object(),
1274 [this](int code, const typename COMMAND_TIMED_SYNC::response& rsp, p2p_connection_context& context)
1275 {
1276 context.m_in_timedsync = false;
1277 if(code < 0)
1278 {
1279 LOG_WARNING_CC(context, "COMMAND_TIMED_SYNC invoke failed. (" << code << ", " << epee::levin::get_err_descr(code) << ")");
1280 return;
1281 }
1282
1283 if(!handle_remote_peerlist(rsp.local_peerlist_new, context))
1284 {
1285 LOG_WARNING_CC(context, "COMMAND_TIMED_SYNC: failed to handle_remote_peerlist(...), closing connection.");
1286 m_network_zones.at(context.m_remote_address.get_zone()).m_net_server.get_config_object().close(context.m_connection_id );
1287 add_host_fail(context.m_remote_address);
1288 }
1289 if(!context.m_is_income)
1290 m_network_zones.at(context.m_remote_address.get_zone()).m_peerlist.set_peer_just_seen(context.peer_id, context.m_remote_address, context.m_pruning_seed, context.m_rpc_port, context.m_rpc_credits_per_hash);
1291 if (!m_payload_handler.process_payload_sync_data(rsp.payload_data, context, false))
1292 {
1293 m_network_zones.at(context.m_remote_address.get_zone()).m_net_server.get_config_object().close(context.m_connection_id );
1294 }
1295 });
1296
1297 if(!r)
1298 {
1299 LOG_WARNING_CC(context_, "COMMAND_TIMED_SYNC Failed");
1300 return false;
1301 }
1302 return true;
1303 }
1304 //-----------------------------------------------------------------------------------
1305 template<class t_payload_net_handler>
1306 size_t node_server<t_payload_net_handler>::get_random_index_with_fixed_probability(size_t max_index)
1307 {
1308 //divide by zero workaround
1309 if(!max_index)
1310 return 0;
1311
1312 size_t x = crypto::rand<size_t>()%(16*max_index+1);
1313 size_t res = (x*x*x)/(max_index*max_index*16*16*16); //parabola \/
1314 MDEBUG("Random connection index=" << res << "(x="<< x << ", max_index=" << max_index << ")");
1315 return res;
1316 }
1317 //-----------------------------------------------------------------------------------
1318 template<class t_payload_net_handler>
1319 bool node_server<t_payload_net_handler>::is_peer_used(const peerlist_entry& peer)
1320 {
1321 const auto zone = peer.adr.get_zone();
1322 const auto server = m_network_zones.find(zone);
1323 if (server == m_network_zones.end())
1324 return false;
1325
1326 const bool is_public = (zone == epee::net_utils::zone::public_);
1327 if(is_public && server->second.m_config.m_peer_id == peer.id)
1328 return true;//dont make connections to ourself
1329
1330 bool used = false;
1331 server->second.m_net_server.get_config_object().foreach_connection([&, is_public](const p2p_connection_context& cntxt)
1332 {
1333 if((is_public && cntxt.peer_id == peer.id) || (!cntxt.m_is_income && peer.adr == cntxt.m_remote_address))
1334 {
1335 used = true;
1336 return false;//stop enumerating
1337 }
1338 return true;
1339 });
1340 return used;
1341 }
1342 //-----------------------------------------------------------------------------------
1343 template<class t_payload_net_handler>
1344 bool node_server<t_payload_net_handler>::is_peer_used(const anchor_peerlist_entry& peer)
1345 {
1346 const auto zone = peer.adr.get_zone();
1347 const auto server = m_network_zones.find(zone);
1348 if (server == m_network_zones.end())
1349 return false;
1350
1351 const bool is_public = (zone == epee::net_utils::zone::public_);
1352 if(is_public && server->second.m_config.m_peer_id == peer.id)
1353 return true;//dont make connections to ourself
1354
1355 bool used = false;
1356 server->second.m_net_server.get_config_object().foreach_connection([&, is_public](const p2p_connection_context& cntxt)
1357 {
1358 if((is_public && cntxt.peer_id == peer.id) || (!cntxt.m_is_income && peer.adr == cntxt.m_remote_address))
1359 {
1360 used = true;
1361 return false;//stop enumerating
1362 }
1363 return true;
1364 });
1365 return used;
1366 }
1367 //-----------------------------------------------------------------------------------
1368 template<class t_payload_net_handler>
1369 bool node_server<t_payload_net_handler>::is_addr_connected(const epee::net_utils::network_address& peer)
1370 {
1371 const auto zone = m_network_zones.find(peer.get_zone());
1372 if (zone == m_network_zones.end())
1373 return false;
1374
1375 bool connected = false;
1376 zone->second.m_net_server.get_config_object().foreach_connection([&](const p2p_connection_context& cntxt)
1377 {
1378 if(!cntxt.m_is_income && peer == cntxt.m_remote_address)
1379 {
1380 connected = true;
1381 return false;//stop enumerating
1382 }
1383 return true;
1384 });
1385
1386 return connected;
1387 }
1388
1389 #define LOG_PRINT_CC_PRIORITY_NODE(priority, con, msg) \
1390 do { \
1391 if (priority) {\
1392 LOG_INFO_CC(con, "[priority]" << msg); \
1393 } else {\
1394 LOG_INFO_CC(con, msg); \
1395 } \
1396 } while(0)
1397
1398 template<class t_payload_net_handler>
1399 bool node_server<t_payload_net_handler>::try_to_connect_and_handshake_with_new_peer(const epee::net_utils::network_address& na, bool just_take_peerlist, uint64_t last_seen_stamp, PeerType peer_type, uint64_t first_seen_stamp)
1400 {
1401 network_zone& zone = m_network_zones.at(na.get_zone());
1402 if (zone.m_connect == nullptr) // outgoing connections in zone not possible
1403 return false;
1404
1405 if (zone.m_our_address == na)
1406 return false;
1407
1408 if (zone.m_current_number_of_out_peers == zone.m_config.m_net_config.max_out_connection_count) // out peers limit
1409 {
1410 return false;
1411 }
1412 else if (zone.m_current_number_of_out_peers > zone.m_config.m_net_config.max_out_connection_count)
1413 {
1414 zone.m_net_server.get_config_object().del_out_connections(1);
1415 --(zone.m_current_number_of_out_peers); // atomic variable, update time = 1s
1416 return false;
1417 }
1418
1419
1420 MDEBUG("Connecting to " << na.str() << "(peer_type=" << peer_type << ", last_seen: "
1421 << (last_seen_stamp ? epee::misc_utils::get_time_interval_string(time(NULL) - last_seen_stamp):"never")
1422 << ")...");
1423
1424 auto con = zone.m_connect(zone, na, m_ssl_support);
1425 if(!con)
1426 {
1427 bool is_priority = is_priority_node(na);
1428 LOG_PRINT_CC_PRIORITY_NODE(is_priority, bool(con), "Connect failed to " << na.str()
1429 /*<< ", try " << try_count*/);
1430 record_addr_failed(na);
1431 return false;
1432 }
1433
1434 con->m_anchor = peer_type == anchor;
1435 peerid_type pi = AUTO_VAL_INIT(pi);
1436 bool res = do_handshake_with_peer(pi, *con, just_take_peerlist);
1437
1438 if(!res)
1439 {
1440 bool is_priority = is_priority_node(na);
1441 LOG_PRINT_CC_PRIORITY_NODE(is_priority, *con, "Failed to HANDSHAKE with peer "
1442 << na.str()
1443 /*<< ", try " << try_count*/);
1444 record_addr_failed(na);
1445 return false;
1446 }
1447
1448 if(just_take_peerlist)
1449 {
1450 zone.m_net_server.get_config_object().close(con->m_connection_id);
1451 LOG_DEBUG_CC(*con, "CONNECTION HANDSHAKED OK AND CLOSED.");
1452 return true;
1453 }
1454
1455 peerlist_entry pe_local = AUTO_VAL_INIT(pe_local);
1456 pe_local.adr = na;
1457 pe_local.id = pi;
1458 time_t last_seen;
1459 time(&last_seen);
1460 pe_local.last_seen = static_cast<int64_t>(last_seen);
1461 pe_local.pruning_seed = con->m_pruning_seed;
1462 pe_local.rpc_port = con->m_rpc_port;
1463 pe_local.rpc_credits_per_hash = con->m_rpc_credits_per_hash;
1464 zone.m_peerlist.append_with_peer_white(pe_local);
1465 //update last seen and push it to peerlist manager
1466
1467 anchor_peerlist_entry ape = AUTO_VAL_INIT(ape);
1468 ape.adr = na;
1469 ape.id = pi;
1470 ape.first_seen = first_seen_stamp ? first_seen_stamp : time(nullptr);
1471
1472 zone.m_peerlist.append_with_peer_anchor(ape);
1473 zone.m_notifier.on_handshake_complete(con->m_connection_id, con->m_is_income);
1474 zone.m_notifier.new_out_connection();
1475
1476 LOG_DEBUG_CC(*con, "CONNECTION HANDSHAKED OK.");
1477 return true;
1478 }
1479
1480 template<class t_payload_net_handler>
1481 bool node_server<t_payload_net_handler>::check_connection_and_handshake_with_peer(const epee::net_utils::network_address& na, uint64_t last_seen_stamp)
1482 {
1483 network_zone& zone = m_network_zones.at(na.get_zone());
1484 if (zone.m_connect == nullptr)
1485 return false;
1486
1487 LOG_PRINT_L1("Connecting to " << na.str() << "(last_seen: "
1488 << (last_seen_stamp ? epee::misc_utils::get_time_interval_string(time(NULL) - last_seen_stamp):"never")
1489 << ")...");
1490
1491 auto con = zone.m_connect(zone, na, m_ssl_support);
1492 if (!con) {
1493 bool is_priority = is_priority_node(na);
1494
1495 LOG_PRINT_CC_PRIORITY_NODE(is_priority, p2p_connection_context{}, "Connect failed to " << na.str());
1496 record_addr_failed(na);
1497
1498 return false;
1499 }
1500
1501 con->m_anchor = false;
1502 peerid_type pi = AUTO_VAL_INIT(pi);
1503 const bool res = do_handshake_with_peer(pi, *con, true);
1504 if (!res) {
1505 bool is_priority = is_priority_node(na);
1506
1507 LOG_PRINT_CC_PRIORITY_NODE(is_priority, *con, "Failed to HANDSHAKE with peer " << na.str());
1508 record_addr_failed(na);
1509 return false;
1510 }
1511
1512 zone.m_net_server.get_config_object().close(con->m_connection_id);
1513
1514 LOG_DEBUG_CC(*con, "CONNECTION HANDSHAKED OK AND CLOSED.");
1515
1516 return true;
1517 }
1518
1519 #undef LOG_PRINT_CC_PRIORITY_NODE
1520
1521 //-----------------------------------------------------------------------------------
1522 template<class t_payload_net_handler>
1523 void node_server<t_payload_net_handler>::record_addr_failed(const epee::net_utils::network_address& addr)
1524 {
1525 CRITICAL_REGION_LOCAL(m_conn_fails_cache_lock);
1526 m_conn_fails_cache[addr.host_str()] = time(NULL);
1527 }
1528 //-----------------------------------------------------------------------------------
1529 template<class t_payload_net_handler>
1530 bool node_server<t_payload_net_handler>::is_addr_recently_failed(const epee::net_utils::network_address& addr)
1531 {
1532 CRITICAL_REGION_LOCAL(m_conn_fails_cache_lock);
1533 auto it = m_conn_fails_cache.find(addr.host_str());
1534 if(it == m_conn_fails_cache.end())
1535 return false;
1536
1537 if(time(NULL) - it->second > P2P_FAILED_ADDR_FORGET_SECONDS)
1538 return false;
1539 else
1540 return true;
1541 }
1542 //-----------------------------------------------------------------------------------
1543 template<class t_payload_net_handler>
1544 bool node_server<t_payload_net_handler>::make_new_connection_from_anchor_peerlist(const std::vector<anchor_peerlist_entry>& anchor_peerlist)
1545 {
1546 for (const auto& pe: anchor_peerlist) {
1547 _note("Considering connecting (out) to anchor peer: " << peerid_to_string(pe.id) << " " << pe.adr.str());
1548
1549 if(is_peer_used(pe)) {
1550 _note("Peer is used");
1551 continue;
1552 }
1553
1554 if(!is_remote_host_allowed(pe.adr)) {
1555 continue;
1556 }
1557
1558 if(is_addr_recently_failed(pe.adr)) {
1559 continue;
1560 }
1561
1562 MDEBUG("Selected peer: " << peerid_to_string(pe.id) << " " << pe.adr.str()
1563 << "[peer_type=" << anchor
1564 << "] first_seen: " << epee::misc_utils::get_time_interval_string(time(NULL) - pe.first_seen));
1565
1566 if(!try_to_connect_and_handshake_with_new_peer(pe.adr, false, 0, anchor, pe.first_seen)) {
1567 _note("Handshake failed");
1568 continue;
1569 }
1570
1571 return true;
1572 }
1573
1574 return false;
1575 }
1576 //-----------------------------------------------------------------------------------
1577 template<class t_payload_net_handler>
1578 bool node_server<t_payload_net_handler>::make_new_connection_from_peerlist(network_zone& zone, bool use_white_list)
1579 {
1580 size_t max_random_index = 0;
1581
1582 std::set<size_t> tried_peers;
1583
1584 size_t try_count = 0;
1585 size_t rand_count = 0;
1586 while(rand_count < (max_random_index+1)*3 && try_count < 10 && !zone.m_net_server.is_stop_signal_sent())
1587 {
1588 ++rand_count;
1589 size_t random_index;
1590 const uint32_t next_needed_pruning_stripe = m_payload_handler.get_next_needed_pruning_stripe().second;
1591
1592 // build a set of all the /16 we're connected to, and prefer a peer that's not in that set
1593 std::set<uint32_t> classB;
1594 if (&zone == &m_network_zones.at(epee::net_utils::zone::public_)) // at returns reference, not copy
1595 {
1596 zone.m_net_server.get_config_object().foreach_connection([&](const p2p_connection_context& cntxt)
1597 {
1598 if (cntxt.m_remote_address.get_type_id() == epee::net_utils::ipv4_network_address::get_type_id())
1599 {
1600
1601 const epee::net_utils::network_address na = cntxt.m_remote_address;
1602 const uint32_t actual_ip = na.as<const epee::net_utils::ipv4_network_address>().ip();
1603 classB.insert(actual_ip & 0x0000ffff);
1604 }
1605 else if (cntxt.m_remote_address.get_type_id() == epee::net_utils::ipv6_network_address::get_type_id())
1606 {
1607 const epee::net_utils::network_address na = cntxt.m_remote_address;
1608 const boost::asio::ip::address_v6 &actual_ip = na.as<const epee::net_utils::ipv6_network_address>().ip();
1609 if (actual_ip.is_v4_mapped())
1610 {
1611 boost::asio::ip::address_v4 v4ip = make_address_v4_from_v6(actual_ip);
1612 uint32_t actual_ipv4;
1613 memcpy(&actual_ipv4, v4ip.to_bytes().data(), sizeof(actual_ipv4));
1614 classB.insert(actual_ipv4 & ntohl(0xffff0000));
1615 }
1616 }
1617 return true;
1618 });
1619 }
1620
1621 auto get_host_string = [](const epee::net_utils::network_address &address) {
1622 if (address.get_type_id() == epee::net_utils::ipv6_network_address::get_type_id())
1623 {
1624 boost::asio::ip::address_v6 actual_ip = address.as<const epee::net_utils::ipv6_network_address>().ip();
1625 if (actual_ip.is_v4_mapped())
1626 {
1627 boost::asio::ip::address_v4 v4ip = make_address_v4_from_v6(actual_ip);
1628 uint32_t actual_ipv4;
1629 memcpy(&actual_ipv4, v4ip.to_bytes().data(), sizeof(actual_ipv4));
1630 return epee::net_utils::ipv4_network_address(actual_ipv4, 0).host_str();
1631 }
1632 }
1633 return address.host_str();
1634 };
1635 std::unordered_set<std::string> hosts_added;
1636 std::deque<size_t> filtered;
1637 const size_t limit = use_white_list ? 20 : std::numeric_limits<size_t>::max();
1638 for (int step = 0; step < 2; ++step)
1639 {
1640 bool skip_duplicate_class_B = step == 0;
1641 size_t idx = 0, skipped = 0;
1642 zone.m_peerlist.foreach (use_white_list, [&classB, &filtered, &idx, &skipped, skip_duplicate_class_B, limit, next_needed_pruning_stripe, &hosts_added, &get_host_string](const peerlist_entry &pe){
1643 if (filtered.size() >= limit)
1644 return false;
1645 bool skip = false;
1646 if (skip_duplicate_class_B && pe.adr.get_type_id() == epee::net_utils::ipv4_network_address::get_type_id())
1647 {
1648 const epee::net_utils::network_address na = pe.adr;
1649 uint32_t actual_ip = na.as<const epee::net_utils::ipv4_network_address>().ip();
1650 skip = classB.find(actual_ip & 0x0000ffff) != classB.end();
1651 }
1652 else if (skip_duplicate_class_B && pe.adr.get_type_id() == epee::net_utils::ipv6_network_address::get_type_id())
1653 {
1654 const epee::net_utils::network_address na = pe.adr;
1655 const boost::asio::ip::address_v6 &actual_ip = na.as<const epee::net_utils::ipv6_network_address>().ip();
1656 if (actual_ip.is_v4_mapped())
1657 {
1658 boost::asio::ip::address_v4 v4ip = make_address_v4_from_v6(actual_ip);
1659 uint32_t actual_ipv4;
1660 memcpy(&actual_ipv4, v4ip.to_bytes().data(), sizeof(actual_ipv4));
1661 skip = classB.find(actual_ipv4 & ntohl(0xffff0000)) != classB.end();
1662 }
1663 }
1664
1665 // consider each host once, to avoid giving undue inflence to hosts running several nodes
1666 if (!skip)
1667 {
1668 const auto i = hosts_added.find(get_host_string(pe.adr));
1669 if (i != hosts_added.end())
1670 skip = true;
1671 }
1672
1673 if (skip)
1674 ++skipped;
1675 else if (next_needed_pruning_stripe == 0 || pe.pruning_seed == 0)
1676 filtered.push_back(idx);
1677 else if (next_needed_pruning_stripe == tools::get_pruning_stripe(pe.pruning_seed))
1678 filtered.push_front(idx);
1679 ++idx;
1680 hosts_added.insert(get_host_string(pe.adr));
1681 return true;
1682 });
1683 if (skipped == 0 || !filtered.empty())
1684 break;
1685 if (skipped)
1686 MDEBUG("Skipping " << skipped << " possible peers as they share a class B with existing peers");
1687 }
1688 if (filtered.empty())
1689 {
1690 MINFO("No available peer in " << (use_white_list ? "white" : "gray") << " list filtered by " << next_needed_pruning_stripe);
1691 return false;
1692 }
1693 if (use_white_list)
1694 {
1695 // if using the white list, we first pick in the set of peers we've already been using earlier
1696 random_index = get_random_index_with_fixed_probability(std::min<uint64_t>(filtered.size() - 1, 20));
1697 CRITICAL_REGION_LOCAL(m_used_stripe_peers_mutex);
1698 if (next_needed_pruning_stripe > 0 && next_needed_pruning_stripe <= (1ul << CRYPTONOTE_PRUNING_LOG_STRIPES) && !m_used_stripe_peers[next_needed_pruning_stripe-1].empty())
1699 {
1700 const epee::net_utils::network_address na = m_used_stripe_peers[next_needed_pruning_stripe-1].front();
1701 m_used_stripe_peers[next_needed_pruning_stripe-1].pop_front();
1702 for (size_t i = 0; i < filtered.size(); ++i)
1703 {
1704 peerlist_entry pe;
1705 if (zone.m_peerlist.get_white_peer_by_index(pe, filtered[i]) && pe.adr == na)
1706 {
1707 MDEBUG("Reusing stripe " << next_needed_pruning_stripe << " peer " << pe.adr.str());
1708 random_index = i;
1709 break;
1710 }
1711 }
1712 }
1713 }
1714 else
1715 random_index = crypto::rand_idx(filtered.size());
1716
1717 CHECK_AND_ASSERT_MES(random_index < filtered.size(), false, "random_index < filtered.size() failed!!");
1718 random_index = filtered[random_index];
1719 CHECK_AND_ASSERT_MES(random_index < (use_white_list ? zone.m_peerlist.get_white_peers_count() : zone.m_peerlist.get_gray_peers_count()),
1720 false, "random_index < peers size failed!!");
1721
1722 if(tried_peers.count(random_index))
1723 continue;
1724
1725 tried_peers.insert(random_index);
1726 peerlist_entry pe = AUTO_VAL_INIT(pe);
1727 bool r = use_white_list ? zone.m_peerlist.get_white_peer_by_index(pe, random_index):zone.m_peerlist.get_gray_peer_by_index(pe, random_index);
1728 CHECK_AND_ASSERT_MES(r, false, "Failed to get random peer from peerlist(white:" << use_white_list << ")");
1729
1730 ++try_count;
1731
1732 _note("Considering connecting (out) to " << (use_white_list ? "white" : "gray") << " list peer: " <<
1733 peerid_to_string(pe.id) << " " << pe.adr.str() << ", pruning seed " << epee::string_tools::to_string_hex(pe.pruning_seed) <<
1734 " (stripe " << next_needed_pruning_stripe << " needed)");
1735
1736 if(zone.m_our_address == pe.adr)
1737 continue;
1738
1739 if(is_peer_used(pe)) {
1740 _note("Peer is used");
1741 continue;
1742 }
1743
1744 if(!is_remote_host_allowed(pe.adr))
1745 continue;
1746
1747 if(is_addr_recently_failed(pe.adr))
1748 continue;
1749
1750 MDEBUG("Selected peer: " << peerid_to_string(pe.id) << " " << pe.adr.str()
1751 << ", pruning seed " << epee::string_tools::to_string_hex(pe.pruning_seed) << " "
1752 << "[peer_list=" << (use_white_list ? white : gray)
1753 << "] last_seen: " << (pe.last_seen ? epee::misc_utils::get_time_interval_string(time(NULL) - pe.last_seen) : "never"));
1754
1755 if(!try_to_connect_and_handshake_with_new_peer(pe.adr, false, pe.last_seen, use_white_list ? white : gray)) {
1756 _note("Handshake failed");
1757 continue;
1758 }
1759
1760 return true;
1761 }
1762 return false;
1763 }
1764 //-----------------------------------------------------------------------------------
1765 template<class t_payload_net_handler>
1766 bool node_server<t_payload_net_handler>::connect_to_seed(epee::net_utils::zone zone)
1767 {
1768 network_zone& server = m_network_zones.at(zone);
1769 boost::upgrade_lock<boost::shared_mutex> seed_nodes_upgrade_lock(server.m_seed_nodes_lock);
1770
1771 if (!server.m_seed_nodes_initialized)
1772 {
1773 const std::uint16_t default_port = cryptonote::get_config(m_nettype).P2P_DEFAULT_PORT;
1774 boost::upgrade_to_unique_lock<boost::shared_mutex> seed_nodes_lock(seed_nodes_upgrade_lock);
1775 server.m_seed_nodes_initialized = true;
1776 for (const auto& full_addr : get_seed_nodes(zone))
1777 {
1778 // seeds should have hostname converted to IP already
1779 MDEBUG("Seed node: " << full_addr);
1780 server.m_seed_nodes.push_back(MONERO_UNWRAP(net::get_network_address(full_addr, default_port)));
1781 }
1782 MDEBUG("Number of seed nodes: " << server.m_seed_nodes.size());
1783 }
1784
1785 if (server.m_seed_nodes.empty() || m_offline || !m_exclusive_peers.empty())
1786 return true;
1787
1788 size_t try_count = 0;
1789 bool is_connected_to_at_least_one_seed_node = false;
1790 size_t current_index = crypto::rand_idx(server.m_seed_nodes.size());
1791 while(true)
1792 {
1793 if(server.m_net_server.is_stop_signal_sent())
1794 return false;
1795
1796 peerlist_entry pe_seed{};
1797 pe_seed.adr = server.m_seed_nodes[current_index];
1798 if (is_peer_used(pe_seed))
1799 is_connected_to_at_least_one_seed_node = true;
1800 else if (try_to_connect_and_handshake_with_new_peer(server.m_seed_nodes[current_index], true))
1801 break;
1802 if(++try_count > server.m_seed_nodes.size())
1803 {
1804 // only IP zone has fallback (to direct IP) seeds
1805 if (zone == epee::net_utils::zone::public_ && !m_fallback_seed_nodes_added.test_and_set())
1806 {
1807 MWARNING("Failed to connect to any of seed peers, trying fallback seeds");
1808 current_index = server.m_seed_nodes.size() - 1;
1809 {
1810 boost::upgrade_to_unique_lock<boost::shared_mutex> seed_nodes_lock(seed_nodes_upgrade_lock);
1811
1812 for (const auto &peer: get_ip_seed_nodes())
1813 {
1814 MDEBUG("Fallback seed node: " << peer);
1815 append_net_address(server.m_seed_nodes, peer, cryptonote::get_config(m_nettype).P2P_DEFAULT_PORT);
1816 }
1817 }
1818 if (current_index == server.m_seed_nodes.size() - 1)
1819 {
1820 MWARNING("No fallback seeds, continuing without seeds");
1821 break;
1822 }
1823 // continue for another few cycles
1824 }
1825 else
1826 {
1827 if (!is_connected_to_at_least_one_seed_node)
1828 MWARNING("Failed to connect to any of seed peers, continuing without seeds");
1829 break;
1830 }
1831 }
1832 if(++current_index >= server.m_seed_nodes.size())
1833 current_index = 0;
1834 }
1835 return true;
1836 }
1837 //-----------------------------------------------------------------------------------
1838 template<class t_payload_net_handler>
1839 bool node_server<t_payload_net_handler>::connections_maker()
1840 {
1841 using zone_type = epee::net_utils::zone;
1842
1843 if (m_offline) return true;
1844 if (!connect_to_peerlist(m_exclusive_peers)) return false;
1845
1846 if (!m_exclusive_peers.empty()) return true;
1847
1848 bool one_succeeded = false;
1849 for(auto& zone : m_network_zones)
1850 {
1851 size_t start_conn_count = get_outgoing_connections_count(zone.second);
1852 if(!zone.second.m_peerlist.get_white_peers_count() && !connect_to_seed(zone.first))
1853 {
1854 continue;
1855 }
1856
1857 if (zone.first == zone_type::public_ && !connect_to_peerlist(m_priority_peers)) continue;
1858
1859 size_t base_expected_white_connections = (zone.second.m_config.m_net_config.max_out_connection_count*P2P_DEFAULT_WHITELIST_CONNECTIONS_PERCENT)/100;
1860
1861 // carefully avoid `continue` in nested loop
1862
1863 size_t conn_count = get_outgoing_connections_count(zone.second);
1864 while(conn_count < zone.second.m_config.m_net_config.max_out_connection_count)
1865 {
1866 const size_t expected_white_connections = m_payload_handler.get_next_needed_pruning_stripe().second ? zone.second.m_config.m_net_config.max_out_connection_count : base_expected_white_connections;
1867 if(conn_count < expected_white_connections)
1868 {
1869 //start from anchor list
1870 while (get_outgoing_connections_count(zone.second) < P2P_DEFAULT_ANCHOR_CONNECTIONS_COUNT
1871 && make_expected_connections_count(zone.second, anchor, P2P_DEFAULT_ANCHOR_CONNECTIONS_COUNT));
1872 //then do white list
1873 while (get_outgoing_connections_count(zone.second) < expected_white_connections
1874 && make_expected_connections_count(zone.second, white, expected_white_connections));
1875 //then do grey list
1876 while (get_outgoing_connections_count(zone.second) < zone.second.m_config.m_net_config.max_out_connection_count
1877 && make_expected_connections_count(zone.second, gray, zone.second.m_config.m_net_config.max_out_connection_count));
1878 }else
1879 {
1880 //start from grey list
1881 while (get_outgoing_connections_count(zone.second) < zone.second.m_config.m_net_config.max_out_connection_count
1882 && make_expected_connections_count(zone.second, gray, zone.second.m_config.m_net_config.max_out_connection_count));
1883 //and then do white list
1884 while (get_outgoing_connections_count(zone.second) < zone.second.m_config.m_net_config.max_out_connection_count
1885 && make_expected_connections_count(zone.second, white, zone.second.m_config.m_net_config.max_out_connection_count));
1886 }
1887 if(zone.second.m_net_server.is_stop_signal_sent())
1888 return false;
1889 size_t new_conn_count = get_outgoing_connections_count(zone.second);
1890 if (new_conn_count <= conn_count)
1891 {
1892 // we did not make any connection, sleep a bit to avoid a busy loop in case we don't have
1893 // any peers to try, then break so we will try seeds to get more peers
1894 boost::this_thread::sleep_for(boost::chrono::seconds(1));
1895 break;
1896 }
1897 conn_count = new_conn_count;
1898 }
1899
1900 if (start_conn_count == get_outgoing_connections_count(zone.second) && start_conn_count < zone.second.m_config.m_net_config.max_out_connection_count)
1901 {
1902 MINFO("Failed to connect to any, trying seeds");
1903 if (!connect_to_seed(zone.first))
1904 continue;
1905 }
1906 one_succeeded = true;
1907 }
1908
1909 return one_succeeded;
1910 }
1911 //-----------------------------------------------------------------------------------
1912 template<class t_payload_net_handler>
1913 bool node_server<t_payload_net_handler>::make_expected_connections_count(network_zone& zone, PeerType peer_type, size_t expected_connections)
1914 {
1915 if (m_offline)
1916 return false;
1917
1918 std::vector<anchor_peerlist_entry> apl;
1919
1920 if (peer_type == anchor) {
1921 zone.m_peerlist.get_and_empty_anchor_peerlist(apl);
1922 }
1923
1924 size_t conn_count = get_outgoing_connections_count(zone);
1925 //add new connections from white peers
1926 if(conn_count < expected_connections)
1927 {
1928 if(zone.m_net_server.is_stop_signal_sent())
1929 return false;
1930
1931 MDEBUG("Making expected connection, type " << peer_type << ", " << conn_count << "/" << expected_connections << " connections");
1932
1933 if (peer_type == anchor && !make_new_connection_from_anchor_peerlist(apl)) {
1934 return false;
1935 }
1936
1937 if (peer_type == white && !make_new_connection_from_peerlist(zone, true)) {
1938 return false;
1939 }
1940
1941 if (peer_type == gray && !make_new_connection_from_peerlist(zone, false)) {
1942 return false;
1943 }
1944 }
1945 return true;
1946 }
1947 //-----------------------------------------------------------------------------------
1948 template<class t_payload_net_handler>
1949 size_t node_server<t_payload_net_handler>::get_public_outgoing_connections_count()
1950 {
1951 auto public_zone = m_network_zones.find(epee::net_utils::zone::public_);
1952 if (public_zone == m_network_zones.end())
1953 return 0;
1954 return get_outgoing_connections_count(public_zone->second);
1955 }
1956 //-----------------------------------------------------------------------------------
1957 template<class t_payload_net_handler>
1958 size_t node_server<t_payload_net_handler>::get_incoming_connections_count(network_zone& zone)
1959 {
1960 size_t count = 0;
1961 zone.m_net_server.get_config_object().foreach_connection([&](const p2p_connection_context& cntxt)
1962 {
1963 if(cntxt.m_is_income)
1964 ++count;
1965 return true;
1966 });
1967 return count;
1968 }
1969 //-----------------------------------------------------------------------------------
1970 template<class t_payload_net_handler>
1971 size_t node_server<t_payload_net_handler>::get_outgoing_connections_count(network_zone& zone)
1972 {
1973 size_t count = 0;
1974 zone.m_net_server.get_config_object().foreach_connection([&](const p2p_connection_context& cntxt)
1975 {
1976 if(!cntxt.m_is_income)
1977 ++count;
1978 return true;
1979 });
1980 return count;
1981 }
1982 //-----------------------------------------------------------------------------------
1983 template<class t_payload_net_handler>
1984 size_t node_server<t_payload_net_handler>::get_outgoing_connections_count()
1985 {
1986 size_t count = 0;
1987 for(auto& zone : m_network_zones)
1988 count += get_outgoing_connections_count(zone.second);
1989 return count;
1990 }
1991 //-----------------------------------------------------------------------------------
1992 template<class t_payload_net_handler>
1993 size_t node_server<t_payload_net_handler>::get_incoming_connections_count()
1994 {
1995 size_t count = 0;
1996 for (auto& zone : m_network_zones)
1997 {
1998 zone.second.m_net_server.get_config_object().foreach_connection([&](const p2p_connection_context& cntxt)
1999 {
2000 if(cntxt.m_is_income)
2001 ++count;
2002 return true;
2003 });
2004 }
2005 return count;
2006 }
2007 //-----------------------------------------------------------------------------------
2008 template<class t_payload_net_handler>
2009 size_t node_server<t_payload_net_handler>::get_public_white_peers_count()
2010 {
2011 auto public_zone = m_network_zones.find(epee::net_utils::zone::public_);
2012 if (public_zone == m_network_zones.end())
2013 return 0;
2014 return public_zone->second.m_peerlist.get_white_peers_count();
2015 }
2016 //-----------------------------------------------------------------------------------
2017 template<class t_payload_net_handler>
2018 size_t node_server<t_payload_net_handler>::get_public_gray_peers_count()
2019 {
2020 auto public_zone = m_network_zones.find(epee::net_utils::zone::public_);
2021 if (public_zone == m_network_zones.end())
2022 return 0;
2023 return public_zone->second.m_peerlist.get_gray_peers_count();
2024 }
2025 //-----------------------------------------------------------------------------------
2026 template<class t_payload_net_handler>
2027 void node_server<t_payload_net_handler>::get_public_peerlist(std::vector<peerlist_entry>& gray, std::vector<peerlist_entry>& white)
2028 {
2029 auto public_zone = m_network_zones.find(epee::net_utils::zone::public_);
2030 if (public_zone != m_network_zones.end())
2031 public_zone->second.m_peerlist.get_peerlist(gray, white);
2032 }
2033 //-----------------------------------------------------------------------------------
2034 template<class t_payload_net_handler>
2035 void node_server<t_payload_net_handler>::get_peerlist(std::vector<peerlist_entry>& gray, std::vector<peerlist_entry>& white)
2036 {
2037 for (auto &zone: m_network_zones)
2038 {
2039 zone.second.m_peerlist.get_peerlist(gray, white); // appends
2040 }
2041 }
2042 //-----------------------------------------------------------------------------------
2043 template<class t_payload_net_handler>
2044 bool node_server<t_payload_net_handler>::idle_worker()
2045 {
2046 m_peer_handshake_idle_maker_interval.do_call(boost::bind(&node_server<t_payload_net_handler>::peer_sync_idle_maker, this));
2047 m_connections_maker_interval.do_call(boost::bind(&node_server<t_payload_net_handler>::connections_maker, this));
2048 m_gray_peerlist_housekeeping_interval.do_call(boost::bind(&node_server<t_payload_net_handler>::gray_peerlist_housekeeping, this));
2049 m_peerlist_store_interval.do_call(boost::bind(&node_server<t_payload_net_handler>::store_config, this));
2050 m_incoming_connections_interval.do_call(boost::bind(&node_server<t_payload_net_handler>::check_incoming_connections, this));
2051 m_dns_blocklist_interval.do_call(boost::bind(&node_server<t_payload_net_handler>::update_dns_blocklist, this));
2052 return true;
2053 }
2054 //-----------------------------------------------------------------------------------
2055 template<class t_payload_net_handler>
2056 bool node_server<t_payload_net_handler>::update_dns_blocklist()
2057 {
2058 if (!m_enable_dns_blocklist)
2059 return true;
2060 if (m_nettype != cryptonote::MAINNET)
2061 return true;
2062
2063 static const std::vector<std::string> dns_urls = {
2064 "blocklist.moneropulse.se"
2065 , "blocklist.moneropulse.org"
2066 , "blocklist.moneropulse.net"
2067 , "blocklist.moneropulse.no"
2068 , "blocklist.moneropulse.fr"
2069 , "blocklist.moneropulse.de"
2070 , "blocklist.moneropulse.ch"
2071 };
2072
2073 std::vector<std::string> records;
2074 if (!tools::dns_utils::load_txt_records_from_dns(records, dns_urls))
2075 return true;
2076
2077 unsigned good = 0, bad = 0;
2078 for (const auto& record : records)
2079 {
2080 std::vector<std::string> ips;
2081 boost::split(ips, record, boost::is_any_of(";"));
2082 for (const auto &ip: ips)
2083 {
2084 if (ip.empty())
2085 continue;
2086 auto subnet = net::get_ipv4_subnet_address(ip);
2087 if (subnet)
2088 {
2089 block_subnet(*subnet, DNS_BLOCKLIST_LIFETIME);
2090 ++good;
2091 continue;
2092 }
2093 const expect<epee::net_utils::network_address> parsed_addr = net::get_network_address(ip, 0);
2094 if (parsed_addr)
2095 {
2096 block_host(*parsed_addr, DNS_BLOCKLIST_LIFETIME, true);
2097 ++good;
2098 continue;
2099 }
2100 MWARNING("Invalid IP address or subnet from DNS blocklist: " << ip << " - " << parsed_addr.error());
2101 ++bad;
2102 }
2103 }
2104 if (good > 0)
2105 MINFO(good << " addresses added to the blocklist");
2106 return true;
2107 }
2108 //-----------------------------------------------------------------------------------
2109 template<class t_payload_net_handler>
2110 bool node_server<t_payload_net_handler>::check_incoming_connections()
2111 {
2112 if (m_offline)
2113 return true;
2114
2115 const auto public_zone = m_network_zones.find(epee::net_utils::zone::public_);
2116 if (public_zone != m_network_zones.end() && get_incoming_connections_count(public_zone->second) == 0)
2117 {
2118 if (m_hide_my_port || public_zone->second.m_config.m_net_config.max_in_connection_count == 0)
2119 {
2120 MGINFO("Incoming connections disabled, enable them for full connectivity");
2121 }
2122 else
2123 {
2124 if (m_igd == delayed_igd)
2125 {
2126 MWARNING("No incoming connections, trying to setup IGD");
2127 add_upnp_port_mapping(m_listening_port);
2128 m_igd = igd;
2129 }
2130 else
2131 {
2132 const el::Level level = el::Level::Warning;
2133 MCLOG_RED(level, "global", "No incoming connections - check firewalls/routers allow port " << get_this_peer_port());
2134 }
2135 }
2136 }
2137 return true;
2138 }
2139 //-----------------------------------------------------------------------------------
2140 template<class t_payload_net_handler>
2141 bool node_server<t_payload_net_handler>::peer_sync_idle_maker()
2142 {
2143 MDEBUG("STARTED PEERLIST IDLE HANDSHAKE");
2144 typedef std::list<std::pair<epee::net_utils::connection_context_base, peerid_type> > local_connects_type;
2145 local_connects_type cncts;
2146 for(auto& zone : m_network_zones)
2147 {
2148 zone.second.m_net_server.get_config_object().foreach_connection([&](p2p_connection_context& cntxt)
2149 {
2150 if(cntxt.peer_id && !cntxt.m_in_timedsync)
2151 {
2152 cntxt.m_in_timedsync = true;
2153 cncts.push_back(local_connects_type::value_type(cntxt, cntxt.peer_id));//do idle sync only with handshaked connections
2154 }
2155 return true;
2156 });
2157 }
2158
2159 std::for_each(cncts.begin(), cncts.end(), [&](const typename local_connects_type::value_type& vl){do_peer_timed_sync(vl.first, vl.second);});
2160
2161 MDEBUG("FINISHED PEERLIST IDLE HANDSHAKE");
2162 return true;
2163 }
2164 //-----------------------------------------------------------------------------------
2165 template<class t_payload_net_handler>
2166 bool node_server<t_payload_net_handler>::sanitize_peerlist(std::vector<peerlist_entry>& local_peerlist)
2167 {
2168 for (size_t i = 0; i < local_peerlist.size(); ++i)
2169 {
2170 bool ignore = false;
2171 peerlist_entry &be = local_peerlist[i];
2172 epee::net_utils::network_address &na = be.adr;
2173 if (na.is_loopback() || na.is_local())
2174 {
2175 ignore = true;
2176 }
2177 else if (be.adr.get_type_id() == epee::net_utils::ipv4_network_address::get_type_id())
2178 {
2179 const epee::net_utils::ipv4_network_address &ipv4 = na.as<const epee::net_utils::ipv4_network_address>();
2180 if (ipv4.ip() == 0)
2181 ignore = true;
2182 else if (ipv4.port() == be.rpc_port)
2183 ignore = true;
2184 }
2185 if (be.pruning_seed && (be.pruning_seed < tools::make_pruning_seed(1, CRYPTONOTE_PRUNING_LOG_STRIPES) || be.pruning_seed > tools::make_pruning_seed(1ul << CRYPTONOTE_PRUNING_LOG_STRIPES, CRYPTONOTE_PRUNING_LOG_STRIPES)))
2186 ignore = true;
2187 if (ignore)
2188 {
2189 MDEBUG("Ignoring " << be.adr.str());
2190 std::swap(local_peerlist[i], local_peerlist[local_peerlist.size() - 1]);
2191 local_peerlist.resize(local_peerlist.size() - 1);
2192 --i;
2193 continue;
2194 }
2195 local_peerlist[i].last_seen = 0;
2196 }
2197 return true;
2198 }
2199 //-----------------------------------------------------------------------------------
2200 template<class t_payload_net_handler>
2201 bool node_server<t_payload_net_handler>::handle_remote_peerlist(const std::vector<peerlist_entry>& peerlist, const epee::net_utils::connection_context_base& context)
2202 {
2203 if (peerlist.size() > P2P_MAX_PEERS_IN_HANDSHAKE)
2204 {
2205 MWARNING(context << "peer sent " << peerlist.size() << " peers, considered spamming");
2206 return false;
2207 }
2208 std::vector<peerlist_entry> peerlist_ = peerlist;
2209 if(!sanitize_peerlist(peerlist_))
2210 return false;
2211
2212 const epee::net_utils::zone zone = context.m_remote_address.get_zone();
2213 for(const auto& peer : peerlist_)
2214 {
2215 if(peer.adr.get_zone() != zone)
2216 {
2217 MWARNING(context << " sent peerlist from another zone, dropping");
2218 return false;
2219 }
2220 }
2221
2222 LOG_DEBUG_CC(context, "REMOTE PEERLIST: remote peerlist size=" << peerlist_.size());
2223 LOG_TRACE_CC(context, "REMOTE PEERLIST: " << ENDL << print_peerlist_to_string(peerlist_));
2224 CRITICAL_REGION_LOCAL(m_blocked_hosts_lock);
2225 return m_network_zones.at(context.m_remote_address.get_zone()).m_peerlist.merge_peerlist(peerlist_, [this](const peerlist_entry &pe) {
2226 return !is_addr_recently_failed(pe.adr) && is_remote_host_allowed(pe.adr);
2227 });
2228 }
2229 //-----------------------------------------------------------------------------------
2230 template<class t_payload_net_handler>
2231 bool node_server<t_payload_net_handler>::get_local_node_data(basic_node_data& node_data, const network_zone& zone)
2232 {
2233 node_data.peer_id = zone.m_config.m_peer_id;
2234 if(!m_hide_my_port && zone.m_can_pingback)
2235 node_data.my_port = m_external_port ? m_external_port : m_listening_port;
2236 else
2237 node_data.my_port = 0;
2238 node_data.rpc_port = zone.m_can_pingback ? m_rpc_port : 0;
2239 node_data.rpc_credits_per_hash = zone.m_can_pingback ? m_rpc_credits_per_hash : 0;
2240 node_data.network_id = m_network_id;
2241 node_data.support_flags = zone.m_config.m_support_flags;
2242 return true;
2243 }
2244 //-----------------------------------------------------------------------------------
2245 template<class t_payload_net_handler>
2246 int node_server<t_payload_net_handler>::handle_get_support_flags(int command, COMMAND_REQUEST_SUPPORT_FLAGS::request& arg, COMMAND_REQUEST_SUPPORT_FLAGS::response& rsp, p2p_connection_context& context)
2247 {
2248 rsp.support_flags = m_network_zones.at(context.m_remote_address.get_zone()).m_config.m_support_flags;
2249 return 1;
2250 }
2251 //-----------------------------------------------------------------------------------
2252 template<class t_payload_net_handler>
2253 void node_server<t_payload_net_handler>::request_callback(const epee::net_utils::connection_context_base& context)
2254 {
2255 m_network_zones.at(context.m_remote_address.get_zone()).m_net_server.get_config_object().request_callback(context.m_connection_id);
2256 }
2257 //-----------------------------------------------------------------------------------
2258 template<class t_payload_net_handler>
2259 bool node_server<t_payload_net_handler>::relay_notify_to_list(int command, epee::levin::message_writer data_buff, std::vector<std::pair<epee::net_utils::zone, boost::uuids::uuid>> connections)
2260 {
2261 epee::byte_slice message = data_buff.finalize_notify(command);
2262 std::sort(connections.begin(), connections.end());
2263 auto zone = m_network_zones.begin();
2264 for(const auto& c_id: connections)
2265 {
2266 for (;;)
2267 {
2268 if (zone == m_network_zones.end())
2269 {
2270 MWARNING("Unable to relay all messages, " << epee::net_utils::zone_to_string(c_id.first) << " not available");
2271 return false;
2272 }
2273 if (c_id.first <= zone->first)
2274 break;
2275
2276 ++zone;
2277 }
2278 if (zone->first == c_id.first)
2279 zone->second.m_net_server.get_config_object().send(message.clone(), c_id.second);
2280 }
2281 return true;
2282 }
2283 //-----------------------------------------------------------------------------------
2284 template<class t_payload_net_handler>
2285 epee::net_utils::zone node_server<t_payload_net_handler>::send_txs(std::vector<cryptonote::blobdata> txs, const epee::net_utils::zone origin, const boost::uuids::uuid& source, const cryptonote::relay_method tx_relay)
2286 {
2287 namespace enet = epee::net_utils;
2288
2289 const auto send = [&txs, &source, tx_relay] (std::pair<const enet::zone, network_zone>& network)
2290 {
2291 if (network.second.m_notifier.send_txs(std::move(txs), source, tx_relay))
2292 return network.first;
2293 return enet::zone::invalid;
2294 };
2295
2296 if (m_network_zones.empty())
2297 return enet::zone::invalid;
2298
2299 if (origin != enet::zone::invalid)
2300 return send(*m_network_zones.begin()); // send all txs received via p2p over public network
2301
2302 if (m_network_zones.size() <= 2)
2303 return send(*m_network_zones.rbegin()); // see static asserts below; sends over anonymity network iff enabled
2304
2305 /* These checks are to ensure that i2p is highest priority if multiple
2306 zones are selected. Make sure to update logic if the values cannot be
2307 in the same relative order. `m_network_zones` must be sorted map too. */
2308 static_assert(std::is_same<std::underlying_type<enet::zone>::type, std::uint8_t>{}, "expected uint8_t zone");
2309 static_assert(unsigned(enet::zone::invalid) == 0, "invalid expected to be 0");
2310 static_assert(unsigned(enet::zone::public_) == 1, "public_ expected to be 1");
2311 static_assert(unsigned(enet::zone::i2p) == 2, "i2p expected to be 2");
2312 static_assert(unsigned(enet::zone::tor) == 3, "tor expected to be 3");
2313
2314 // check for anonymity networks with noise and connections
2315 for (auto network = ++m_network_zones.begin(); network != m_network_zones.end(); ++network)
2316 {
2317 if (enet::zone::tor < network->first)
2318 break; // unknown network
2319
2320 const auto status = network->second.m_notifier.get_status();
2321 if (status.has_noise && status.connections_filled)
2322 return send(*network);
2323 }
2324
2325 // use the anonymity network with outbound support
2326 for (auto network = ++m_network_zones.begin(); network != m_network_zones.end(); ++network)
2327 {
2328 if (enet::zone::tor < network->first)
2329 break; // unknown network
2330
2331 const auto status = network->second.m_notifier.get_status();
2332 if (network->second.m_connect && status.has_outgoing)
2333 return send(*network);
2334 }
2335
2336 MWARNING("Unable to send " << txs.size() << " transaction(s): anonymity networks had no outgoing connections");
2337 return enet::zone::invalid;
2338 }
2339 //-----------------------------------------------------------------------------------
2340 template<class t_payload_net_handler>
2341 void node_server<t_payload_net_handler>::callback(p2p_connection_context& context)
2342 {
2343 m_payload_handler.on_callback(context);
2344 }
2345 //-----------------------------------------------------------------------------------
2346 template<class t_payload_net_handler>
2347 bool node_server<t_payload_net_handler>::invoke_notify_to_peer(const int command, epee::levin::message_writer message, const epee::net_utils::connection_context_base& context)
2348 {
2349 if(is_filtered_command(context.m_remote_address, command))
2350 return false;
2351
2352 network_zone& zone = m_network_zones.at(context.m_remote_address.get_zone());
2353 int res = zone.m_net_server.get_config_object().send(message.finalize_notify(command), context.m_connection_id);
2354 return res > 0;
2355 }
2356 //-----------------------------------------------------------------------------------
2357 template<class t_payload_net_handler>
2358 bool node_server<t_payload_net_handler>::drop_connection(const epee::net_utils::connection_context_base& context)
2359 {
2360 m_network_zones.at(context.m_remote_address.get_zone()).m_net_server.get_config_object().close(context.m_connection_id);
2361 return true;
2362 }
2363 //-----------------------------------------------------------------------------------
2364 template<class t_payload_net_handler> template<class t_callback>
2365 bool node_server<t_payload_net_handler>::try_ping(basic_node_data& node_data, p2p_connection_context& context, const t_callback &cb)
2366 {
2367 if(!node_data.my_port)
2368 return false;
2369
2370 bool address_ok = (context.m_remote_address.get_type_id() == epee::net_utils::ipv4_network_address::get_type_id() || context.m_remote_address.get_type_id() == epee::net_utils::ipv6_network_address::get_type_id());
2371 CHECK_AND_ASSERT_MES(address_ok, false,
2372 "Only IPv4 or IPv6 addresses are supported here");
2373
2374 const epee::net_utils::network_address na = context.m_remote_address;
2375 std::string ip;
2376 uint32_t ipv4_addr = 0;
2377 boost::asio::ip::address_v6 ipv6_addr;
2378 bool is_ipv4;
2379 if (na.get_type_id() == epee::net_utils::ipv4_network_address::get_type_id())
2380 {
2381 ipv4_addr = na.as<const epee::net_utils::ipv4_network_address>().ip();
2382 ip = epee::string_tools::get_ip_string_from_int32(ipv4_addr);
2383 is_ipv4 = true;
2384 }
2385 else
2386 {
2387 ipv6_addr = na.as<const epee::net_utils::ipv6_network_address>().ip();
2388 ip = ipv6_addr.to_string();
2389 is_ipv4 = false;
2390 }
2391 network_zone& zone = m_network_zones.at(na.get_zone());
2392
2393 if(!zone.m_peerlist.is_host_allowed(context.m_remote_address))
2394 return false;
2395
2396 std::string port = epee::string_tools::num_to_string_fast(node_data.my_port);
2397
2398 epee::net_utils::network_address address;
2399 if (is_ipv4)
2400 {
2401 address = epee::net_utils::network_address{epee::net_utils::ipv4_network_address(ipv4_addr, node_data.my_port)};
2402 }
2403 else
2404 {
2405 address = epee::net_utils::network_address{epee::net_utils::ipv6_network_address(ipv6_addr, node_data.my_port)};
2406 }
2407 peerid_type pr = node_data.peer_id;
2408 bool r = zone.m_net_server.connect_async(ip, port, zone.m_config.m_net_config.ping_connection_timeout, [cb, /*context,*/ address, pr, this](
2409 const typename net_server::t_connection_context& ping_context,
2410 const boost::system::error_code& ec)->bool
2411 {
2412 if(ec)
2413 {
2414 LOG_WARNING_CC(ping_context, "back ping connect failed to " << address.str());
2415 return false;
2416 }
2417 COMMAND_PING::request req;
2418 COMMAND_PING::response rsp;
2419 //vc2010 workaround
2420 /*std::string ip_ = ip;
2421 std::string port_=port;
2422 peerid_type pr_ = pr;
2423 auto cb_ = cb;*/
2424
2425 // GCC 5.1.0 gives error with second use of uint64_t (peerid_type) variable.
2426 peerid_type pr_ = pr;
2427
2428 network_zone& zone = m_network_zones.at(address.get_zone());
2429
2430 bool inv_call_res = epee::net_utils::async_invoke_remote_command2<COMMAND_PING::response>(ping_context, COMMAND_PING::ID, req, zone.m_net_server.get_config_object(),
2431 [=](int code, const COMMAND_PING::response& rsp, p2p_connection_context& context)
2432 {
2433 if(code <= 0)
2434 {
2435 LOG_WARNING_CC(ping_context, "Failed to invoke COMMAND_PING to " << address.str() << "(" << code << ", " << epee::levin::get_err_descr(code) << ")");
2436 return;
2437 }
2438
2439 network_zone& zone = m_network_zones.at(address.get_zone());
2440 if(rsp.status != PING_OK_RESPONSE_STATUS_TEXT || pr != rsp.peer_id)
2441 {
2442 LOG_WARNING_CC(ping_context, "back ping invoke wrong response \"" << rsp.status << "\" from" << address.str() << ", hsh_peer_id=" << pr_ << ", rsp.peer_id=" << peerid_to_string(rsp.peer_id));
2443 zone.m_net_server.get_config_object().close(ping_context.m_connection_id);
2444 return;
2445 }
2446 zone.m_net_server.get_config_object().close(ping_context.m_connection_id);
2447 cb();
2448 });
2449
2450 if(!inv_call_res)
2451 {
2452 LOG_WARNING_CC(ping_context, "back ping invoke failed to " << address.str());
2453 zone.m_net_server.get_config_object().close(ping_context.m_connection_id);
2454 return false;
2455 }
2456 return true;
2457 }, "0.0.0.0", m_ssl_support);
2458 if(!r)
2459 {
2460 LOG_WARNING_CC(context, "Failed to call connect_async, network error.");
2461 }
2462 return r;
2463 }
2464 //-----------------------------------------------------------------------------------
2465 template<class t_payload_net_handler>
2466 bool node_server<t_payload_net_handler>::try_get_support_flags(const p2p_connection_context& context, std::function<void(p2p_connection_context&, const uint32_t&)> f)
2467 {
2468 if(context.m_remote_address.get_zone() != epee::net_utils::zone::public_)
2469 return false;
2470
2471 COMMAND_REQUEST_SUPPORT_FLAGS::request support_flags_request;
2472 bool r = epee::net_utils::async_invoke_remote_command2<typename COMMAND_REQUEST_SUPPORT_FLAGS::response>
2473 (
2474 context,
2475 COMMAND_REQUEST_SUPPORT_FLAGS::ID,
2476 support_flags_request,
2477 m_network_zones.at(epee::net_utils::zone::public_).m_net_server.get_config_object(),
2478 [=](int code, const typename COMMAND_REQUEST_SUPPORT_FLAGS::response& rsp, p2p_connection_context& context_)
2479 {
2480 if(code < 0)
2481 {
2482 LOG_WARNING_CC(context_, "COMMAND_REQUEST_SUPPORT_FLAGS invoke failed. (" << code << ", " << epee::levin::get_err_descr(code) << ")");
2483 return;
2484 }
2485
2486 f(context_, rsp.support_flags);
2487 },
2488 P2P_DEFAULT_HANDSHAKE_INVOKE_TIMEOUT
2489 );
2490
2491 return r;
2492 }
2493 //-----------------------------------------------------------------------------------
2494 template<class t_payload_net_handler>
2495 int node_server<t_payload_net_handler>::handle_timed_sync(int command, typename COMMAND_TIMED_SYNC::request& arg, typename COMMAND_TIMED_SYNC::response& rsp, p2p_connection_context& context)
2496 {
2497 if(!m_payload_handler.process_payload_sync_data(arg.payload_data, context, false))
2498 {
2499 LOG_WARNING_CC(context, "Failed to process_payload_sync_data(), dropping connection");
2500 drop_connection(context);
2501 return 1;
2502 }
2503
2504 //fill response
2505 const epee::net_utils::zone zone_type = context.m_remote_address.get_zone();
2506 network_zone& zone = m_network_zones.at(zone_type);
2507
2508 //will add self to peerlist if in same zone as outgoing later in this function
2509 const bool outgoing_to_same_zone = !context.m_is_income && zone.m_our_address.get_zone() == zone_type;
2510 const uint32_t max_peerlist_size = P2P_DEFAULT_PEERS_IN_HANDSHAKE - (outgoing_to_same_zone ? 1 : 0);
2511
2512 std::vector<peerlist_entry> local_peerlist_new;
2513 zone.m_peerlist.get_peerlist_head(local_peerlist_new, true, max_peerlist_size);
2514
2515 /* Tor/I2P nodes receiving connections via forwarding (from tor/i2p daemon)
2516 do not know the address of the connecting peer. This is relayed to them,
2517 iff the node has setup an inbound hidden service.
2518
2519 \note Insert into `local_peerlist_new` so that it is only sent once like
2520 the other peers. */
2521 if(outgoing_to_same_zone)
2522 {
2523 local_peerlist_new.insert(
2524 local_peerlist_new.begin() + crypto::rand_range(std::size_t(0), local_peerlist_new.size()),
2525 peerlist_entry{zone.m_our_address, zone.m_config.m_peer_id, 0}
2526 );
2527 }
2528
2529 //only include out peers we did not already send
2530 rsp.local_peerlist_new.reserve(local_peerlist_new.size());
2531 for (auto &pe: local_peerlist_new)
2532 {
2533 if (!context.sent_addresses.insert(pe.adr).second)
2534 continue;
2535 rsp.local_peerlist_new.push_back(std::move(pe));
2536 }
2537 m_payload_handler.get_payload_sync_data(rsp.payload_data);
2538
2539 LOG_DEBUG_CC(context, "COMMAND_TIMED_SYNC");
2540 return 1;
2541 }
2542 //-----------------------------------------------------------------------------------
2543 template<class t_payload_net_handler>
2544 int node_server<t_payload_net_handler>::handle_handshake(int command, typename COMMAND_HANDSHAKE::request& arg, typename COMMAND_HANDSHAKE::response& rsp, p2p_connection_context& context)
2545 {
2546 if(arg.node_data.network_id != m_network_id)
2547 {
2548
2549 LOG_INFO_CC(context, "WRONG NETWORK AGENT CONNECTED! id=" << arg.node_data.network_id);
2550 drop_connection(context);
2551 add_host_fail(context.m_remote_address);
2552 return 1;
2553 }
2554
2555 if(!context.m_is_income)
2556 {
2557 LOG_WARNING_CC(context, "COMMAND_HANDSHAKE came not from incoming connection");
2558 drop_connection(context);
2559 add_host_fail(context.m_remote_address);
2560 return 1;
2561 }
2562
2563 if(context.peer_id)
2564 {
2565 LOG_WARNING_CC(context, "COMMAND_HANDSHAKE came, but seems that connection already have associated peer_id (double COMMAND_HANDSHAKE?)");
2566 drop_connection(context);
2567 return 1;
2568 }
2569
2570 const auto azone = context.m_remote_address.get_zone();
2571 network_zone& zone = m_network_zones.at(azone);
2572
2573 // test only the remote end's zone, otherwise an attacker could connect to you on clearnet
2574 // and pass in a tor connection's peer id, and deduce the two are the same if you reject it
2575 if(azone == epee::net_utils::zone::public_ && arg.node_data.peer_id == zone.m_config.m_peer_id)
2576 {
2577 LOG_DEBUG_CC(context, "Connection to self detected, dropping connection");
2578 drop_connection(context);
2579 return 1;
2580 }
2581
2582 if(!m_payload_handler.process_payload_sync_data(arg.payload_data, context, true))
2583 {
2584 LOG_WARNING_CC(context, "COMMAND_HANDSHAKE came, but process_payload_sync_data returned false, dropping connection.");
2585 drop_connection(context);
2586 return 1;
2587 }
2588
2589 zone.m_notifier.on_handshake_complete(context.m_connection_id, context.m_is_income);
2590
2591 //associate peer_id with this connection
2592 context.peer_id = arg.node_data.peer_id;
2593 context.m_in_timedsync = false;
2594 context.m_rpc_port = arg.node_data.rpc_port;
2595 context.m_rpc_credits_per_hash = arg.node_data.rpc_credits_per_hash;
2596 context.support_flags = arg.node_data.support_flags;
2597
2598 if(arg.node_data.my_port && zone.m_can_pingback)
2599 {
2600 peerid_type peer_id_l = arg.node_data.peer_id;
2601 uint32_t port_l = arg.node_data.my_port;
2602 //try ping to be sure that we can add this peer to peer_list
2603 try_ping(arg.node_data, context, [peer_id_l, port_l, context, this]()
2604 {
2605 CHECK_AND_ASSERT_MES((context.m_remote_address.get_type_id() == epee::net_utils::ipv4_network_address::get_type_id() || context.m_remote_address.get_type_id() == epee::net_utils::ipv6_network_address::get_type_id()), void(),
2606 "Only IPv4 or IPv6 addresses are supported here");
2607 //called only(!) if success pinged, update local peerlist
2608 peerlist_entry pe;
2609 const epee::net_utils::network_address na = context.m_remote_address;
2610 if (context.m_remote_address.get_type_id() == epee::net_utils::ipv4_network_address::get_type_id())
2611 {
2612 pe.adr = epee::net_utils::ipv4_network_address(na.as<epee::net_utils::ipv4_network_address>().ip(), port_l);
2613 }
2614 else
2615 {
2616 pe.adr = epee::net_utils::ipv6_network_address(na.as<epee::net_utils::ipv6_network_address>().ip(), port_l);
2617 }
2618 time_t last_seen;
2619 time(&last_seen);
2620 pe.last_seen = static_cast<int64_t>(last_seen);
2621 pe.id = peer_id_l;
2622 pe.pruning_seed = context.m_pruning_seed;
2623 pe.rpc_port = context.m_rpc_port;
2624 pe.rpc_credits_per_hash = context.m_rpc_credits_per_hash;
2625 this->m_network_zones.at(context.m_remote_address.get_zone()).m_peerlist.append_with_peer_white(pe);
2626 LOG_DEBUG_CC(context, "PING SUCCESS " << context.m_remote_address.host_str() << ":" << port_l);
2627 });
2628 }
2629
2630 if (context.support_flags == 0)
2631 try_get_support_flags(context, [](p2p_connection_context& flags_context, const uint32_t& support_flags)
2632 {
2633 flags_context.support_flags = support_flags;
2634 });
2635
2636 //fill response
2637 zone.m_peerlist.get_peerlist_head(rsp.local_peerlist_new, true);
2638 for (const auto &e: rsp.local_peerlist_new)
2639 context.sent_addresses.insert(e.adr);
2640 get_local_node_data(rsp.node_data, zone);
2641 m_payload_handler.get_payload_sync_data(rsp.payload_data);
2642 LOG_DEBUG_CC(context, "COMMAND_HANDSHAKE");
2643 return 1;
2644 }
2645 //-----------------------------------------------------------------------------------
2646 template<class t_payload_net_handler>
2647 int node_server<t_payload_net_handler>::handle_ping(int command, COMMAND_PING::request& arg, COMMAND_PING::response& rsp, p2p_connection_context& context)
2648 {
2649 LOG_DEBUG_CC(context, "COMMAND_PING");
2650 rsp.status = PING_OK_RESPONSE_STATUS_TEXT;
2651 rsp.peer_id = m_network_zones.at(context.m_remote_address.get_zone()).m_config.m_peer_id;
2652 return 1;
2653 }
2654 //-----------------------------------------------------------------------------------
2655 template<class t_payload_net_handler>
2656 bool node_server<t_payload_net_handler>::log_peerlist()
2657 {
2658 std::vector<peerlist_entry> pl_white;
2659 std::vector<peerlist_entry> pl_gray;
2660 for (auto& zone : m_network_zones)
2661 zone.second.m_peerlist.get_peerlist(pl_gray, pl_white);
2662 MINFO(ENDL << "Peerlist white:" << ENDL << print_peerlist_to_string(pl_white) << ENDL << "Peerlist gray:" << ENDL << print_peerlist_to_string(pl_gray) );
2663 return true;
2664 }
2665 //-----------------------------------------------------------------------------------
2666 template<class t_payload_net_handler>
2667 bool node_server<t_payload_net_handler>::log_connections()
2668 {
2669 MINFO("Connections: \r\n" << print_connections_container() );
2670 return true;
2671 }
2672 //-----------------------------------------------------------------------------------
2673 template<class t_payload_net_handler>
2674 std::string node_server<t_payload_net_handler>::print_connections_container()
2675 {
2676
2677 std::stringstream ss;
2678 for (auto& zone : m_network_zones)
2679 {
2680 zone.second.m_net_server.get_config_object().foreach_connection([&](const p2p_connection_context& cntxt)
2681 {
2682 ss << cntxt.m_remote_address.str()
2683 << " \t\tpeer_id " << peerid_to_string(cntxt.peer_id)
2684 << " \t\tconn_id " << cntxt.m_connection_id << (cntxt.m_is_income ? " INC":" OUT")
2685 << std::endl;
2686 return true;
2687 });
2688 }
2689 std::string s = ss.str();
2690 return s;
2691 }
2692 //-----------------------------------------------------------------------------------
2693 template<class t_payload_net_handler>
2694 void node_server<t_payload_net_handler>::on_connection_new(p2p_connection_context& context)
2695 {
2696 MINFO("["<< epee::net_utils::print_connection_context(context) << "] NEW CONNECTION");
2697 }
2698 //-----------------------------------------------------------------------------------
2699 template<class t_payload_net_handler>
2700 void node_server<t_payload_net_handler>::on_connection_close(p2p_connection_context& context)
2701 {
2702 network_zone& zone = m_network_zones.at(context.m_remote_address.get_zone());
2703 if (!zone.m_net_server.is_stop_signal_sent() && !context.m_is_income) {
2704 epee::net_utils::network_address na = AUTO_VAL_INIT(na);
2705 na = context.m_remote_address;
2706
2707 zone.m_peerlist.remove_from_peer_anchor(na);
2708 }
2709
2710 if (!zone.m_net_server.is_stop_signal_sent()) {
2711 zone.m_notifier.on_connection_close(context.m_connection_id);
2712 }
2713 m_payload_handler.on_connection_close(context);
2714
2715 MINFO("["<< epee::net_utils::print_connection_context(context) << "] CLOSE CONNECTION");
2716 }
2717
2718 template<class t_payload_net_handler>
2719 bool node_server<t_payload_net_handler>::is_priority_node(const epee::net_utils::network_address& na)
2720 {
2721 return (std::find(m_priority_peers.begin(), m_priority_peers.end(), na) != m_priority_peers.end()) || (std::find(m_exclusive_peers.begin(), m_exclusive_peers.end(), na) != m_exclusive_peers.end());
2722 }
2723
2724 template<class t_payload_net_handler> template <class Container>
2725 bool node_server<t_payload_net_handler>::connect_to_peerlist(const Container& peers)
2726 {
2727 const network_zone& public_zone = m_network_zones.at(epee::net_utils::zone::public_);
2728 for(const epee::net_utils::network_address& na: peers)
2729 {
2730 if(public_zone.m_net_server.is_stop_signal_sent())
2731 return false;
2732
2733 if(is_addr_connected(na))
2734 continue;
2735
2736 try_to_connect_and_handshake_with_new_peer(na);
2737 }
2738
2739 return true;
2740 }
2741
2742 template<class t_payload_net_handler> template <class Container>
2743 bool node_server<t_payload_net_handler>::parse_peers_and_add_to_container(const boost::program_options::variables_map& vm, const command_line::arg_descriptor<std::vector<std::string> > & arg, Container& container)
2744 {
2745 std::vector<std::string> perrs = command_line::get_arg(vm, arg);
2746
2747 for(const std::string& pr_str: perrs)
2748 {
2749 const uint16_t default_port = cryptonote::get_config(m_nettype).P2P_DEFAULT_PORT;
2750 expect<epee::net_utils::network_address> adr = net::get_network_address(pr_str, default_port);
2751 if (adr)
2752 {
2753 add_zone(adr->get_zone());
2754 container.push_back(std::move(*adr));
2755 continue;
2756 }
2757 std::vector<epee::net_utils::network_address> resolved_addrs;
2758 bool r = append_net_address(resolved_addrs, pr_str, default_port);
2759 CHECK_AND_ASSERT_MES(r, false, "Failed to parse or resolve address from string: " << pr_str);
2760 for (const epee::net_utils::network_address& addr : resolved_addrs)
2761 {
2762 container.push_back(addr);
2763 }
2764 }
2765
2766 return true;
2767 }
2768
2769 template<class t_payload_net_handler>
2770 bool node_server<t_payload_net_handler>::set_max_out_peers(network_zone& zone, int64_t max)
2771 {
2772 if(max == -1) {
2773 zone.m_config.m_net_config.max_out_connection_count = P2P_DEFAULT_CONNECTIONS_COUNT;
2774 return true;
2775 }
2776 zone.m_config.m_net_config.max_out_connection_count = max;
2777 return true;
2778 }
2779
2780 template<class t_payload_net_handler>
2781 bool node_server<t_payload_net_handler>::set_max_in_peers(network_zone& zone, int64_t max)
2782 {
2783 zone.m_config.m_net_config.max_in_connection_count = max;
2784 return true;
2785 }
2786
2787 template<class t_payload_net_handler>
2788 void node_server<t_payload_net_handler>::change_max_out_public_peers(size_t count)
2789 {
2790 auto public_zone = m_network_zones.find(epee::net_utils::zone::public_);
2791 if (public_zone != m_network_zones.end())
2792 {
2793 const auto current = public_zone->second.m_net_server.get_config_object().get_out_connections_count();
2794 public_zone->second.m_config.m_net_config.max_out_connection_count = count;
2795 if(current > count)
2796 public_zone->second.m_net_server.get_config_object().del_out_connections(current - count);
2797 m_payload_handler.set_max_out_peers(epee::net_utils::zone::public_, count);
2798 }
2799 }
2800
2801 template<class t_payload_net_handler>
2802 uint32_t node_server<t_payload_net_handler>::get_max_out_public_peers() const
2803 {
2804 const auto public_zone = m_network_zones.find(epee::net_utils::zone::public_);
2805 if (public_zone == m_network_zones.end())
2806 return 0;
2807 return public_zone->second.m_config.m_net_config.max_out_connection_count;
2808 }
2809
2810 template<class t_payload_net_handler>
2811 void node_server<t_payload_net_handler>::change_max_in_public_peers(size_t count)
2812 {
2813 auto public_zone = m_network_zones.find(epee::net_utils::zone::public_);
2814 if (public_zone != m_network_zones.end())
2815 {
2816 const auto current = public_zone->second.m_net_server.get_config_object().get_in_connections_count();
2817 public_zone->second.m_config.m_net_config.max_in_connection_count = count;
2818 if(current > count)
2819 public_zone->second.m_net_server.get_config_object().del_in_connections(current - count);
2820 }
2821 }
2822
2823 template<class t_payload_net_handler>
2824 uint32_t node_server<t_payload_net_handler>::get_max_in_public_peers() const
2825 {
2826 const auto public_zone = m_network_zones.find(epee::net_utils::zone::public_);
2827 if (public_zone == m_network_zones.end())
2828 return 0;
2829 return public_zone->second.m_config.m_net_config.max_in_connection_count;
2830 }
2831
2832 template<class t_payload_net_handler>
2833 bool node_server<t_payload_net_handler>::set_tos_flag(const boost::program_options::variables_map& vm, int flag)
2834 {
2835 if(flag==-1){
2836 return true;
2837 }
2838 epee::net_utils::connection<epee::levin::async_protocol_handler<p2p_connection_context> >::set_tos_flag(flag);
2839 _dbg1("Set ToS flag " << flag);
2840 return true;
2841 }
2842
2843 template<class t_payload_net_handler>
2844 bool node_server<t_payload_net_handler>::set_rate_up_limit(const boost::program_options::variables_map& vm, int64_t limit)
2845 {
2846 this->islimitup=(limit != -1) && (limit != default_limit_up);
2847
2848 if (limit==-1) {
2849 limit=default_limit_up;
2850 }
2851
2852 epee::net_utils::connection<epee::levin::async_protocol_handler<p2p_connection_context> >::set_rate_up_limit( limit );
2853 MINFO("Set limit-up to " << limit << " kB/s");
2854 return true;
2855 }
2856
2857 template<class t_payload_net_handler>
2858 bool node_server<t_payload_net_handler>::set_rate_down_limit(const boost::program_options::variables_map& vm, int64_t limit)
2859 {
2860 this->islimitdown=(limit != -1) && (limit != default_limit_down);
2861 if(limit==-1) {
2862 limit=default_limit_down;
2863 }
2864 epee::net_utils::connection<epee::levin::async_protocol_handler<p2p_connection_context> >::set_rate_down_limit( limit );
2865 MINFO("Set limit-down to " << limit << " kB/s");
2866 return true;
2867 }
2868
2869 template<class t_payload_net_handler>
2870 bool node_server<t_payload_net_handler>::set_rate_limit(const boost::program_options::variables_map& vm, int64_t limit)
2871 {
2872 int64_t limit_up = 0;
2873 int64_t limit_down = 0;
2874
2875 if(limit == -1)
2876 {
2877 limit_up = default_limit_up;
2878 limit_down = default_limit_down;
2879 }
2880 else
2881 {
2882 limit_up = limit;
2883 limit_down = limit;
2884 }
2885 if(!this->islimitup) {
2886 epee::net_utils::connection<epee::levin::async_protocol_handler<p2p_connection_context> >::set_rate_up_limit(limit_up);
2887 MINFO("Set limit-up to " << limit_up << " kB/s");
2888 }
2889 if(!this->islimitdown) {
2890 epee::net_utils::connection<epee::levin::async_protocol_handler<p2p_connection_context> >::set_rate_down_limit(limit_down);
2891 MINFO("Set limit-down to " << limit_down << " kB/s");
2892 }
2893
2894 return true;
2895 }
2896
2897 template<class t_payload_net_handler>
2898 bool node_server<t_payload_net_handler>::has_too_many_connections(const epee::net_utils::network_address &address)
2899 {
2900 if (address.get_zone() != epee::net_utils::zone::public_)
2901 return false; // Unable to determine how many connections from host
2902
2903 uint32_t count = 0;
2904
2905 m_network_zones.at(epee::net_utils::zone::public_).m_net_server.get_config_object().foreach_connection([&](const p2p_connection_context& cntxt)
2906 {
2907 if (cntxt.m_is_income && cntxt.m_remote_address.is_same_host(address)) {
2908 count++;
2909
2910 // the only call location happens BEFORE foreach_connection list is updated
2911 if (count >= max_connections) {
2912 return false;
2913 }
2914 }
2915
2916 return true;
2917 });
2918 // the only call location happens BEFORE foreach_connection list is updated
2919 return count >= max_connections;
2920 }
2921
2922 template<class t_payload_net_handler>
2923 bool node_server<t_payload_net_handler>::gray_peerlist_housekeeping()
2924 {
2925 if (m_offline) return true;
2926 if (!m_exclusive_peers.empty()) return true;
2927
2928 for (auto& zone : m_network_zones)
2929 {
2930 if (m_payload_handler.needs_new_sync_connections(zone.first))
2931 continue;
2932
2933 if (zone.second.m_net_server.is_stop_signal_sent())
2934 return false;
2935
2936 if (zone.second.m_connect == nullptr)
2937 continue;
2938
2939 peerlist_entry pe{};
2940 if (!zone.second.m_peerlist.get_random_gray_peer(pe))
2941 continue;
2942
2943 if (!check_connection_and_handshake_with_peer(pe.adr, pe.last_seen))
2944 {
2945 zone.second.m_peerlist.remove_from_peer_gray(pe);
2946 LOG_PRINT_L2("PEER EVICTED FROM GRAY PEER LIST: address: " << pe.adr.host_str() << " Peer ID: " << peerid_to_string(pe.id));
2947 }
2948 else
2949 {
2950 zone.second.m_peerlist.set_peer_just_seen(pe.id, pe.adr, pe.pruning_seed, pe.rpc_port, pe.rpc_credits_per_hash);
2951 LOG_PRINT_L2("PEER PROMOTED TO WHITE PEER LIST IP address: " << pe.adr.host_str() << " Peer ID: " << peerid_to_string(pe.id));
2952 }
2953 }
2954 return true;
2955 }
2956
2957 template<class t_payload_net_handler>
2958 void node_server<t_payload_net_handler>::add_used_stripe_peer(const typename t_payload_net_handler::connection_context &context)
2959 {
2960 const uint32_t stripe = tools::get_pruning_stripe(context.m_pruning_seed);
2961 if (stripe == 0 || stripe > (1ul << CRYPTONOTE_PRUNING_LOG_STRIPES))
2962 return;
2963 const uint32_t index = stripe - 1;
2964 CRITICAL_REGION_LOCAL(m_used_stripe_peers_mutex);
2965 MINFO("adding stripe " << stripe << " peer: " << context.m_remote_address.str());
2966 m_used_stripe_peers[index].erase(std::remove_if(m_used_stripe_peers[index].begin(), m_used_stripe_peers[index].end(),
2967 [&context](const epee::net_utils::network_address &na){ return context.m_remote_address == na; }), m_used_stripe_peers[index].end());
2968 m_used_stripe_peers[index].push_back(context.m_remote_address);
2969 }
2970
2971 template<class t_payload_net_handler>
2972 void node_server<t_payload_net_handler>::remove_used_stripe_peer(const typename t_payload_net_handler::connection_context &context)
2973 {
2974 const uint32_t stripe = tools::get_pruning_stripe(context.m_pruning_seed);
2975 if (stripe == 0 || stripe > (1ul << CRYPTONOTE_PRUNING_LOG_STRIPES))
2976 return;
2977 const uint32_t index = stripe - 1;
2978 CRITICAL_REGION_LOCAL(m_used_stripe_peers_mutex);
2979 MINFO("removing stripe " << stripe << " peer: " << context.m_remote_address.str());
2980 m_used_stripe_peers[index].erase(std::remove_if(m_used_stripe_peers[index].begin(), m_used_stripe_peers[index].end(),
2981 [&context](const epee::net_utils::network_address &na){ return context.m_remote_address == na; }), m_used_stripe_peers[index].end());
2982 }
2983
2984 template<class t_payload_net_handler>
2985 void node_server<t_payload_net_handler>::clear_used_stripe_peers()
2986 {
2987 CRITICAL_REGION_LOCAL(m_used_stripe_peers_mutex);
2988 MINFO("clearing used stripe peers");
2989 for (auto &e: m_used_stripe_peers)
2990 e.clear();
2991 }
2992
2993 template<class t_payload_net_handler>
2994 void node_server<t_payload_net_handler>::add_upnp_port_mapping_impl(uint32_t port, bool ipv6) // if ipv6 false, do ipv4
2995 {
2996 std::string ipversion = ipv6 ? "(IPv6)" : "(IPv4)";
2997 MDEBUG("Attempting to add IGD port mapping " << ipversion << ".");
2998 int result;
2999 const int ipv6_arg = ipv6 ? 1 : 0;
3000
3001 #if MINIUPNPC_API_VERSION > 13
3002 // default according to miniupnpc.h
3003 unsigned char ttl = 2;
3004 UPNPDev* deviceList = upnpDiscover(1000, NULL, NULL, 0, ipv6_arg, ttl, &result);
3005 #else
3006 UPNPDev* deviceList = upnpDiscover(1000, NULL, NULL, 0, ipv6_arg, &result);
3007 #endif
3008 UPNPUrls urls;
3009 IGDdatas igdData;
3010 char lanAddress[64];
3011 result = UPNP_GetValidIGD(deviceList, &urls, &igdData, lanAddress, sizeof lanAddress);
3012 freeUPNPDevlist(deviceList);
3013 if (result > 0) {
3014 if (result == 1) {
3015 std::ostringstream portString;
3016 portString << port;
3017
3018 // Delete the port mapping before we create it, just in case we have dangling port mapping from the daemon not being shut down correctly
3019 UPNP_DeletePortMapping(urls.controlURL, igdData.first.servicetype, portString.str().c_str(), "TCP", 0);
3020
3021 int portMappingResult;
3022 portMappingResult = UPNP_AddPortMapping(urls.controlURL, igdData.first.servicetype, portString.str().c_str(), portString.str().c_str(), lanAddress, CRYPTONOTE_NAME, "TCP", 0, "0");
3023 if (portMappingResult != 0) {
3024 LOG_ERROR("UPNP_AddPortMapping failed, error: " << strupnperror(portMappingResult));
3025 } else {
3026 MLOG_GREEN(el::Level::Info, "Added IGD port mapping.");
3027 }
3028 } else if (result == 2) {
3029 MWARNING("IGD was found but reported as not connected.");
3030 } else if (result == 3) {
3031 MWARNING("UPnP device was found but not recognized as IGD.");
3032 } else {
3033 MWARNING("UPNP_GetValidIGD returned an unknown result code.");
3034 }
3035
3036 FreeUPNPUrls(&urls);
3037 } else {
3038 MINFO("No IGD was found.");
3039 }
3040 }
3041
3042 template<class t_payload_net_handler>
3043 void node_server<t_payload_net_handler>::add_upnp_port_mapping_v4(uint32_t port)
3044 {
3045 add_upnp_port_mapping_impl(port, false);
3046 }
3047
3048 template<class t_payload_net_handler>
3049 void node_server<t_payload_net_handler>::add_upnp_port_mapping_v6(uint32_t port)
3050 {
3051 add_upnp_port_mapping_impl(port, true);
3052 }
3053
3054 template<class t_payload_net_handler>
3055 void node_server<t_payload_net_handler>::add_upnp_port_mapping(uint32_t port, bool ipv4, bool ipv6)
3056 {
3057 if (ipv4) add_upnp_port_mapping_v4(port);
3058 if (ipv6) add_upnp_port_mapping_v6(port);
3059 }
3060
3061
3062 template<class t_payload_net_handler>
3063 void node_server<t_payload_net_handler>::delete_upnp_port_mapping_impl(uint32_t port, bool ipv6)
3064 {
3065 std::string ipversion = ipv6 ? "(IPv6)" : "(IPv4)";
3066 MDEBUG("Attempting to delete IGD port mapping " << ipversion << ".");
3067 int result;
3068 const int ipv6_arg = ipv6 ? 1 : 0;
3069 #if MINIUPNPC_API_VERSION > 13
3070 // default according to miniupnpc.h
3071 unsigned char ttl = 2;
3072 UPNPDev* deviceList = upnpDiscover(1000, NULL, NULL, 0, ipv6_arg, ttl, &result);
3073 #else
3074 UPNPDev* deviceList = upnpDiscover(1000, NULL, NULL, 0, ipv6_arg, &result);
3075 #endif
3076 UPNPUrls urls;
3077 IGDdatas igdData;
3078 char lanAddress[64];
3079 result = UPNP_GetValidIGD(deviceList, &urls, &igdData, lanAddress, sizeof lanAddress);
3080 freeUPNPDevlist(deviceList);
3081 if (result > 0) {
3082 if (result == 1) {
3083 std::ostringstream portString;
3084 portString << port;
3085
3086 int portMappingResult;
3087 portMappingResult = UPNP_DeletePortMapping(urls.controlURL, igdData.first.servicetype, portString.str().c_str(), "TCP", 0);
3088 if (portMappingResult != 0) {
3089 LOG_ERROR("UPNP_DeletePortMapping failed, error: " << strupnperror(portMappingResult));
3090 } else {
3091 MLOG_GREEN(el::Level::Info, "Deleted IGD port mapping.");
3092 }
3093 } else if (result == 2) {
3094 MWARNING("IGD was found but reported as not connected.");
3095 } else if (result == 3) {
3096 MWARNING("UPnP device was found but not recognized as IGD.");
3097 } else {
3098 MWARNING("UPNP_GetValidIGD returned an unknown result code.");
3099 }
3100
3101 FreeUPNPUrls(&urls);
3102 } else {
3103 MINFO("No IGD was found.");
3104 }
3105 }
3106
3107 template<class t_payload_net_handler>
3108 void node_server<t_payload_net_handler>::delete_upnp_port_mapping_v4(uint32_t port)
3109 {
3110 delete_upnp_port_mapping_impl(port, false);
3111 }
3112
3113 template<class t_payload_net_handler>
3114 void node_server<t_payload_net_handler>::delete_upnp_port_mapping_v6(uint32_t port)
3115 {
3116 delete_upnp_port_mapping_impl(port, true);
3117 }
3118
3119 template<class t_payload_net_handler>
3120 void node_server<t_payload_net_handler>::delete_upnp_port_mapping(uint32_t port)
3121 {
3122 delete_upnp_port_mapping_v4(port);
3123 delete_upnp_port_mapping_v6(port);
3124 }
3125
3126 template<typename t_payload_net_handler>
3127 boost::optional<p2p_connection_context_t<typename t_payload_net_handler::connection_context>>
3128 node_server<t_payload_net_handler>::socks_connect(network_zone& zone, const epee::net_utils::network_address& remote, epee::net_utils::ssl_support_t ssl_support)
3129 {
3130 auto result = socks_connect_internal(zone.m_net_server.get_stop_signal(), zone.m_net_server.get_io_context(), zone.m_proxy_address, remote);
3131 if (result) // if no error
3132 {
3133 p2p_connection_context context{};
3134 if (zone.m_net_server.add_connection(context, std::move(*result), remote, ssl_support))
3135 return {std::move(context)};
3136 }
3137 return boost::none;
3138 }
3139
3140 template<typename t_payload_net_handler>
3141 boost::optional<p2p_connection_context_t<typename t_payload_net_handler::connection_context>>
3142 node_server<t_payload_net_handler>::public_connect(network_zone& zone, epee::net_utils::network_address const& na, epee::net_utils::ssl_support_t ssl_support)
3143 {
3144 bool is_ipv4 = na.get_type_id() == epee::net_utils::ipv4_network_address::get_type_id();
3145 bool is_ipv6 = na.get_type_id() == epee::net_utils::ipv6_network_address::get_type_id();
3146 CHECK_AND_ASSERT_MES(is_ipv4 || is_ipv6, boost::none,
3147 "Only IPv4 or IPv6 addresses are supported here");
3148
3149 std::string address;
3150 std::string port;
3151
3152 if (is_ipv4)
3153 {
3154 const epee::net_utils::ipv4_network_address &ipv4 = na.as<const epee::net_utils::ipv4_network_address>();
3155 address = epee::string_tools::get_ip_string_from_int32(ipv4.ip());
3156 port = epee::string_tools::num_to_string_fast(ipv4.port());
3157 }
3158 else if (is_ipv6)
3159 {
3160 const epee::net_utils::ipv6_network_address &ipv6 = na.as<const epee::net_utils::ipv6_network_address>();
3161 address = ipv6.ip().to_string();
3162 port = epee::string_tools::num_to_string_fast(ipv6.port());
3163 }
3164 else
3165 {
3166 LOG_ERROR("Only IPv4 or IPv6 addresses are supported here");
3167 return boost::none;
3168 }
3169
3170 typename net_server::t_connection_context con{};
3171 const bool res = zone.m_net_server.connect(address, port,
3172 zone.m_config.m_net_config.connection_timeout,
3173 con, "0.0.0.0", ssl_support);
3174
3175 if (res)
3176 return {std::move(con)};
3177 return boost::none;
3178 }
3179 }