Search in sources :

Example 76 with Destination

use of net.i2p.data.Destination in project i2p.i2p by i2p.

the class StreamSinkClient method runClient.

/**
 * Actually connect and run the client - this call blocks until completion.
 */
public void runClient() {
    I2PSocketManager mgr = null;
    if (_i2cpHost != null)
        mgr = I2PSocketManagerFactory.createManager(_i2cpHost, _i2cpPort, new Properties());
    else
        mgr = I2PSocketManagerFactory.createManager();
    Destination peer = null;
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(_peerDestFile);
        peer = new Destination();
        peer.readBytes(fis);
    } catch (IOException ioe) {
        _log.error("Error finding the peer destination to contact in " + _peerDestFile, ioe);
        return;
    } catch (DataFormatException dfe) {
        _log.error("Peer destination is not valid in " + _peerDestFile, dfe);
        return;
    } finally {
        if (fis != null)
            try {
                fis.close();
            } catch (IOException ioe) {
            }
    }
    if (_log.shouldLog(Log.DEBUG))
        _log.debug("Send " + _sendSize + "KB to " + peer.calculateHash().toBase64());
    while (true) {
        try {
            I2PSocket sock = mgr.connect(peer);
            byte[] buf = new byte[Math.min(32 * 1024, _sendSize * 1024)];
            Random rand = new Random();
            OutputStream out = sock.getOutputStream();
            long beforeSending = System.currentTimeMillis();
            for (int i = 0; (_sendSize < 0) || (i < _sendSize); i += buf.length / 1024) {
                rand.nextBytes(buf);
                out.write(buf);
                if (_log.shouldLog(Log.DEBUG))
                    _log.debug("Wrote " + ((1 + i * buf.length) / 1024) + "/" + _sendSize + "KB");
                if (_writeDelay > 0) {
                    try {
                        Thread.sleep(_writeDelay);
                    } catch (InterruptedException ie) {
                    }
                }
            }
            sock.close();
            long afterSending = System.currentTimeMillis();
            if (_log.shouldLog(Log.DEBUG))
                _log.debug("Sent " + _sendSize + "KB in " + (afterSending - beforeSending) + "ms");
        } catch (InterruptedIOException iie) {
            _log.error("Timeout connecting to the peer", iie);
        // return;
        } catch (NoRouteToHostException nrthe) {
            _log.error("Unable to connect to the peer", nrthe);
        // return;
        } catch (ConnectException ce) {
            _log.error("Connection already dropped", ce);
        // return;
        } catch (I2PException ie) {
            _log.error("Error connecting to the peer", ie);
            return;
        } catch (IOException ioe) {
            _log.error("IO error sending", ioe);
            return;
        }
    }
}
Also used : I2PException(net.i2p.I2PException) Destination(net.i2p.data.Destination) InterruptedIOException(java.io.InterruptedIOException) OutputStream(java.io.OutputStream) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException) Properties(java.util.Properties) NoRouteToHostException(java.net.NoRouteToHostException) FileInputStream(java.io.FileInputStream) DataFormatException(net.i2p.data.DataFormatException) Random(java.util.Random) ConnectException(java.net.ConnectException)

Example 77 with Destination

use of net.i2p.data.Destination in project i2p.i2p by i2p.

the class TestSwarm method connectWithPeers.

private void connectWithPeers() {
    if (_peerDestFiles != null) {
        for (int i = 0; i < _peerDestFiles.length; i++) {
            try {
                FileInputStream fin = new FileInputStream(_peerDestFiles[i]);
                Destination dest = new Destination();
                dest.readBytes(fin);
                I2PThread flooder = new I2PThread(new Flooder(dest), "Flooder+" + dest.calculateHash().toBase64().substring(0, 4));
                flooder.start();
            } catch (Exception e) {
                _log.error("Unable to read the peer from " + _peerDestFiles[i], e);
            }
        }
    }
}
Also used : Destination(net.i2p.data.Destination) I2PThread(net.i2p.util.I2PThread) FileInputStream(java.io.FileInputStream)

Example 78 with Destination

use of net.i2p.data.Destination in project i2p.i2p by i2p.

the class GeneralHelper method getDestination.

/**
 *  Works even if tunnel is not running.
 *  @return Destination or null
 */
