Search in sources :

Example 1 with TorCtlException

use of org.berndpruenster.netlayer.tor.TorCtlException 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 2 with TorCtlException

use of org.berndpruenster.netlayer.tor.TorCtlException 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 3 with TorCtlException

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

the class TorNetworkNode method getSocksProxy.

// TODO handle failure more cleanly
public Socks5Proxy getSocksProxy() {
    try {
        String stream = null;
        if (streamIsolation) {
            // create a random string
            // note that getProxy does Sha256 that string anyways
            byte[] bytes = new byte[512];
            new SecureRandom().nextBytes(bytes);
            stream = Base64.getEncoder().encodeToString(bytes);
        }
        if (socksProxy == null || streamIsolation) {
            tor = Tor.getDefault();
            // ask for the connection
            socksProxy = tor != null ? tor.getProxy(stream) : null;
        }
        return socksProxy;
    } catch (TorCtlException e) {
        log.error("TorCtlException at getSocksProxy: " + e.toString());
        e.printStackTrace();
        return null;
    } catch (Throwable t) {
        log.error("Error at getSocksProxy: " + t.toString());
        return null;
    }
}
Also used : TorCtlException(org.berndpruenster.netlayer.tor.TorCtlException) SecureRandom(java.security.SecureRandom)

Example 4 with TorCtlException

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

the class TorRoundTripTime method execute.

@Override
protected void execute() {
    SocksSocket socket;
    try {
        // fetch proxy
        Tor tor = Tor.getDefault();
        checkNotNull(tor, "tor must not be null");
        Socks5Proxy proxy = tor.getProxy();
        // for each configured host
        for (String current : configuration.getProperty(HOSTS, "").split(",")) {
            // parse Url
            NodeAddress tmp = OnionParser.getNodeAddress(current);
            List<Long> samples = new ArrayList<>();
            while (samples.size() < Integer.parseInt(configuration.getProperty(SAMPLE_SIZE, "1"))) {
                // start timer - we do not need System.nanoTime as we expect our result to be in
                // seconds time.
                long start = System.currentTimeMillis();
                // connect
                socket = new SocksSocket(proxy, tmp.getHostName(), tmp.getPort());
                // by the time we get here, we are connected
                samples.add(System.currentTimeMillis() - start);
                // cleanup
                socket.close();
            }
            // report
            reporter.report(StatisticsHelper.process(samples), getName());
        }
    } catch (TorCtlException | IOException e) {
        e.printStackTrace();
    }
}
Also used : TorCtlException(org.berndpruenster.netlayer.tor.TorCtlException) Socks5Proxy(com.runjva.sourceforge.jsocks.protocol.Socks5Proxy) Tor(org.berndpruenster.netlayer.tor.Tor) ArrayList(java.util.ArrayList) NodeAddress(bisq.network.p2p.NodeAddress) IOException(java.io.IOException) SocksSocket(com.runjva.sourceforge.jsocks.protocol.SocksSocket)

Example 5 with TorCtlException

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

the class TorStartupTime method execute.

@Override
protected void execute() {
    // cleanup installation
    torWorkingDirectory.delete();
    Tor tor = null;
    // start timer - we do not need System.nanoTime as we expect our result to be in
    // tenth of seconds time.
    long start = System.currentTimeMillis();
    try {
        tor = new NativeTor(torWorkingDirectory, null, torOverrides);
        // stop the timer and set its timestamp
        reporter.report(System.currentTimeMillis() - start, getName());
    } catch (TorCtlException e) {
        e.printStackTrace();
    } finally {
        // cleanup
        if (tor != null)
            tor.shutdown();
    }
}
Also used : TorCtlException(org.berndpruenster.netlayer.tor.TorCtlException) NativeTor(org.berndpruenster.netlayer.tor.NativeTor) Tor(org.berndpruenster.netlayer.tor.Tor) NativeTor(org.berndpruenster.netlayer.tor.NativeTor)

Aggregations

TorCtlException (org.berndpruenster.netlayer.tor.TorCtlException)5 Tor (org.berndpruenster.netlayer.tor.Tor)4 NodeAddress (bisq.network.p2p.NodeAddress)3 Socks5Proxy (com.runjva.sourceforge.jsocks.protocol.Socks5Proxy)3 IOException (java.io.IOException)3 SocksSocket (com.runjva.sourceforge.jsocks.protocol.SocksSocket)2 SecureRandom (java.security.SecureRandom)2 Timer (bisq.common.Timer)1 UserThread (bisq.common.UserThread)1 NetworkProtoResolver (bisq.common.proto.network.NetworkProtoResolver)1 Utilities (bisq.common.util.Utilities)1 Utils (bisq.network.utils.Utils)1 Preconditions.checkArgument (com.google.common.base.Preconditions.checkArgument)1 Futures (com.google.common.util.concurrent.Futures)1 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)1 MoreExecutors (com.google.common.util.concurrent.MoreExecutors)1 BufferedReader (java.io.BufferedReader)1 BufferedWriter (java.io.BufferedWriter)1 InputStreamReader (java.io.InputStreamReader)1 OutputStreamWriter (java.io.OutputStreamWriter)1