Search in sources :

Example 1 with Tor

use of org.berndpruenster.netlayer.tor.Tor in project bitcoin-spring-boot-starter by theborakompanioni.

the class DefaultTorHiddenServiceSocketFactoryTest method itShouldCreateHiddenService.

@Test
void itShouldCreateHiddenService() throws InterruptedException {
    // create a hidden service in directory 'test' inside the tor installation directory
    HiddenServiceSocketCreateContext context = HiddenServiceSocketCreateContext.builder().hostPort(port).hiddenServiceDir("test").build();
    HiddenServiceSocket hiddenServiceSocket = this.sut.createReady(context).blockOptional(Duration.ofMinutes(3)).orElseThrow(() -> new IllegalStateException("Could not create hidden service on port " + port));
    log.info("Hidden Service {} is ready", hiddenServiceSocket);
    Flux<Socket> socketFlux = Flux.<Socket>create(fluxSink -> {
        try {
            fluxSink.next(hiddenServiceSocket.accept());
        } catch (IOException e) {
            fluxSink.error(e);
        }
    }).onErrorContinue((e, target) -> {
        log.warn("Error while accepting socket connections: {}", e.getMessage());
    });
    CountDownLatch countDownLatch = new CountDownLatch(1);
    new Thread(() -> {
        log.info("trying to connect to the hidden service {}", hiddenServiceSocket);
        try (TorSocket s1 = new TorSocket(hiddenServiceSocket.getSocketAddress(), "foo")) {
            log.info("Successfully connected to {}", hiddenServiceSocket);
            log.info("Closing socket now...");
            IOUtils.closeQuietly(hiddenServiceSocket);
        } catch (IOException e) {
            log.error("Exception while handling socket connection", e);
        }
        // retry connecting
        try (TorSocket s2 = new TorSocket(hiddenServiceSocket.getServiceName(), hiddenServiceSocket.getHiddenServicePort(), "foo")) {
            // do nothing on purpose
            log.error("expected an error when opening connection to closed hidden service socket");
        } catch (IOException e) {
            log.debug("As expected, connection to {} failed with: {}", hiddenServiceSocket, e.getMessage());
        }
        countDownLatch.countDown();
    }).start();
    Socket incomingSocket = socketFlux.blockFirst(Duration.ofSeconds(10));
    log.info("Got an incoming connection to socket {}: {}", hiddenServiceSocket, incomingSocket);
    boolean await = countDownLatch.await(90, TimeUnit.SECONDS);
    assertThat("socket has been accepted", await, is(true));
    IOUtils.closeQuietly(incomingSocket);
}
Also used : NativeTorFactory(org.tbk.tor.NativeTorFactory) BeforeEach(org.junit.jupiter.api.BeforeEach) Socket(java.net.Socket) IOUtils(org.apache.commons.compress.utils.IOUtils) HiddenServiceSocket(org.berndpruenster.netlayer.tor.HiddenServiceSocket) IOException(java.io.IOException) Tor(org.berndpruenster.netlayer.tor.Tor) File(java.io.File) Test(org.junit.jupiter.api.Test) TimeUnit(java.util.concurrent.TimeUnit) Flux(reactor.core.publisher.Flux) CountDownLatch(java.util.concurrent.CountDownLatch) Slf4j(lombok.extern.slf4j.Slf4j) AfterEach(org.junit.jupiter.api.AfterEach) HiddenServiceSocketCreateContext(org.tbk.tor.hs.TorHiddenServiceSocketFactory.HiddenServiceSocketCreateContext) Duration(java.time.Duration) Matchers.is(org.hamcrest.Matchers.is) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) TorSocket(org.berndpruenster.netlayer.tor.TorSocket) NativeTor(org.berndpruenster.netlayer.tor.NativeTor) TorSocket(org.berndpruenster.netlayer.tor.TorSocket) HiddenServiceSocket(org.berndpruenster.netlayer.tor.HiddenServiceSocket) HiddenServiceSocketCreateContext(org.tbk.tor.hs.TorHiddenServiceSocketFactory.HiddenServiceSocketCreateContext) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) Socket(java.net.Socket) HiddenServiceSocket(org.berndpruenster.netlayer.tor.HiddenServiceSocket) TorSocket(org.berndpruenster.netlayer.tor.TorSocket) Test(org.junit.jupiter.api.Test)