public Destination getDestination(int tunnel) {
    TunnelController tun = getController(tunnel);
    if (tun != null) {
        Destination rv = tun.getDestination();
        if (rv != null)
            return rv;
        // if not running, do this the hard way
        File keyFile = tun.getPrivateKeyFile();
        if (keyFile != null) {
            PrivateKeyFile pkf = new PrivateKeyFile(keyFile);
            try {
                rv = pkf.getDestination();
                if (rv != null)
                    return rv;
            } catch (I2PException e) {
            } catch (IOException e) {
            }
        }
    }
    return null;
}
Also used : I2PException(net.i2p.I2PException) Destination(net.i2p.data.Destination) TunnelController(net.i2p.i2ptunnel.TunnelController) PrivateKeyFile(net.i2p.data.PrivateKeyFile) IOException(java.io.IOException) SecureFile(net.i2p.util.SecureFile) PrivateKeyFile(net.i2p.data.PrivateKeyFile) File(java.io.File)

Example 79 with Destination

use of net.i2p.data.Destination in project i2p.i2p by i2p.

the class LocalHTTPServer method serveLocalFile.

/**
 *  Very simple web server.
 *
 *  Serve local files in the docs/ directory, for CSS and images in
 *  error pages, using the reserved address proxy.i2p
 *  (similar to p.p in privoxy).
 *  This solves the problems with including links to the router console,
 *  as assuming the router console is at 127.0.0.1 leads to broken
 *  links if it isn't.
 *
 *  Ignore all request headers (If-Modified-Since, etc.)
 *
 *  There is basic protection here -
 *  FileUtil.readFile() prevents traversal above the base directory -
 *  but inproxy/gateway ops would be wise to block proxy.i2p to prevent
 *  exposing the docs/ directory or perhaps other issues through
 *  uncaught vulnerabilities.
 *  Restrict to the /themes/ directory for now.
 *
 *  @param targetRequest decoded path only, non-null
 *  @param query raw (encoded), may be null
 */
public static void serveLocalFile(OutputStream out, String method, String targetRequest, String query, String proxyNonce) throws IOException {
    // a home page message for the curious...
    if (targetRequest.equals("/")) {
        out.write(OK.getBytes("UTF-8"));
        out.flush();
        return;
    }
    if ((method.equals("GET") || method.equals("HEAD")) && targetRequest.startsWith("/themes/") && !targetRequest.contains("..")) {
        String filename = null;
        try {
            // "/themes/".length
            filename = targetRequest.substring(8);
        } catch (IndexOutOfBoundsException ioobe) {
            return;
        }
        // theme hack
        if (filename.startsWith("console/default/"))
            filename = filename.replaceFirst("default", I2PAppContext.getGlobalContext().getProperty("routerconsole.theme", "light"));
        File themesDir = new File(I2PAppContext.getGlobalContext().getBaseDir(), "docs/themes");
        File file = new File(themesDir, filename);
        if (file.exists() && !file.isDirectory()) {
            String type;
            if (filename.endsWith(".css"))
                type = "text/css";
            else if (filename.endsWith(".ico"))
                type = "image/x-icon";
            else if (filename.endsWith(".png"))
                type = "image/png";
            else if (filename.endsWith(".jpg"))
                type = "image/jpeg";
            else
                type = "text/html";
            out.write("HTTP/1.1 200 OK\r\nContent-Type: ".getBytes("UTF-8"));
            out.write(type.getBytes("UTF-8"));
            out.write("\r\nCache-Control: max-age=86400\r\nConnection: close\r\nProxy-Connection: close\r\n\r\n".getBytes("UTF-8"));
            FileUtil.readFile(filename, themesDir.getAbsolutePath(), out);
            return;
        }
    }
    // Do the add and redirect.
    if (targetRequest.equals("/add")) {
        if (query == null) {
            out.write(ERR_ADD.getBytes("UTF-8"));
            return;
        }
        Map<String, String> opts = new HashMap<String, String>(8);
        // this only works if all keys are followed by =value
        StringTokenizer tok = new StringTokenizer(query, "=&;");
        while (tok.hasMoreTokens()) {
            String k = tok.nextToken();
            if (!tok.hasMoreTokens())
                break;
            String v = tok.nextToken();
            opts.put(decode(k), decode(v));
        }
        String url = opts.get("url");
        String host = opts.get("host");
        String b64Dest = opts.get("dest");
        String nonce = opts.get("nonce");
        String referer = opts.get("referer");
        String book = "privatehosts.txt";
        if (opts.get("master") != null)
            book = "userhosts.txt";
        else if (opts.get("router") != null)
            book = "hosts.txt";
        Destination dest = null;
        if (b64Dest != null) {
            try {
                dest = new Destination(b64Dest);
            } catch (DataFormatException dfe) {
                System.err.println("Bad dest to save?" + b64Dest);
            }
        }
        // System.err.println("nonce        : \"" + nonce         + "\"");
        if (proxyNonce.equals(nonce) && url != null && host != null && dest != null) {
            NamingService ns = I2PAppContext.getGlobalContext().namingService();
            Properties nsOptions = new Properties();
            nsOptions.setProperty("list", book);
            if (referer != null && referer.startsWith("http")) {
                String ref = DataHelper.escapeHTML(referer);
                String from = "<a href=\"" + ref + "\">" + ref + "</a>";
                nsOptions.setProperty("s", _t("Added via address helper from {0}", from));
            } else {
                nsOptions.setProperty("s", _t("Added via address helper"));
            }
            boolean success = ns.put(host, dest, nsOptions);
            writeRedirectPage(out, success, host, book, url);
            return;
        }
        out.write(ERR_ADD.getBytes("UTF-8"));
    } else {
        out.write(ERR_404.getBytes("UTF-8"));
    }
    out.flush();
}
Also used : Destination(net.i2p.data.Destination) StringTokenizer(java.util.StringTokenizer) DataFormatException(net.i2p.data.DataFormatException) HashMap(java.util.HashMap) NamingService(net.i2p.client.naming.NamingService) Properties(java.util.Properties) File(java.io.File)

