Debian Codegraph @

src/p2p/net_node.cpp

raw symbols SCIP
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 #include <boost/algorithm/string/find_iterator.hpp>
32 #include <boost/algorithm/string/finder.hpp>
33 #include <boost/chrono/duration.hpp>
34 #include <boost/endian/conversion.hpp>
35 #include <boost/optional/optional.hpp>
36 #include <boost/thread/future.hpp>
37 #include <boost/utility/string_ref.hpp>
38 #include <chrono>
39 #include <utility>
40
41 #include "common/command_line.h"
42 #include "cryptonote_core/cryptonote_core.h"
43 #include "cryptonote_protocol/cryptonote_protocol_defs.h"
44 #include "net_node.h"
45 #include "net/net_utils_base.h"
46 #include "net/socks.h"
47 #include "net/parse.h"
48 #include "net/tor_address.h"
49 #include "net/i2p_address.h"
50 #include "p2p/p2p_protocol_defs.h"
51 #include "string_tools.h"
52
53 namespace
54 {
55 constexpr const boost::chrono::milliseconds future_poll_interval{500};
56 constexpr const std::chrono::seconds socks_connect_timeout{P2P_DEFAULT_SOCKS_CONNECT_TIMEOUT};
57
58 std::int64_t get_max_connections(const boost::iterator_range<boost::string_ref::const_iterator> value) noexcept
59 {
60 // -1 is default, 0 is error
61 if (value.empty())
62 return -1;
63
64 std::uint32_t out = 0;
65 if (epee::string_tools::get_xtype_from_string(out, std::string{value.begin(), value.end()}))
66 return out;
67 return 0;
68 }
69
70 template<typename T>
71 epee::net_utils::network_address get_address(const boost::string_ref value)
72 {
73 expect<T> address = T::make(value);
74 if (!address)
75 {
76 MERROR(
77 "Failed to parse " << epee::net_utils::zone_to_string(T::get_zone()) << " address \"" << value << "\": " << address.error().message()
78 );
79 return {};
80 }
81 return {std::move(*address)};
82 }
83
84 bool start_socks(std::shared_ptr<net::socks::client> client, const net::socks::endpoint& proxy, const epee::net_utils::network_address& remote)
85 {
86 CHECK_AND_ASSERT_MES(client != nullptr, false, "Unexpected null client");
87
88 bool set = false;
89 switch (remote.get_type_id())
90 {
91 case net::tor_address::get_type_id():
92 set = client->set_connect_command(remote.as<net::tor_address>(), std::addressof(proxy.userinfo));
93 break;
94 case net::i2p_address::get_type_id():
95 set = client->set_connect_command(remote.as<net::i2p_address>(), std::addressof(proxy.userinfo));
96 break;
97 case epee::net_utils::ipv4_network_address::get_type_id():
98 set = client->set_connect_command(remote.as<epee::net_utils::ipv4_network_address>(), std::addressof(proxy.userinfo));
99 break;
100 case epee::net_utils::ipv6_network_address::get_type_id():
101 if (client->socks_version() == net::socks::version::v5)
102 {
103 set = client->set_connect_command(remote.as<epee::net_utils::ipv6_network_address>(), std::addressof(proxy.userinfo));
104 break;
105 }
106 /* fallthrough */
107 default:
108 MERROR("Unsupported network address in socks_connect. Try socks5://");
109 return false;
110 }
111
112 const bool sent =
113 set && net::socks::client::connect_and_send(std::move(client), proxy.address);
114 CHECK_AND_ASSERT_MES(sent, false, "Unexpected failure to init socks client");
115 return true;
116 }
117 }
118
119 namespace nodetool
120 {
121 const command_line::arg_descriptor<std::string> arg_p2p_bind_ip = {"p2p-bind-ip", "Interface for p2p network protocol (IPv4)", "0.0.0.0"};
122 const command_line::arg_descriptor<std::string> arg_p2p_bind_ipv6_address = {"p2p-bind-ipv6-address", "Interface for p2p network protocol (IPv6)", "::"};
123 const command_line::arg_descriptor<std::string, false, true, 2> arg_p2p_bind_port = {
124 "p2p-bind-port"
125 , "Port for p2p network protocol (IPv4)"
126 , std::to_string(config::P2P_DEFAULT_PORT)
127 , {{ &cryptonote::arg_testnet_on, &cryptonote::arg_stagenet_on }}
128 , [](std::array<bool, 2> testnet_stagenet, bool defaulted, std::string val)->std::string {
129 if (testnet_stagenet[0] && defaulted)
130 return std::to_string(config::testnet::P2P_DEFAULT_PORT);
131 else if (testnet_stagenet[1] && defaulted)
132 return std::to_string(config::stagenet::P2P_DEFAULT_PORT);
133 return val;
134 }
135 };
136 const command_line::arg_descriptor<std::string, false, true, 2> arg_p2p_bind_port_ipv6 = {
137 "p2p-bind-port-ipv6"
138 , "Port for p2p network protocol (IPv6)"
139 , std::to_string(config::P2P_DEFAULT_PORT)
140 , {{ &cryptonote::arg_testnet_on, &cryptonote::arg_stagenet_on }}
141 , [](std::array<bool, 2> testnet_stagenet, bool defaulted, std::string val)->std::string {
142 if (testnet_stagenet[0] && defaulted)
143 return std::to_string(config::testnet::P2P_DEFAULT_PORT);
144 else if (testnet_stagenet[1] && defaulted)
145 return std::to_string(config::stagenet::P2P_DEFAULT_PORT);
146 return val;
147 }
148 };
149
150 const command_line::arg_descriptor<uint32_t> arg_p2p_external_port = {"p2p-external-port", "External port for p2p network protocol (if port forwarding used with NAT)", 0};
151 const command_line::arg_descriptor<bool> arg_p2p_allow_local_ip = {"allow-local-ip", "Allow local ip add to peer list, mostly in debug purposes"};
152 const command_line::arg_descriptor<std::vector<std::string> > arg_p2p_add_peer = {"add-peer", "Manually add peer to local peerlist"};
153 const command_line::arg_descriptor<std::vector<std::string> > arg_p2p_add_priority_node = {"add-priority-node", "Specify list of peers to connect to and attempt to keep the connection open"};
154 const command_line::arg_descriptor<std::vector<std::string> > arg_p2p_add_exclusive_node = {"add-exclusive-node", "Specify list of peers to connect to only."
155 " If this option is given the options add-priority-node and seed-node are ignored"};
156 const command_line::arg_descriptor<std::vector<std::string> > arg_p2p_seed_node = {"seed-node", "Connect to a node to retrieve peer addresses, and disconnect"};
157 const command_line::arg_descriptor<std::vector<std::string> > arg_tx_proxy = {"tx-proxy", "Send local txes through proxy: <network-type>,[socks5://[user:pass@]]<socks-ip:port>[,max_connections][,disable_noise] i.e. \"tor,127.0.0.1:9050,100,disable_noise\""};
158 const command_line::arg_descriptor<std::vector<std::string> > arg_anonymous_inbound = {"anonymous-inbound", "<hidden-service-address>,<[bind-ip:]port>[,max_connections] i.e. \"x.onion,127.0.0.1:18083,100\""};
159 const command_line::arg_descriptor<std::string> arg_ban_list = {"ban-list", "Specify ban list file, one IP address per line"};
160 const command_line::arg_descriptor<bool> arg_p2p_hide_my_port = {"hide-my-port", "Do not announce yourself as peerlist candidate", false, true};
161 const command_line::arg_descriptor<bool> arg_no_sync = {"no-sync", "Don't synchronize the blockchain with other peers", false};
162 const command_line::arg_descriptor<bool> arg_enable_dns_blocklist = {"enable-dns-blocklist", "Apply realtime blocklist from DNS", false};
163
164 const command_line::arg_descriptor<bool> arg_no_igd = {"no-igd", "Disable UPnP port mapping"};
165 const command_line::arg_descriptor<std::string> arg_igd = {"igd", "UPnP port mapping (disabled)", "disabled"};
166 const command_line::arg_descriptor<bool> arg_p2p_use_ipv6 = {"p2p-use-ipv6", "Enable IPv6 for p2p", false};
167 const command_line::arg_descriptor<bool> arg_p2p_ignore_ipv4 = {"p2p-ignore-ipv4", "Ignore unsuccessful IPv4 bind for p2p", false};
168 const command_line::arg_descriptor<int64_t> arg_out_peers = {"out-peers", "set max number of out peers", -1};
169 const command_line::arg_descriptor<int64_t> arg_in_peers = {"in-peers", "set max number of in peers", -1};
170 const command_line::arg_descriptor<int> arg_tos_flag = {"tos-flag", "set TOS flag", -1};
171
172 const command_line::arg_descriptor<int64_t> arg_limit_rate_up = {"limit-rate-up", "set limit-rate-up [kB/s]", P2P_DEFAULT_LIMIT_RATE_UP};
173 const command_line::arg_descriptor<int64_t> arg_limit_rate_down = {"limit-rate-down", "set limit-rate-down [kB/s]", P2P_DEFAULT_LIMIT_RATE_DOWN};
174 const command_line::arg_descriptor<int64_t> arg_limit_rate = {"limit-rate", "set limit-rate [kB/s]", -1};
175
176 const command_line::arg_descriptor<bool> arg_pad_transactions = {
177 "pad-transactions", "Pad relayed transactions to help defend against traffic volume analysis", false
178 };
179 const command_line::arg_descriptor<uint32_t> arg_max_connections_per_ip = {"max-connections-per-ip", "Maximum number of p2p connections allowed from the same IP address", 1};
180
181 boost::optional<std::vector<proxy>> get_proxies(boost::program_options::variables_map const& vm)
182 {
183 namespace ip = boost::asio::ip;
184
185 std::vector<proxy> proxies{};
186
187 const std::vector<std::string> args = command_line::get_arg(vm, arg_tx_proxy);
188 proxies.reserve(args.size());
189
190 for (const boost::string_ref arg : args)
191 {
192 proxies.emplace_back();
193
194 auto next = boost::algorithm::make_split_iterator(arg, boost::algorithm::first_finder(","));
195 CHECK_AND_ASSERT_MES(!next.eof() && !next->empty(), boost::none, "No network type for --" << arg_tx_proxy.name);
196 const boost::string_ref zone{next->begin(), next->size()};
197
198 ++next;
199 CHECK_AND_ASSERT_MES(!next.eof() && !next->empty(), boost::none, "No ip:port given for --" << arg_tx_proxy.name);
200 const boost::string_ref proxy{next->begin(), next->size()};
201
202 ++next;
203 for (unsigned count = 0; !next.eof(); ++count, ++next)
204 {
205 if (2 <= count)
206 {
207 MERROR("Too many ',' characters given to --" << arg_tx_proxy.name);
208 return boost::none;
209 }
210
211 if (boost::string_ref{next->begin(), next->size()} == "disable_noise")
212 proxies.back().noise = false;
213 else
214 {
215 proxies.back().max_connections = get_max_connections(*next);
216 if (proxies.back().max_connections == 0)
217 {
218 MERROR("Invalid max connections given to --" << arg_tx_proxy.name);
219 return boost::none;
220 }
221 }
222 }
223
224 switch (epee::net_utils::zone_from_string(zone))
225 {
226 case epee::net_utils::zone::tor:
227 proxies.back().zone = epee::net_utils::zone::tor;
228 break;
229 case epee::net_utils::zone::i2p:
230 proxies.back().zone = epee::net_utils::zone::i2p;
231 break;
232 default:
233 MERROR("Invalid network for --" << arg_tx_proxy.name);
234 return boost::none;
235 }
236
237 auto endpoint = net::socks::endpoint::get(proxy);
238 if (!endpoint)
239 {
240 MERROR("Invalid --" << arg_tx_proxy.name << " value: " << endpoint.error().message());
241 return boost::none;
242 }
243
244 proxies.back().address = std::move(*endpoint);
245 }
246
247 return proxies;
248 }
249
250 boost::optional<std::vector<anonymous_inbound>> get_anonymous_inbounds(boost::program_options::variables_map const& vm)
251 {
252 std::vector<anonymous_inbound> inbounds{};
253
254 const std::vector<std::string> args = command_line::get_arg(vm, arg_anonymous_inbound);
255 inbounds.reserve(args.size());
256
257 for (const boost::string_ref arg : args)
258 {
259 inbounds.emplace_back();
260
261 auto next = boost::algorithm::make_split_iterator(arg, boost::algorithm::first_finder(","));
262 CHECK_AND_ASSERT_MES(!next.eof() && !next->empty(), boost::none, "No inbound address for --" << arg_anonymous_inbound.name);
263 const boost::string_ref address{next->begin(), next->size()};
264
265 ++next;
266 CHECK_AND_ASSERT_MES(!next.eof() && !next->empty(), boost::none, "No local ipv4:port given for --" << arg_anonymous_inbound.name);
267 const boost::string_ref bind{next->begin(), next->size()};
268
269 const std::size_t colon = bind.find_first_of(':');
270 CHECK_AND_ASSERT_MES(colon < bind.size(), boost::none, "No local port given for --" << arg_anonymous_inbound.name);
271
272 ++next;
273 if (!next.eof())
274 {
275 inbounds.back().max_connections = get_max_connections(*next);
276 if (inbounds.back().max_connections == 0)
277 {
278 MERROR("Invalid max connections given to --" << arg_tx_proxy.name);
279 return boost::none;
280 }
281 }
282
283 expect<epee::net_utils::network_address> our_address = net::get_network_address(address, 0);
284 switch (our_address ? our_address->get_type_id() : epee::net_utils::address_type::invalid)
285 {
286 case net::tor_address::get_type_id():
287 inbounds.back().our_address = std::move(*our_address);
288 inbounds.back().default_remote = net::tor_address::unknown();
289 break;
290 case net::i2p_address::get_type_id():
291 inbounds.back().our_address = std::move(*our_address);
292 inbounds.back().default_remote = net::i2p_address::unknown();
293 break;
294 default:
295 MERROR("Invalid inbound address (" << address << ") for --" << arg_anonymous_inbound.name << ": " << (our_address ? "invalid type" : our_address.error().message()));
296 return boost::none;
297 }
298
299 // get_address returns default constructed address on error
300 if (inbounds.back().our_address == epee::net_utils::network_address{})
301 return boost::none;
302
303 std::uint32_t ip = 0;
304 std::uint16_t port = 0;
305 if (!epee::string_tools::parse_peer_from_string(ip, port, std::string{bind}))
306 {
307 MERROR("Invalid ipv4:port given for --" << arg_anonymous_inbound.name);
308 return boost::none;
309 }
310 inbounds.back().local_ip = std::string{bind.substr(0, colon)};
311 inbounds.back().local_port = std::string{bind.substr(colon + 1)};
312 }
313
314 return inbounds;
315 }
316
317 bool is_filtered_command(const epee::net_utils::network_address& address, int command)
318 {
319 switch (command)
320 {
321 case nodetool::COMMAND_HANDSHAKE_T<cryptonote::CORE_SYNC_DATA>::ID:
322 case nodetool::COMMAND_TIMED_SYNC_T<cryptonote::CORE_SYNC_DATA>::ID:
323 case cryptonote::NOTIFY_NEW_TRANSACTIONS::ID:
324 return false;
325 default:
326 break;
327 }
328
329 if (address.get_zone() == epee::net_utils::zone::public_)
330 return false;
331
332 MWARNING("Filtered command (#" << command << ") to/from " << address.str());
333 return true;
334 }
335
336 boost::optional<boost::asio::ip::tcp::socket>
337 socks_connect_internal(const std::atomic<bool>& stop_signal, boost::asio::io_context& service, const net::socks::endpoint& proxy, const epee::net_utils::network_address& remote)
338 {
339 using socket_type = net::socks::client::stream_type::socket;
340 using client_result = std::pair<boost::system::error_code, socket_type>;
341
342 struct notify
343 {
344 boost::promise<client_result> socks_promise;
345
346 void operator()(boost::system::error_code error, socket_type&& sock)
347 {
348 socks_promise.set_value(std::make_pair(error, std::move(sock)));
349 }
350 };
351
352 net::socks::client::close_on_exit close_client{};
353 boost::unique_future<client_result> socks_result{};
354 {
355 boost::promise<client_result> socks_promise{};
356 socks_result = socks_promise.get_future();
357
358 auto client = net::socks::make_connect_client(
359 boost::asio::ip::tcp::socket{service}, proxy.ver, notify{std::move(socks_promise)}
360 );
361 close_client.self = client;
362 if (!start_socks(std::move(client), proxy, remote))
363 return boost::none;
364 }
365
366 const auto start = std::chrono::steady_clock::now();
367 while (socks_result.wait_for(future_poll_interval) == boost::future_status::timeout)
368 {
369 if (socks_connect_timeout < std::chrono::steady_clock::now() - start)
370 {
371 MERROR("Timeout on socks connect (" << proxy.address << " to " << remote.str() << ")");
372 return boost::none;
373 }
374
375 if (stop_signal)
376 return boost::none;
377 }
378
379 try
380 {
381 auto result = socks_result.get();
382 if (!result.first)
383 {
384 close_client.self.reset();
385 return {std::move(result.second)};
386 }
387
388 MERROR("Failed to make socks connection to " << remote.str() << " (via " << proxy.address << "): " << result.first.message());
389 }
390 catch (boost::broken_promise const&)
391 {}
392
393 return boost::none;
394 }
395 }