Example 2 with Tor

use of org.berndpruenster.netlayer.tor.Tor in project bitcoin-spring-boot-starter by theborakompanioni.

the class TorExampleApplication method torInfoRunner.

@Bean
@Profile("!test")
public ApplicationRunner torInfoRunner() {
    String successPhrase = "Congratulations. This browser is configured to use Tor.";
    String errorPhraseIgnoreCase = "not using Tor";
    return args -> {
        HttpGet req = new HttpGet("https://check.torproject.org/");
        HttpResponse rsp = torHttpClient.execute(req);
        String body = EntityUtils.toString(rsp.getEntity(), StandardCharsets.UTF_8);
        boolean containsErrorPhrase = body.toLowerCase().contains(errorPhraseIgnoreCase.toLowerCase());
        boolean containsSuccessPhrase = body.contains(successPhrase);
        boolean torEnabled = containsSuccessPhrase && !containsErrorPhrase;
        log.info("=================================================");
        if (torEnabled) {
            log.info("Tor is enabled.");
        } else {
            log.warn("Tor is NOT enabled.");
        }
        log.info("=================================================");
    };
}
Also used : SpringBootApplication(org.springframework.boot.autoconfigure.SpringBootApplication) ApplicationRunner(org.springframework.boot.ApplicationRunner) SpringApplicationBuilder(org.springframework.boot.builder.SpringApplicationBuilder) Autowired(org.springframework.beans.factory.annotation.Autowired) ApplicationListener(org.springframework.context.ApplicationListener) Tor(org.berndpruenster.netlayer.tor.Tor) Profile(org.springframework.context.annotation.Profile) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) EntityUtils(org.apache.http.util.EntityUtils) ApplicationPidFileWriter(org.springframework.boot.context.ApplicationPidFileWriter) WebServerPortFileWriter(org.springframework.boot.web.context.WebServerPortFileWriter) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) Qualifier(org.springframework.beans.factory.annotation.Qualifier) WebApplicationType(org.springframework.boot.WebApplicationType) HttpResponse(org.apache.http.HttpResponse) Optional(java.util.Optional) HiddenServiceDefinition(org.tbk.tor.hs.HiddenServiceDefinition) Bean(org.springframework.context.annotation.Bean) TorCtlException(org.berndpruenster.netlayer.tor.TorCtlException) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) Profile(org.springframework.context.annotation.Profile) Bean(org.springframework.context.annotation.Bean)

Example 3 with Tor

use of org.berndpruenster.netlayer.tor.Tor in project haveno by haveno-dex.

the class PriceNodeStats method execute.

