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

TorControlProtocol: Implement GETINFO command #2247

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
@@ -0,0 +1,61 @@
package bisq.tor.controller;

import bisq.tor.controller.events.events.BootstrapEvent;

import java.util.Optional;

public class BootstrapEventParser {
public static Optional<BootstrapEvent> tryParse(String line) {
// 650 STATUS_CLIENT NOTICE BOOTSTRAP PROGRESS=50 TAG=loading_descriptors SUMMARY="Loading relay descriptors"
if (isStatusClientEvent(line)) {
String[] parts = line.split(" ");

if (isBootstrapEvent(parts)) {
BootstrapEvent bootstrapEvent = parseBootstrapEvent(parts);
return Optional.of(bootstrapEvent);
}
}

return Optional.empty();
}

private static boolean isStatusClientEvent(String line) {
// 650 STATUS_CLIENT NOTICE CIRCUIT_ESTABLISHED
return line.startsWith("650 STATUS_CLIENT");
}

private static boolean isBootstrapEvent(String[] parts) {
// 650 STATUS_CLIENT NOTICE BOOTSTRAP PROGRESS=50 TAG=loading_descriptors SUMMARY="Loading relay descriptors"
return parts.length >= 7 && parts[3].equals("BOOTSTRAP");
}


private static BootstrapEvent parseBootstrapEvent(String[] parts) {
String progress = parts[4].replace("PROGRESS=", "");
String tag = parts[5].replace("TAG=", "");
String summary = parseBootstrapSummary(parts);

int progressInt = Integer.parseInt(progress);
return new BootstrapEvent(progressInt, tag, summary);
}

private static String parseBootstrapSummary(String[] parts) {
StringBuilder summary = new StringBuilder();

// SUMMARY="Loading relay descriptors" has whitespaces in string
for (int i = 6; i < parts.length; i++) {
String summaryPart = parts[i];
summary.append(summaryPart)
.append(" ");
}

String summaryPrefix = "SUMMARY=\"";
summary.delete(0, summaryPrefix.length());

// ends with `" `
int length = summary.length();
summary.delete(length - 2, length);

return summary.toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,22 @@

import bisq.common.encoding.Hex;
import bisq.security.keys.TorKeyPair;
import bisq.tor.controller.events.listener.BootstrapEventListener;
import net.freehaven.tor.control.PasswordDigest;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class WhonixTorController implements AutoCloseable {
public class TorControlProtocol implements AutoCloseable {
private final Socket controlSocket;
private final BufferedReader bufferedReader;
private final WhonixTorControlReader whonixTorControlReader;
private final OutputStream outputStream;

public WhonixTorController() throws IOException {
controlSocket = new Socket("127.0.0.1", 9051);

InputStream inputStream = controlSocket.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.US_ASCII));

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

Expand All @@ -28,6 +26,10 @@ public void close() throws IOException {
controlSocket.close();
}

public void initialize() {
whonixTorControlReader.start();
}

public void authenticate(PasswordDigest passwordDigest) throws IOException {
byte[] secret = passwordDigest.getSecret();
String secretHex = Hex.encode(secret);
Expand All @@ -53,6 +55,16 @@ public void addOnion(TorKeyPair torKeyPair, int onionPort, int localPort) throws
String reply = receiveReply();
}

public String getInfo(String keyword) throws IOException {
String command = "GETINFO " + keyword + "\r\n";
sendCommand(command);
String reply = receiveReply();
if (!reply.startsWith("250-")) {
throw new ControlCommandFailedException("Couldn't get info: " + keyword);
}
return reply;
}

public void resetConf(String configName) throws IOException {
String command = "RESETCONF " + configName + "\r\n";
sendCommand(command);
Expand Down Expand Up @@ -93,14 +105,22 @@ public void takeOwnership() throws IOException {
}
}

public void addBootstrapEventListener(BootstrapEventListener listener) {
whonixTorControlReader.addBootstrapEventListener(listener);
}

public void removeBootstrapEventListener(BootstrapEventListener listener) {
whonixTorControlReader.removeBootstrapEventListener(listener);
}

private void sendCommand(String command) throws IOException {
byte[] commandBytes = command.getBytes(StandardCharsets.US_ASCII);
outputStream.write(commandBytes);
outputStream.flush();
}

private String receiveReply() throws IOException {
String reply = bufferedReader.readLine();
private String receiveReply() {
String reply = whonixTorControlReader.readLine();
if (reply.equals("510 Command filtered")) {
throw new TorCommandFilteredException();
}
Expand Down
121 changes: 121 additions & 0 deletions network/tor/tor/src/main/java/bisq/tor/controller/TorController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
package bisq.tor.controller;

import bisq.common.observable.Observable;
import bisq.tor.TorrcClientConfigFactory;
import bisq.tor.controller.events.events.BootstrapEvent;
import bisq.tor.controller.events.listener.BootstrapEventListener;
import bisq.tor.controller.exceptions.TorBootstrapFailedException;
import bisq.tor.process.NativeTorProcess;
import lombok.Getter;
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.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@Slf4j
public class TorController implements BootstrapEventListener {
private final int bootstrapTimeout;
private final CountDownLatch isBootstrappedCountdownLatch = new CountDownLatch(1);
@Getter
private final Observable<BootstrapEvent> bootstrapEvent = new Observable<>();

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

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

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

torControlProtocol.initialize();
torControlProtocol.authenticate(hashedControlPassword);
}

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

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

@Override
public void onBootstrapStatusEvent(BootstrapEvent bootstrapEvent) {
log.info("Tor bootstrap event: {}", bootstrapEvent);
this.bootstrapEvent.set(bootstrapEvent);
if (bootstrapEvent.isDoneEvent()) {
isBootstrappedCountdownLatch.countDown();
}
}

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

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

private void enableNetworking() throws IOException {
TorControlProtocol torControlProtocol = getTorControlProtocol();
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;
} else if (isBootstrapTimeoutTriggered()) {
throw new TorBootstrapFailedException("Tor bootstrap timeout triggered.");
}
}
} catch (InterruptedException e) {
throw new TorBootstrapFailedException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}

private boolean isBootstrapTimeoutTriggered() {
BootstrapEvent bootstrapEvent = this.bootstrapEvent.get();
Instant timestamp = bootstrapEvent.getTimestamp();
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
@@ -0,0 +1,87 @@
package bisq.tor.controller;

import bisq.tor.controller.events.events.BootstrapEvent;
import bisq.tor.controller.events.listener.BootstrapEventListener;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.LinkedBlockingQueue;

@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 Optional<Thread> workerThread = Optional.empty();

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

public void start() {
Thread thread = new Thread(() -> {
try {
String line;
while ((line = bufferedReader.readLine()) != null) {

if (isEvent(line)) {
Optional<BootstrapEvent> bootstrapEventOptional = BootstrapEventParser.tryParse(line);
if (bootstrapEventOptional.isPresent()) {
BootstrapEvent bootstrapEvent = bootstrapEventOptional.get();
bootstrapEventListeners.forEach(listener -> listener.onBootstrapStatusEvent(bootstrapEvent));
} else {
log.info("Unknown Tor event: {}", line);
}

} else {
replies.add(line);
}

if (Thread.interrupted()) {
break;
}
}
} catch (IOException e) {
log.error("Tor control port reader couldn't read reply.", e);
}

});
workerThread = Optional.of(thread);
thread.start();
}

@Override
public void close() throws Exception {
workerThread.ifPresent(Thread::interrupt);
}

public String readLine() {
try {
return replies.take();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}

public void addBootstrapEventListener(BootstrapEventListener listener) {
bootstrapEventListeners.add(listener);
}

public void removeBootstrapEventListener(BootstrapEventListener listener) {
bootstrapEventListeners.remove(listener);
}

private boolean isEvent(String line) {
// 650 STATUS_CLIENT NOTICE CIRCUIT_ESTABLISHED
return line.startsWith("650");
}
}
Loading