Skip to content

Commit

Permalink
Get SOCKS5 port from Tor daemon
Browse files Browse the repository at this point in the history
We don't know the SOCKS5 port when we're using to a running Tor daemon.
This change is needed to support external Tor instances.

Ref: bisq-network#1894
  • Loading branch information
alvasw committed Apr 26, 2024
1 parent b6d2c15 commit fbc95ac
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
8 changes: 2 additions & 6 deletions network/tor/tor/src/main/java/bisq/tor/TorService.java
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ public class TorService implements Service {
private final AtomicBoolean isRunning = new AtomicBoolean();

private Optional<NativeTorProcess> torProcess = Optional.empty();
private Optional<Integer> socksPort = Optional.empty();
private Optional<TorSocksProxyFactory> torSocksProxyFactory = Optional.empty();

public TorService(TorTransportConfig transportConfig) {
Expand Down Expand Up @@ -92,7 +91,7 @@ public CompletableFuture<Boolean> initialize() {
nativeTorController.enableTorNetworking();
nativeTorController.waitUntilBootstrapped();

int port = socksPort.orElseThrow();
int port = nativeTorController.getSocksPort().orElseThrow();
torSocksProxyFactory = Optional.of(new TorSocksProxyFactory(port));
})
.thenApply(unused -> true);
Expand Down Expand Up @@ -153,13 +152,10 @@ private void installTorIfNotUpToDate() {
}

private void createTorrcConfigFile(Path dataDir, PasswordDigest hashedControlPassword) {
int socksPort = NetworkUtils.findFreeSystemPort();
this.socksPort = Optional.of(socksPort);

TorrcClientConfigFactory torrcClientConfigFactory = TorrcClientConfigFactory.builder()
.isTestNetwork(transportConfig.isTestNetwork())
.dataDir(dataDir)
.socksPort(socksPort)
.socksPort(NetworkUtils.findFreeSystemPort())
.hashedControlPassword(hashedControlPassword)
.build();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,30 @@ public boolean isHiddenServiceAvailable(String onionUrl) {
}
}

public Optional<Integer> getSocksPort() {
try {
TorControlConnection controlConnection = torControlConnection.orElseThrow();
String socksListenersString = controlConnection.getInfo("net/listeners/socks");

String socksListener;
if (socksListenersString.contains(" ")) {
String[] socksPorts = socksListenersString.split(" ");
socksListener = socksPorts[0];
} else {
socksListener = socksListenersString;
}

// "127.0.0.1:12345"
socksListener = socksListener.replace("\"", "");
String portString = socksListener.split(":")[1];

int port = Integer.parseInt(portString);
return Optional.of(port);
} catch (IOException e) {
return Optional.empty();
}
}

public void waitUntilBootstrapped() {
try {
while (true) {
Expand Down

0 comments on commit fbc95ac

Please sign in to comment.