@Override
protected void execute() {
    try {
        // fetch proxy
        Tor tor = Tor.getDefault();
        checkNotNull(tor, "tor must not be null");
        Socks5Proxy proxy = tor.getProxy();
        String[] hosts = configuration.getProperty(HOSTS, "").split(",");
        Collections.shuffle(Arrays.asList(hosts));
        // for each configured host
        for (String current : hosts) {
            Map<String, String> result = new HashMap<>();
            // parse Url
            NodeAddress tmp = OnionParser.getNodeAddress(current);
            // connect
            try {
                SocksSocket socket = new SocksSocket(proxy, tmp.getHostName(), tmp.getPort());
                // prepare to receive data
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                // ask for fee data
                PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
                out.println("GET /getFees/");
                out.println();
                out.flush();
                // sift through the received lines and see if we got something json-like
                String line;
                while ((line = in.readLine()) != null) {
                    Matcher matcher = stringNumberPattern.matcher(line);
                    if (matcher.find())
                        if (!IGNORE.contains(matcher.group(1)))
                            result.put("fees." + matcher.group(1), matcher.group(2));
                }
                in.close();
                out.close();
                socket.close();
                // connect
                socket = new SocksSocket(proxy, tmp.getHostName(), tmp.getPort());
                // prepare to receive data
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                // ask for exchange rate data
                out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
                out.println("GET /getAllMarketPrices/");
                out.println();
                out.flush();
                String currencyCode = "";
                while ((line = in.readLine()) != null) {
                    Matcher currencyCodeMatcher = currencyCodePattern.matcher(line);
                    Matcher priceMatcher = pricePattern.matcher(line);
                    if (currencyCodeMatcher.find()) {
                        currencyCode = currencyCodeMatcher.group(1);
                        if (!assets.contains(currencyCode))
                            currencyCode = "";
                    } else if (!"".equals(currencyCode) && priceMatcher.find())
                        result.put("price." + currencyCode, priceMatcher.group(1));
                }
                // close all the things
                in.close();
                out.close();
                socket.close();
                // report
                reporter.report(result, getName());
                // only ask for data as long as we got none
                if (!result.isEmpty())
                    break;
            } catch (IOException e) {
                log.error("{} seems to be down. Trying next configured price node.", tmp.getHostName());
                e.printStackTrace();
            }
        }
    } catch (TorCtlException | IOException e) {
        e.printStackTrace();
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) Socks5Proxy(com.runjva.sourceforge.jsocks.protocol.Socks5Proxy) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) IOException(java.io.IOException) SocksSocket(com.runjva.sourceforge.jsocks.protocol.SocksSocket) BufferedWriter(java.io.BufferedWriter) TorCtlException(org.berndpruenster.netlayer.tor.TorCtlException) Tor(org.berndpruenster.netlayer.tor.Tor) BufferedReader(java.io.BufferedReader) NodeAddress(bisq.network.p2p.NodeAddress) OutputStreamWriter(java.io.OutputStreamWriter) PrintWriter(java.io.PrintWriter)

Example 4 with Tor

use of org.berndpruenster.netlayer.tor.Tor in project haveno by haveno-dex.

the class TorNetworkNode method createTorAndHiddenService.

// /////////////////////////////////////////////////////////////////////////////////////////
// create tor
// /////////////////////////////////////////////////////////////////////////////////////////
private void createTorAndHiddenService(int localPort, int servicePort) {
    torStartupFuture = executorService.submit(() -> {
        try {
            // get tor
            Tor.setDefault(torMode.getTor());
            // start hidden service
            long ts2 = new Date().getTime();
            hiddenServiceSocket = new HiddenServiceSocket(localPort, torMode.getHiddenServiceDirectory(), servicePort);
            nodeAddressProperty.set(new NodeAddress(hiddenServiceSocket.getServiceName() + ":" + hiddenServiceSocket.getHiddenServicePort()));
            UserThread.execute(() -> setupListeners.forEach(SetupListener::onTorNodeReady));
            hiddenServiceSocket.addReadyListener(socket -> {
                try {
                    log.info("\n################################################################\n" + "Tor hidden service published after {} ms. Socket={}\n" + "################################################################", (new Date().getTime() - ts2), // takes usually 30-40 sec
                    socket);
                    new Thread() {

                        @Override
                        public void run() {
                            try {
                                nodeAddressProperty.set(new NodeAddress(hiddenServiceSocket.getServiceName() + ":" + hiddenServiceSocket.getHiddenServicePort()));
                                startServer(socket);
                                UserThread.execute(() -> setupListeners.forEach(SetupListener::onHiddenServicePublished));
                            } catch (final Exception e1) {
                                log.error(e1.toString());
                                e1.printStackTrace();
                            }
                        }
                    }.start();
                } catch (final Exception e) {
                    log.error(e.toString());
                    e.printStackTrace();
                }
                return null;
            });
        } catch (TorCtlException e) {
            String msg = e.getCause() != null ? e.getCause().toString() : e.toString();
            log.error("Tor node creation failed: {}", msg);
            if (e.getCause() instanceof IOException) {
                // Since we cannot connect to Tor, we cannot do nothing.
                // Furthermore, we have no hidden services started yet, so there is no graceful
                // shutdown needed either
                UserThread.execute(() -> setupListeners.forEach(s -> s.onSetupFailed(new RuntimeException(msg))));
            } else {
                restartTor(e.getMessage());
            }
        } catch (IOException e) {
            log.error("Could not connect to running Tor: {}", e.getMessage());
            // Since we cannot connect to Tor, we cannot do nothing.
            // Furthermore, we have no hidden services started yet, so there is no graceful
            // shutdown needed either
            UserThread.execute(() -> setupListeners.forEach(s -> s.onSetupFailed(new RuntimeException(e.getMessage()))));
        } catch (Throwable ignore) {
        }
        return null;
    });
    Futures.addCallback(torStartupFuture, Utilities.failureCallback(throwable -> UserThread.execute(() -> log.error("Hidden service creation failed: " + throwable))), MoreExecutors.directExecutor());
}
Also used : MoreExecutors(com.google.common.util.concurrent.MoreExecutors) Socket(java.net.Socket) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Utilities(bisq.common.util.Utilities) Date(java.util.Date) LoggerFactory(org.slf4j.LoggerFactory) Timer(bisq.common.Timer) SecureRandom(java.security.SecureRandom) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) Socks5Proxy(com.runjva.sourceforge.jsocks.protocol.Socks5Proxy) MonadicBinding(org.fxmisc.easybind.monadic.MonadicBinding) TorCtlException(org.berndpruenster.netlayer.tor.TorCtlException) Utils(bisq.network.utils.Utils) Logger(org.slf4j.Logger) HiddenServiceSocket(org.berndpruenster.netlayer.tor.HiddenServiceSocket) IOException(java.io.IOException) Tor(org.berndpruenster.netlayer.tor.Tor) TimeUnit(java.util.concurrent.TimeUnit) Nullable(org.jetbrains.annotations.Nullable) Futures(com.google.common.util.concurrent.Futures) BooleanProperty(javafx.beans.property.BooleanProperty) Base64(java.util.Base64) SimpleBooleanProperty(javafx.beans.property.SimpleBooleanProperty) EasyBind(org.fxmisc.easybind.EasyBind) NodeAddress(bisq.network.p2p.NodeAddress) UserThread(bisq.common.UserThread) TorSocket(org.berndpruenster.netlayer.tor.TorSocket) NetworkProtoResolver(bisq.common.proto.network.NetworkProtoResolver) HiddenServiceSocket(org.berndpruenster.netlayer.tor.HiddenServiceSocket) TorCtlException(org.berndpruenster.netlayer.tor.TorCtlException) NodeAddress(bisq.network.p2p.NodeAddress) IOException(java.io.IOException) Date(java.util.Date) TorCtlException(org.berndpruenster.netlayer.tor.TorCtlException) IOException(java.io.IOException) UserThread(bisq.common.UserThread)

