Skip to content

Commit ca5781e

Browse files
committed
config: allow setting -proxy per network
`-proxy=addr:port` specifies the proxy for all networks (except I2P). Previously only the Tor proxy could have been specified separately via `-onion=addr:port`. Make it possible to specify separately the proxy for IPv4, IPv6, Tor and CJDNS by e.g. `-proxy=addr:port=ipv6`. Or remove the proxy for a given network, e.g. `-proxy=0=cjdns`. Resolves: bitcoin/bitcoin#24450
1 parent baa848b commit ca5781e

File tree

4 files changed

+136
-44
lines changed

4 files changed

+136
-44
lines changed

src/init.cpp

Lines changed: 94 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -552,11 +552,26 @@ void SetupServerArgs(ArgsManager& argsman, bool can_listen_ipc)
552552
argsman.AddArg("-peerblockfilters", strprintf("Serve compact block filters to peers per BIP 157 (default: %u)", DEFAULT_PEERBLOCKFILTERS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
553553
argsman.AddArg("-txreconciliation", strprintf("Enable transaction reconciliations per BIP 330 (default: %d)", DEFAULT_TXRECONCILIATION_ENABLE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CONNECTION);
554554
argsman.AddArg("-port=<port>", strprintf("Listen for connections on <port> (default: %u, testnet3: %u, testnet4: %u, signet: %u, regtest: %u). Not relevant for I2P (see doc/i2p.md). If set to a value x, the default onion listening port will be set to x+1.", defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort(), testnet4ChainParams->GetDefaultPort(), signetChainParams->GetDefaultPort(), regtestChainParams->GetDefaultPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
555+
const std::string proxy_doc_for_value =
555556
#ifdef HAVE_SOCKADDR_UN
556-
argsman.AddArg("-proxy=<ip:port|path>", "Connect through SOCKS5 proxy, set -noproxy to disable (default: disabled). May be a local file path prefixed with 'unix:' if the proxy supports it.", ArgsManager::ALLOW_ANY | ArgsManager::DISALLOW_ELISION, OptionsCategory::CONNECTION);
557+
"<ip>[:<port>]|unix:<path>";
557558
#else
558-
argsman.AddArg("-proxy=<ip:port>", "Connect through SOCKS5 proxy, set -noproxy to disable (default: disabled)", ArgsManager::ALLOW_ANY | ArgsManager::DISALLOW_ELISION, OptionsCategory::CONNECTION);
559+
"<ip>[:<port>]";
559560
#endif
561+
const std::string proxy_doc_for_unix_socket =
562+
#ifdef HAVE_SOCKADDR_UN
563+
"May be a local file path prefixed with 'unix:' if the proxy supports it. ";
564+
#else
565+
"";
566+
#endif
567+
argsman.AddArg("-proxy=" + proxy_doc_for_value + "[=<network>]",
568+
"Connect through SOCKS5 proxy, set -noproxy to disable. " +
569+
proxy_doc_for_unix_socket +
570+
"Could end in =network to set the proxy only for that network. " +
571+
"The network can be any of ipv4, ipv6, tor or cjdns. " +
572+
"(default: disabled)",
573+
ArgsManager::ALLOW_ANY | ArgsManager::DISALLOW_ELISION,
574+
OptionsCategory::CONNECTION);
560575
argsman.AddArg("-proxyrandomize", strprintf("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)", DEFAULT_PROXYRANDOMIZE), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
561576
argsman.AddArg("-seednode=<ip>", "Connect to a node to retrieve peer addresses, and disconnect. This option can be specified multiple times to connect to multiple nodes. During startup, seednodes will be tried before dnsseeds.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
562577
argsman.AddArg("-networkactive", "Enable all P2P network activity (default: 1). Can be changed by the setnetworkactive RPC command", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
@@ -1189,31 +1204,34 @@ bool CheckHostPortOptions(const ArgsManager& args) {
11891204
}
11901205
}
11911206

1192-
for ([[maybe_unused]] const auto& [arg, unix] : std::vector<std::pair<std::string, bool>>{
1193-
// arg name UNIX socket support
1194-
{"-i2psam", false},
1195-
{"-onion", true},
1196-
{"-proxy", true},
1197-
{"-rpcbind", false},
1198-
{"-torcontrol", false},
1199-
{"-whitebind", false},
1200-
{"-zmqpubhashblock", true},
1201-
{"-zmqpubhashtx", true},
1202-
{"-zmqpubrawblock", true},
1203-
{"-zmqpubrawtx", true},
1204-
{"-zmqpubsequence", true},
1207+
for ([[maybe_unused]] const auto& [param_name, unix, suffix_allowed] : std::vector<std::tuple<std::string, bool, bool>>{
1208+
// arg name UNIX socket support =suffix allowed
1209+
{"-i2psam", false, false},
1210+
{"-onion", true, false},
1211+
{"-proxy", true, true},
1212+
{"-bind", false, true},
1213+
{"-rpcbind", false, false},
1214+
{"-torcontrol", false, false},
1215+
{"-whitebind", false, false},
1216+
{"-zmqpubhashblock", true, false},
1217+
{"-zmqpubhashtx", true, false},
1218+
{"-zmqpubrawblock", true, false},
1219+
{"-zmqpubrawtx", true, false},
1220+
{"-zmqpubsequence", true, false},
12051221
}) {
1206-
for (const std::string& socket_addr : args.GetArgs(arg)) {
1222+
for (const std::string& param_value : args.GetArgs(param_name)) {
1223+
const std::string param_value_hostport{
1224+
suffix_allowed ? param_value.substr(0, param_value.rfind('=')) : param_value};
12071225
std::string host_out;
12081226
uint16_t port_out{0};
1209-
if (!SplitHostPort(socket_addr, port_out, host_out)) {
1227+
if (!SplitHostPort(param_value_hostport, port_out, host_out)) {
12101228
#ifdef HAVE_SOCKADDR_UN
12111229
// Allow unix domain sockets for some options e.g. unix:/some/file/path
1212-
if (!unix || !socket_addr.starts_with(ADDR_PREFIX_UNIX)) {
1213-
return InitError(InvalidPortErrMsg(arg, socket_addr));
1230+
if (!unix || !param_value.starts_with(ADDR_PREFIX_UNIX)) {
1231+
return InitError(InvalidPortErrMsg(param_name, param_value));
12141232
}
12151233
#else
1216-
return InitError(InvalidPortErrMsg(arg, socket_addr));
1234+
return InitError(InvalidPortErrMsg(param_name, param_value));
12171235
#endif
12181236
}
12191237
}
@@ -1569,33 +1587,66 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
15691587
// Check for host lookup allowed before parsing any network related parameters
15701588
fNameLookup = args.GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
15711589

1572-
Proxy onion_proxy;
1573-
15741590
bool proxyRandomize = args.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
1575-
// -proxy sets a proxy for all outgoing network traffic
1576-
// -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
1577-
std::string proxyArg = args.GetArg("-proxy", "");
1578-
if (proxyArg != "" && proxyArg != "0") {
1579-
Proxy addrProxy;
1580-
if (IsUnixSocketPath(proxyArg)) {
1581-
addrProxy = Proxy(proxyArg, /*tor_stream_isolation=*/proxyRandomize);
1582-
} else {
1583-
const std::optional<CService> proxyAddr{Lookup(proxyArg, 9050, fNameLookup)};
1584-
if (!proxyAddr.has_value()) {
1585-
return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1591+
// -proxy sets a proxy for outgoing network traffic, possibly per network.
1592+
// -noproxy, -proxy=0 or -proxy="" can be used to remove the proxy setting, this is the default
1593+
Proxy ipv4_proxy;
1594+
Proxy ipv6_proxy;
1595+
Proxy onion_proxy;
1596+
Proxy name_proxy;
1597+
Proxy cjdns_proxy;
1598+
for (const std::string& param_value : args.GetArgs("-proxy")) {
1599+
const auto eq_pos{param_value.rfind('=')};
1600+
const std::string proxy_str{param_value.substr(0, eq_pos)}; // e.g. 127.0.0.1:9050=ipv4 -> 127.0.0.1:9050
1601+
std::string net_str;
1602+
if (eq_pos != std::string::npos) {
1603+
if (eq_pos + 1 == param_value.length()) {
1604+
return InitError(strprintf(_("Invalid -proxy address or hostname, ends with '=': '%s'"), param_value));
15861605
}
1587-
1588-
addrProxy = Proxy(proxyAddr.value(), /*tor_stream_isolation=*/proxyRandomize);
1606+
net_str = ToLower(param_value.substr(eq_pos + 1)); // e.g. 127.0.0.1:9050=ipv4 -> ipv4
15891607
}
15901608

1591-
if (!addrProxy.IsValid())
1592-
return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg));
1609+
Proxy proxy;
1610+
if (!proxy_str.empty() && proxy_str != "0") {
1611+
if (IsUnixSocketPath(proxy_str)) {
1612+
proxy = Proxy{proxy_str, /*tor_stream_isolation=*/proxyRandomize};
1613+
} else {
1614+
const std::optional<CService> addr{Lookup(proxy_str, DEFAULT_TOR_SOCKS_PORT, fNameLookup)};
1615+
if (!addr.has_value()) {
1616+
return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxy_str));
1617+
}
1618+
proxy = Proxy{addr.value(), /*tor_stream_isolation=*/proxyRandomize};
1619+
}
1620+
if (!proxy.IsValid()) {
1621+
return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxy_str));
1622+
}
1623+
}
15931624

1594-
SetProxy(NET_IPV4, addrProxy);
1595-
SetProxy(NET_IPV6, addrProxy);
1596-
SetProxy(NET_CJDNS, addrProxy);
1597-
SetNameProxy(addrProxy);
1598-
onion_proxy = addrProxy;
1625+
if (net_str.empty()) { // For all networks.
1626+
ipv4_proxy = ipv6_proxy = name_proxy = cjdns_proxy = onion_proxy = proxy;
1627+
} else if (net_str == "ipv4") {
1628+
ipv4_proxy = name_proxy = proxy;
1629+
} else if (net_str == "ipv6") {
1630+
ipv6_proxy = name_proxy = proxy;
1631+
} else if (net_str == "tor" || net_str == "onion") {
1632+
onion_proxy = proxy;
1633+
} else if (net_str == "cjdns") {
1634+
cjdns_proxy = proxy;
1635+
} else {
1636+
return InitError(strprintf(_("Unrecognized network in -proxy='%s': '%s'"), param_value, net_str));
1637+
}
1638+
}
1639+
if (ipv4_proxy.IsValid()) {
1640+
SetProxy(NET_IPV4, ipv4_proxy);
1641+
}
1642+
if (ipv6_proxy.IsValid()) {
1643+
SetProxy(NET_IPV6, ipv6_proxy);
1644+
}
1645+
if (name_proxy.IsValid()) {
1646+
SetNameProxy(name_proxy);
1647+
}
1648+
if (cjdns_proxy.IsValid()) {
1649+
SetProxy(NET_CJDNS, cjdns_proxy);
15991650
}
16001651

16011652
const bool onlynet_used_with_onion{!onlynets.empty() && g_reachable_nets.Contains(NET_ONION)};
@@ -1616,7 +1667,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
16161667
if (IsUnixSocketPath(onionArg)) {
16171668
onion_proxy = Proxy(onionArg, /*tor_stream_isolation=*/proxyRandomize);
16181669
} else {
1619-
const std::optional<CService> addr{Lookup(onionArg, 9050, fNameLookup)};
1670+
const std::optional<CService> addr{Lookup(onionArg, DEFAULT_TOR_SOCKS_PORT, fNameLookup)};
16201671
if (!addr.has_value() || !addr->IsValid()) {
16211672
return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
16221673
}

src/torcontrol.cpp

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,6 @@ static const float RECONNECT_TIMEOUT_MAX = 600.0;
7171
* this is belt-and-suspenders sanity limit to prevent memory exhaustion.
7272
*/
7373
static const int MAX_LINE_LENGTH = 100000;
74-
static const uint16_t DEFAULT_TOR_SOCKS_PORT = 9050;
7574

7675
/****** Low-level TorControlConnection ********/
7776

src/torcontrol.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
#include <string>
2020
#include <vector>
2121

22+
constexpr uint16_t DEFAULT_TOR_SOCKS_PORT{9050};
2223
constexpr int DEFAULT_TOR_CONTROL_PORT = 9051;
2324
extern const std::string DEFAULT_TOR_CONTROL;
2425
static const bool DEFAULT_LISTEN_ONION = true;

test/functional/feature_proxy.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -444,6 +444,47 @@ def networks_dict(d):
444444
msg = "Error: Unknown network specified in -onlynet: 'abc'"
445445
self.nodes[1].assert_start_raises_init_error(expected_msg=msg)
446446

447+
self.log.info("Test passing trailing '=' raises expected init error")
448+
self.nodes[1].extra_args = ["-proxy=127.0.0.1:9050="]
449+
msg = "Error: Invalid -proxy address or hostname, ends with '=': '127.0.0.1:9050='"
450+
self.nodes[1].assert_start_raises_init_error(expected_msg=msg)
451+
452+
self.log.info("Test passing unrecognized network raises expected init error")
453+
self.nodes[1].extra_args = ["-proxy=127.0.0.1:9050=foo"]
454+
msg = "Error: Unrecognized network in -proxy='127.0.0.1:9050=foo': 'foo'"
455+
self.nodes[1].assert_start_raises_init_error(expected_msg=msg)
456+
457+
self.log.info("Test passing proxy only for IPv6")
458+
self.start_node(1, extra_args=["-proxy=127.6.6.6:6666=ipv6"])
459+
nets = networks_dict(self.nodes[1].getnetworkinfo())
460+
assert_equal(nets["ipv4"]["proxy"], "")
461+
assert_equal(nets["ipv6"]["proxy"], "127.6.6.6:6666")
462+
self.stop_node(1)
463+
464+
self.log.info("Test passing separate proxy for IPv4 and IPv6")
465+
self.start_node(1, extra_args=["-proxy=127.4.4.4:4444=ipv4", "-proxy=127.6.6.6:6666=ipv6"])
466+
nets = networks_dict(self.nodes[1].getnetworkinfo())
467+
assert_equal(nets["ipv4"]["proxy"], "127.4.4.4:4444")
468+
assert_equal(nets["ipv6"]["proxy"], "127.6.6.6:6666")
469+
self.stop_node(1)
470+
471+
self.log.info("Test overriding the Tor proxy")
472+
self.start_node(1, extra_args=["-proxy=127.1.1.1:1111", "-proxy=127.2.2.2:2222=tor"])
473+
nets = networks_dict(self.nodes[1].getnetworkinfo())
474+
assert_equal(nets["ipv4"]["proxy"], "127.1.1.1:1111")
475+
assert_equal(nets["ipv6"]["proxy"], "127.1.1.1:1111")
476+
assert_equal(nets["onion"]["proxy"], "127.2.2.2:2222")
477+
self.stop_node(1)
478+
479+
self.log.info("Test removing CJDNS proxy")
480+
self.start_node(1, extra_args=["-proxy=127.1.1.1:1111", "-proxy=0=cjdns"])
481+
nets = networks_dict(self.nodes[1].getnetworkinfo())
482+
assert_equal(nets["ipv4"]["proxy"], "127.1.1.1:1111")
483+
assert_equal(nets["ipv6"]["proxy"], "127.1.1.1:1111")
484+
assert_equal(nets["onion"]["proxy"], "127.1.1.1:1111")
485+
assert_equal(nets["cjdns"]["proxy"], "")
486+
self.stop_node(1)
487+
447488
self.log.info("Test passing too-long unix path to -proxy raises init error")
448489
self.nodes[1].extra_args = [f"-proxy=unix:{'x' * 1000}"]
449490
if self.have_unix_sockets:

0 commit comments

Comments
 (0)