Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TorController: Make TorControlProtocol field final #2282

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,42 +4,56 @@
import bisq.security.keys.TorKeyPair;
import bisq.tor.controller.events.listener.BootstrapEventListener;
import bisq.tor.controller.events.listener.HsDescEventListener;
import bisq.tor.controller.exceptions.CannotConnectWithTorException;
import bisq.tor.controller.exceptions.CannotSendCommandToTorException;
import net.freehaven.tor.control.PasswordDigest;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class TorControlProtocol implements AutoCloseable {
private final Socket controlSocket;
private final WhonixTorControlReader whonixTorControlReader;
private final OutputStream outputStream;
private Optional<OutputStream> outputStream = Optional.empty();

// MidReplyLine = StatusCode "-" ReplyLine
// DataReplyLine = StatusCode "+" ReplyLine CmdData
private final Pattern multiLineReplyPattern = Pattern.compile("^\\d+[-+].+");

public TorControlProtocol(int port) throws IOException {
controlSocket = new Socket("127.0.0.1", port);
whonixTorControlReader = new WhonixTorControlReader(controlSocket.getInputStream());
outputStream = controlSocket.getOutputStream();
public TorControlProtocol() {
controlSocket = new Socket();
whonixTorControlReader = new WhonixTorControlReader();
}

@Override
public void close() throws IOException {
controlSocket.close();
public void initialize(int port) {
try {
var socketAddress = new InetSocketAddress("127.0.0.1", port);
controlSocket.connect(socketAddress);
whonixTorControlReader.start(controlSocket.getInputStream());
outputStream = Optional.of(controlSocket.getOutputStream());
} catch (IOException e) {
throw new CannotConnectWithTorException(e);
}
}

public void initialize() {
whonixTorControlReader.start();
@Override
public void close() {
try {
controlSocket.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}

public void authenticate(PasswordDigest passwordDigest) throws IOException {
public void authenticate(PasswordDigest passwordDigest) {
byte[] secret = passwordDigest.getSecret();
String secretHex = Hex.encode(secret);
String command = "AUTHENTICATE " + secretHex + "\r\n";
Expand All @@ -56,7 +70,7 @@ public void authenticate(PasswordDigest passwordDigest) throws IOException {
}
}

public void addOnion(TorKeyPair torKeyPair, int onionPort, int localPort) throws IOException {
public void addOnion(TorKeyPair torKeyPair, int onionPort, int localPort) {
String base64SecretScalar = torKeyPair.getBase64SecretScalar();
String command = "ADD_ONION " + "ED25519-V3:" + base64SecretScalar + " Port=" + onionPort + "," + localPort + "\r\n";

Expand All @@ -65,14 +79,14 @@ public void addOnion(TorKeyPair torKeyPair, int onionPort, int localPort) throws
assertTwoLineOkReply(replyStream, "ADD_ONION");
}

public String getInfo(String keyword) throws IOException {
public String getInfo(String keyword) {
String command = "GETINFO " + keyword + "\r\n";
sendCommand(command);
Stream<String> replyStream = receiveReply();
return assertTwoLineOkReply(replyStream, "GETINFO");
}

public void hsFetch(String hsAddress) throws IOException {
public void hsFetch(String hsAddress) {
String command = "HSFETCH " + hsAddress + "\r\n";
sendCommand(command);
String reply = receiveReply().findFirst().orElseThrow();
Expand All @@ -81,7 +95,7 @@ public void hsFetch(String hsAddress) throws IOException {
}
}

public void resetConf(String configName) throws IOException {
public void resetConf(String configName) {
String command = "RESETCONF " + configName + "\r\n";
sendCommand(command);
String reply = receiveReply().findFirst().orElseThrow();
Expand All @@ -90,7 +104,7 @@ public void resetConf(String configName) throws IOException {
}
}

public void setConfig(String configName, String configValue) throws IOException {
public void setConfig(String configName, String configValue) {
String command = "SETCONF " + configName + "=" + configValue + "\r\n";
sendCommand(command);
String reply = receiveReply().findFirst().orElseThrow();
Expand All @@ -99,7 +113,7 @@ public void setConfig(String configName, String configValue) throws IOException
}
}

public void setEvents(List<String> events) throws IOException {
public void setEvents(List<String> events) {
var stringBuilder = new StringBuffer("SETEVENTS");
events.forEach(event -> stringBuilder.append(" ").append(event));
stringBuilder.append("\r\n");
Expand All @@ -112,7 +126,7 @@ public void setEvents(List<String> events) throws IOException {
}
}

public void takeOwnership() throws IOException {
public void takeOwnership() {
String command = "TAKEOWNERSHIP\r\n";
sendCommand(command);
String reply = receiveReply().findFirst().orElseThrow();
Expand All @@ -137,10 +151,15 @@ public void removeHsDescEventListener(HsDescEventListener listener) {
whonixTorControlReader.removeHsDescEventListener(listener);
}

private void sendCommand(String command) throws IOException {
byte[] commandBytes = command.getBytes(StandardCharsets.US_ASCII);
outputStream.write(commandBytes);
outputStream.flush();
private void sendCommand(String command) {
try {
@SuppressWarnings("resource") OutputStream outputStream = this.outputStream.orElseThrow();
byte[] commandBytes = command.getBytes(StandardCharsets.US_ASCII);
outputStream.write(commandBytes);
outputStream.flush();
} catch (IOException e) {
throw new CannotSendCommandToTorException(e);
}
}

private Stream<String> receiveReply() {
Expand Down
105 changes: 33 additions & 72 deletions network/tor/tor/src/main/java/bisq/tor/controller/TorController.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,21 @@
import lombok.extern.slf4j.Slf4j;
import net.freehaven.tor.control.PasswordDigest;

import java.io.IOException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@Slf4j
public class TorController implements BootstrapEventListener, HsDescEventListener {
private final TorControlProtocol torControlProtocol = new TorControlProtocol();

private final int bootstrapTimeout; // in ms
private final int hsUploadTimeout; // in ms
private final CountDownLatch isBootstrappedCountdownLatch = new CountDownLatch(1);
Expand All @@ -36,66 +40,52 @@ public class TorController implements BootstrapEventListener, HsDescEventListene
private final Map<String, CompletableFuture<Boolean>> pendingIsOnionServiceOnlineLookupFutureMap =
new ConcurrentHashMap<>();

private Optional<TorControlProtocol> torControlProtocol = Optional.empty();

public TorController(int bootstrapTimeout, int hsUploadTimeout) {
this.bootstrapTimeout = bootstrapTimeout;
this.hsUploadTimeout = hsUploadTimeout;
}

public void initialize(int controlPort) throws IOException {
public void initialize(int controlPort) {
initialize(controlPort, Optional.empty());
}

public void initialize(int controlPort, PasswordDigest hashedControlPassword) throws IOException {
public void initialize(int controlPort, PasswordDigest hashedControlPassword) {
initialize(controlPort, Optional.of(hashedControlPassword));
}

public void shutdown() {
torControlProtocol.ifPresent(torControlProtocol -> {
try {
torControlProtocol.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
});
torControlProtocol.close();
}

public void bootstrapTor() throws IOException {
public void bootstrapTor() {
bindToBisq();
subscribeToBootstrapEvents();
enableNetworking();
waitUntilBootstrapped();
}

public CompletableFuture<Boolean> isOnionServiceOnline(String onionAddress) throws IOException, ExecutionException, InterruptedException, TimeoutException {
public CompletableFuture<Boolean> isOnionServiceOnline(String onionAddress) {
var onionServiceLookupCompletableFuture = new CompletableFuture<Boolean>();
pendingIsOnionServiceOnlineLookupFutureMap.put(onionAddress, onionServiceLookupCompletableFuture);
subscribeToHsDescEvents();

TorControlProtocol torControlProtocol = getTorControlProtocol();
String serviceId = onionAddress.replace(".onion", "");
torControlProtocol.hsFetch(serviceId);

onionServiceLookupCompletableFuture.thenRun(() -> {
torControlProtocol.removeHsDescEventListener(this);
try {
torControlProtocol.setEvents(Collections.emptyList());
} catch (IOException e) {
throw new RuntimeException(e);
}
torControlProtocol.setEvents(Collections.emptyList());
});

return onionServiceLookupCompletableFuture;
}

public void publish(TorKeyPair torKeyPair, int onionServicePort, int localPort) throws IOException, InterruptedException {
public void publish(TorKeyPair torKeyPair, int onionServicePort, int localPort) throws InterruptedException {
String onionAddress = torKeyPair.getOnionAddress();
var onionServicePublishedLatch = new CountDownLatch(1);
pendingOnionServicePublishLatchMap.put(onionAddress, onionServicePublishedLatch);

subscribeToHsDescEvents();
TorControlProtocol torControlProtocol = getTorControlProtocol();
torControlProtocol.addOnion(torKeyPair, onionServicePort, localPort);

boolean isSuccess = onionServicePublishedLatch.await(hsUploadTimeout, TimeUnit.MILLISECONDS);
Expand All @@ -107,28 +97,20 @@ public void publish(TorKeyPair torKeyPair, int onionServicePort, int localPort)
torControlProtocol.setEvents(Collections.emptyList());
}

public Optional<Integer> getSocksPort() {
try {
TorControlProtocol torControlProtocol = getTorControlProtocol();
String socksListenersString = torControlProtocol.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 int getSocksPort() {
String socksListenersString = torControlProtocol.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];
return Integer.parseInt(portString);
}

@Override
Expand Down Expand Up @@ -174,50 +156,35 @@ public void onHsDescEvent(HsDescEvent hsDescEvent) {
}
}

private void initialize(int controlPort, Optional<PasswordDigest> hashedControlPassword) throws IOException {
var torControlProtocol = new TorControlProtocol(controlPort);
this.torControlProtocol = Optional.of(torControlProtocol);

torControlProtocol.initialize();
if (hashedControlPassword.isPresent()) {
torControlProtocol.authenticate(hashedControlPassword.get());
}
private void initialize(int controlPort, Optional<PasswordDigest> hashedControlPassword) {
torControlProtocol.initialize(controlPort);
hashedControlPassword.ifPresent(torControlProtocol::authenticate);
}

private void bindToBisq() throws IOException {
TorControlProtocol torControlProtocol = getTorControlProtocol();
private void bindToBisq() {
torControlProtocol.takeOwnership();
torControlProtocol.resetConf(NativeTorProcess.ARG_OWNER_PID);
}

private void subscribeToBootstrapEvents() throws IOException {
TorControlProtocol torControlProtocol = getTorControlProtocol();
private void subscribeToBootstrapEvents() {
torControlProtocol.addBootstrapEventListener(this);
torControlProtocol.setEvents(List.of("STATUS_CLIENT"));
}

private void subscribeToHsDescEvents() throws IOException {
TorControlProtocol torControlProtocol = getTorControlProtocol();
private void subscribeToHsDescEvents() {
torControlProtocol.addHsDescEventListener(this);
torControlProtocol.setEvents(List.of("HS_DESC"));
}

private void enableNetworking() throws IOException {
TorControlProtocol torControlProtocol = getTorControlProtocol();
private void enableNetworking() {
torControlProtocol.setConfig(TorrcClientConfigFactory.DISABLE_NETWORK_CONFIG_KEY, "0");
}

private void waitUntilBootstrapped() {
try {
while (true) {
if (torControlProtocol.isEmpty()) {
throw new TorBootstrapFailedException("Tor is not initializing.");
}

boolean isSuccess = isBootstrappedCountdownLatch.await(bootstrapTimeout, TimeUnit.MILLISECONDS);

if (isSuccess) {
TorControlProtocol torControlProtocol = this.torControlProtocol.get();
torControlProtocol.removeBootstrapEventListener(this);
torControlProtocol.setEvents(Collections.emptyList());
break;
Expand All @@ -227,8 +194,6 @@ private void waitUntilBootstrapped() {
}
} catch (InterruptedException e) {
throw new TorBootstrapFailedException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}

Expand All @@ -238,8 +203,4 @@ private boolean isBootstrapTimeoutTriggered() {
Instant bootstrapTimeoutAgo = Instant.now().minus(bootstrapTimeout, ChronoUnit.MILLIS);
return bootstrapTimeoutAgo.isAfter(timestamp);
}

private TorControlProtocol getTorControlProtocol() {
return this.torControlProtocol.orElseThrow();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,17 @@

@Slf4j
public class WhonixTorControlReader implements AutoCloseable {
private final BufferedReader bufferedReader;
private final BlockingQueue<String> replies = new LinkedBlockingQueue<>();
private final List<BootstrapEventListener> bootstrapEventListeners = new CopyOnWriteArrayList<>();
private final List<HsDescEventListener> hsDescEventListeners = new CopyOnWriteArrayList<>();

private Optional<Thread> workerThread = Optional.empty();

public WhonixTorControlReader(InputStream inputStream) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.US_ASCII));
}

public void start() {
public void start(InputStream inputStream) {
Thread thread = new Thread(() -> {
try {
var bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.US_ASCII));

String line;
while ((line = bufferedReader.readLine()) != null) {

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package bisq.tor.controller.exceptions;

public class CannotConnectWithTorException extends RuntimeException {
public CannotConnectWithTorException(Throwable cause) {
super(cause);
}
}
Loading
Loading