Example 5 with Tor

use of org.berndpruenster.netlayer.tor.Tor in project haveno by haveno-dex.

the class P2PNetworkLoadTests method cleanup.

@AfterAll
static void cleanup() {
    Tor tor = Tor.getDefault();
    checkNotNull(tor, "tor must not be null");
    tor.shutdown();
}
Also used : Tor(org.berndpruenster.netlayer.tor.Tor) NativeTor(org.berndpruenster.netlayer.tor.NativeTor) AfterAll(org.junit.jupiter.api.AfterAll)

Aggregations

Tor (org.berndpruenster.netlayer.tor.Tor)14 NativeTor (org.berndpruenster.netlayer.tor.NativeTor)8 IOException (java.io.IOException)5 TorCtlException (org.berndpruenster.netlayer.tor.TorCtlException)5 AfterAll (org.junit.jupiter.api.AfterAll)5 NodeAddress (bisq.network.p2p.NodeAddress)3 Socks5Proxy (com.runjva.sourceforge.jsocks.protocol.Socks5Proxy)3 Slf4j (lombok.extern.slf4j.Slf4j)3 SocksSocket (com.runjva.sourceforge.jsocks.protocol.SocksSocket)2 Socket (java.net.Socket)2 StandardCharsets (java.nio.charset.StandardCharsets)2 Duration (java.time.Duration)2 Date (java.util.Date)2 TimeUnit (java.util.concurrent.TimeUnit)2 HiddenServiceSocket (org.berndpruenster.netlayer.tor.HiddenServiceSocket)2 TorSocket (org.berndpruenster.netlayer.tor.TorSocket)2 Timer (bisq.common.Timer)1 UserThread (bisq.common.UserThread)1 NetworkProtoResolver (bisq.common.proto.network.NetworkProtoResolver)1 Utilities (bisq.common.util.Utilities)1