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

Remove deprecated OnionServicePublishService #2284

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 @@ -7,15 +7,16 @@
import bisq.network.identity.NetworkId;
import bisq.network.p2p.node.ConnectionException;
import bisq.security.keys.KeyBundle;
import bisq.security.keys.TorKeyPair;
import bisq.tor.TorService;
import bisq.tor.TorTransportConfig;
import bisq.tor.onionservice.CreateOnionServiceResponse;
import com.runjva.sourceforge.jsocks.protocol.Socks5Proxy;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
Expand Down Expand Up @@ -81,14 +82,19 @@ public ServerSocketResult getServerSocket(NetworkId networkId, KeyBundle keyBund
bootstrapInfo.getBootstrapProgress().set(0.25);
bootstrapInfo.getBootstrapDetails().set("Create Onion service for node ID '" + networkId + "'");

CreateOnionServiceResponse response = torService.createOnionService(port, keyBundle.getTorKeyPair())
TorKeyPair torKeyPair = keyBundle.getTorKeyPair();
ServerSocket serverSocket = torService.createOnionService(port, torKeyPair)
.get(2, TimeUnit.MINUTES);

bootstrapInfo.getBootstrapState().set(BootstrapState.SERVICE_PUBLISHED);
bootstrapInfo.getBootstrapProgress().set(0.5);
bootstrapInfo.getBootstrapDetails().set("My Onion service address: " + response.getOnionAddress().toString());

return new ServerSocketResult(response);
String onionAddress = torKeyPair.getOnionAddress();
bootstrapInfo.getBootstrapDetails().set("My Onion service address: " + onionAddress);

Address address = new Address(onionAddress);
return new ServerSocketResult(serverSocket, address);

} catch (InterruptedException | ExecutionException | TimeoutException e) {
e.printStackTrace();
throw new ConnectionException(e);
Expand Down
68 changes: 35 additions & 33 deletions network/tor/tor/src/main/java/bisq/tor/TorService.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,9 @@
import bisq.network.tor.common.torrc.BaseTorrcGenerator;
import bisq.network.tor.common.torrc.TorrcFileGenerator;
import bisq.security.keys.TorKeyPair;
import bisq.tor.controller.NativeTorController;
import bisq.tor.controller.TorController;
import bisq.tor.controller.events.events.BootstrapEvent;
import bisq.tor.installer.TorInstaller;
import bisq.tor.onionservice.CreateOnionServiceResponse;
import bisq.tor.onionservice.OnionServicePublishService;
import bisq.tor.process.NativeTorProcess;
import bisq.tor.process.control_port.ControlPortFilePoller;
import com.runjva.sourceforge.jsocks.protocol.Socks5Proxy;
Expand All @@ -40,7 +38,8 @@
import java.nio.file.Path;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.Set;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
Expand All @@ -49,8 +48,8 @@ public class TorService implements Service {

private final TorTransportConfig transportConfig;
private final Path torDataDirPath;
private final NativeTorController nativeTorController;
private final OnionServicePublishService onionServicePublishService;
private final TorController torController;
private final Set<String> publishedOnionServices = new CopyOnWriteArraySet<>();

private final AtomicBoolean isRunning = new AtomicBoolean();

Expand All @@ -60,9 +59,7 @@ public class TorService implements Service {
public TorService(TorTransportConfig transportConfig) {
this.transportConfig = transportConfig;
this.torDataDirPath = transportConfig.getDataDir();
nativeTorController = new NativeTorController(transportConfig.getBootstrapTimeout(),
transportConfig.getHsUploadTimeout());
this.onionServicePublishService = new OnionServicePublishService(nativeTorController);
torController = new TorController(transportConfig.getBootstrapTimeout(), transportConfig.getHsUploadTimeout());
}

@Override
Expand All @@ -89,19 +86,16 @@ public CompletableFuture<Boolean> initialize() {
return new ControlPortFilePoller(controlPortFilePath)
.parsePort()
.thenAccept(controlPort -> {
nativeTorController.connect(controlPort, Optional.of(hashedControlPassword));
nativeTorController.bindTorToConnection();
torController.initialize(controlPort, hashedControlPassword);
torController.bootstrapTor();

nativeTorController.enableTorNetworking();
nativeTorController.waitUntilBootstrapped();

int port = nativeTorController.getSocksPort().orElseThrow();
int port = torController.getSocksPort();
torSocksProxyFactory = Optional.of(new TorSocksProxyFactory(port));
})
.thenApply(unused -> true);
} else {
return CompletableFuture.supplyAsync(() -> {
nativeTorController.connect(9051, Optional.empty());
torController.initialize(9051);
torSocksProxyFactory = Optional.of(new TorSocksProxyFactory(9050));
return true;
});
Expand All @@ -112,38 +106,46 @@ public CompletableFuture<Boolean> initialize() {
public CompletableFuture<Boolean> shutdown() {
log.info("shutdown");
return CompletableFuture.supplyAsync(() -> {
nativeTorController.shutdown();
torController.shutdown();
torProcess.ifPresent(NativeTorProcess::waitUntilExited);
return true;
});
}

public Observable<BootstrapEvent> getBootstrapEvent() {
return nativeTorController.getBootstrapEvent();
}

public CompletableFuture<CreateOnionServiceResponse> createOnionService(int port, TorKeyPair torKeyPair) {
public CompletableFuture<ServerSocket> createOnionService(int port, TorKeyPair torKeyPair) {
log.info("Start hidden service with port {}", port);
long ts = System.currentTimeMillis();
try {
@SuppressWarnings("resource") ServerSocket localServerSocket = new ServerSocket(RANDOM_PORT);
var localServerSocket = new ServerSocket(RANDOM_PORT);
int localPort = localServerSocket.getLocalPort();
return onionServicePublishService.publish(torKeyPair, port, localPort)
.thenApply(onionAddress -> {
log.info("Tor hidden service Ready. Took {} ms. Onion address={}",
System.currentTimeMillis() - ts, onionAddress);
return new CreateOnionServiceResponse(localServerSocket, onionAddress);
}
);

} catch (IOException e) {

String onionAddress = torKeyPair.getOnionAddress();
if (!publishedOnionServices.contains(onionAddress)) {
torController.publish(torKeyPair, port, localPort);
publishedOnionServices.add(onionAddress);
}

log.info("Tor hidden service Ready. Took {} ms. Onion address={}",
System.currentTimeMillis() - ts, onionAddress);

return CompletableFuture.completedFuture(localServerSocket);

} catch (IOException | InterruptedException e) {
log.error("Can't create onion service", e);
return CompletableFuture.failedFuture(e);
}
}

public boolean isOnionServiceOnline(String onionUrl) {
return nativeTorController.isHiddenServiceAvailable(onionUrl);
try {
return torController.isOnionServiceOnline(onionUrl).get(1, TimeUnit.MINUTES);
} catch (ExecutionException | InterruptedException | TimeoutException e) {
throw new RuntimeException(e);
}
}

public Observable<BootstrapEvent> getBootstrapEvent() {
return torController.getBootstrapEvent();
}

public Socket getSocket(String streamId) throws IOException {
Expand Down
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
Loading
Loading