Example 80 with Destination

use of net.i2p.data.Destination in project i2p.i2p by i2p.

the class SOCKS5Server method getDestinationI2PSocket.

/**
 * Get an I2PSocket that can be used to send/receive 8-bit clean data
 * to/from the destination of the SOCKS connection.
 *
 * @return an I2PSocket connected with the destination
 */
public I2PSocket getDestinationI2PSocket(I2PSOCKSTunnel t) throws SOCKSException {
    setupServer();
    if (connHostName == null) {
        _log.error("BUG: destination host name has not been initialized!");
        throw new SOCKSException("BUG! See the logs!");
    }
    if (connPort == 0) {
        _log.error("BUG: destination port has not been initialized!");
        throw new SOCKSException("BUG! See the logs!");
    }
    // for errors
    DataOutputStream out;
    try {
        out = new DataOutputStream(clientSock.getOutputStream());
    } catch (IOException e) {
        throw new SOCKSException("Connection error", e);
    }
    // FIXME: here we should read our config file, select an
    // outproxy, and instantiate the proper socket class that
    // handles the outproxy itself (SOCKS4a, SOCKS5, HTTP CONNECT...).
    I2PSocket destSock;
    try {
        if (connHostName.toLowerCase(Locale.US).endsWith(".i2p")) {
            // Let's not do a new Dest for every request, huh?
            // I2PSocketManager sm = I2PSocketManagerFactory.createManager();
            // destSock = sm.connect(I2PTunnel.destFromName(connHostName), null);
            Destination dest = _context.namingService().lookup(connHostName);
            if (dest == null) {
                try {
                    sendRequestReply(Reply.HOST_UNREACHABLE, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
                } catch (IOException ioe) {
                }
                throw new SOCKSException("Host not found");
            }
            if (_log.shouldDebug())
                _log.debug("connecting to " + connHostName + "...");
            Properties overrides = new Properties();
            I2PSocketOptions sktOpts = t.buildOptions(overrides);
            sktOpts.setPort(connPort);
            destSock = t.createI2PSocket(dest, sktOpts);
        } else if ("localhost".equals(connHostName) || "127.0.0.1".equals(connHostName)) {
            String err = "No localhost accesses allowed through the Socks Proxy";
            _log.error(err);
            try {
                sendRequestReply(Reply.CONNECTION_NOT_ALLOWED_BY_RULESET, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
            } catch (IOException ioe) {
            }
            throw new SOCKSException(err);
        /**
         **
         *            } else if (connPort == 80) {
         *                // rewrite GET line to include hostname??? or add Host: line???
         *                // or forward to local eepProxy (but that's a Socket not an I2PSocket)
         *                // use eepProxy configured outproxies?
         *                String err = "No handler for HTTP outproxy implemented";
         *                _log.error(err);
         *                try {
         *                    sendRequestReply(Reply.CONNECTION_NOT_ALLOWED_BY_RULESET, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
         *                } catch (IOException ioe) {}
         *                throw new SOCKSException(err);
         ***
         */
        } else {
            Outproxy outproxy = getOutproxyPlugin();
            if (outproxy != null) {
                // but here, we wrap a Socket in a I2PSocket and use the regular Runner.
                try {
                    destSock = new SocketWrapper(outproxy.connect(connHostName, connPort));
                } catch (IOException ioe) {
                    try {
                        sendRequestReply(Reply.HOST_UNREACHABLE, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
                    } catch (IOException ioe2) {
                    }
                    throw new SOCKSException("connect failed via outproxy plugin", ioe);
                }
            } else {
                List<String> proxies = t.getProxies(connPort);
                if (proxies == null || proxies.isEmpty()) {
                    String err = "No outproxy configured for port " + connPort + " and no default configured either";
                    _log.error(err);
                    try {
                        sendRequestReply(Reply.CONNECTION_NOT_ALLOWED_BY_RULESET, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
                    } catch (IOException ioe) {
                    }
                    throw new SOCKSException(err);
                }
                int p = _context.random().nextInt(proxies.size());
                String proxy = proxies.get(p);
                if (_log.shouldLog(Log.DEBUG))
                    _log.debug("connecting to proxy " + proxy + " for " + connHostName + " port " + connPort);
                try {
                    destSock = outproxyConnect(t, proxy);
                } catch (SOCKSException se) {
                    try {
                        sendRequestReply(Reply.HOST_UNREACHABLE, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
                    } catch (IOException ioe) {
                    }
                    throw se;
                }
            }
        }
        confirmConnection();
        _log.debug("connection confirmed - exchanging data...");
    } catch (DataFormatException e) {
        if (_log.shouldLog(Log.WARN))
            _log.warn("socks error", e);
        try {
            sendRequestReply(Reply.HOST_UNREACHABLE, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
        } catch (IOException ioe) {
        }
        throw new SOCKSException("Error in destination format");
    } catch (IOException e) {
        if (_log.shouldLog(Log.WARN))
            _log.warn("socks error", e);
        try {
            sendRequestReply(Reply.HOST_UNREACHABLE, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
        } catch (IOException ioe) {
        }
        throw new SOCKSException("Connection error", e);
    } catch (I2PException e) {
        if (_log.shouldLog(Log.WARN))
            _log.warn("socks error", e);
        try {
            sendRequestReply(Reply.HOST_UNREACHABLE, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
        } catch (IOException ioe) {
        }
        throw new SOCKSException("Connection error", e);
    }
    return destSock;
}
Also used : I2PException(net.i2p.I2PException) Destination(net.i2p.data.Destination) DataOutputStream(java.io.DataOutputStream) SOCKSException(net.i2p.socks.SOCKSException) I2PSocket(net.i2p.client.streaming.I2PSocket) Outproxy(net.i2p.app.Outproxy) I2PSocketOptions(net.i2p.client.streaming.I2PSocketOptions) IOException(java.io.IOException) Properties(java.util.Properties) DataFormatException(net.i2p.data.DataFormatException) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

Destination (net.i2p.data.Destination)149 IOException (java.io.IOException)46 DataFormatException (net.i2p.data.DataFormatException)33 Properties (java.util.Properties)29 I2PException (net.i2p.I2PException)26 Hash (net.i2p.data.Hash)18 ArrayList (java.util.ArrayList)13 File (java.io.File)12 I2PSessionException (net.i2p.client.I2PSessionException)12 SigType (net.i2p.crypto.SigType)12 ByteArrayInputStream (java.io.ByteArrayInputStream)11 ByteArrayOutputStream (java.io.ByteArrayOutputStream)10 I2PSession (net.i2p.client.I2PSession)10 I2PSocket (net.i2p.client.streaming.I2PSocket)10 FileInputStream (java.io.FileInputStream)7 InputStream (java.io.InputStream)7 OutputStream (java.io.OutputStream)7 I2PClient (net.i2p.client.I2PClient)7 I2PSocketOptions (net.i2p.client.streaming.I2PSocketOptions)7 Test (org.junit.Test)6