Search in sources :

Example 26 with I2PException

use of net.i2p.I2PException 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 27 with I2PException

use of net.i2p.I2PException in project i2p.i2p by i2p.

the class PrivateKeyFile method main.

/**
 *  Create a new PrivateKeyFile, or modify an existing one, with various
 *  types of Certificates.
 *
 *  Changing a Certificate does not change the public or private keys.
 *  But it does change the Destination Hash, which effectively makes it
 *  a new Destination. In other words, don't change the Certificate on
 *  a Destination you've already registered in a hosts.txt key add form.
 *
 *  Copied and expanded from that in Destination.java
 */
public static void main(String[] args) {
    int hashEffort = HASH_EFFORT;
    String stype = null;
    String hostname = null;
    int mode = 0;
    boolean error = false;
    Getopt g = new Getopt("pkf", args, "t:nuxhse:c:a:");
    int c;
    while ((c = g.getopt()) != -1) {
        switch(c) {
            case 'c':
                stype = g.getOptarg();
                break;
            case 't':
                stype = g.getOptarg();
            case 'n':
            case 'u':
            case 'x':
            case 'h':
            case 's':
                if (mode == 0)
                    mode = c;
                else
                    error = true;
                break;
            case 'a':
                hostname = g.getOptarg();
                if (mode == 0)
                    mode = c;
                else
                    error = true;
                break;
            case 'e':
                hashEffort = Integer.parseInt(g.getOptarg());
                break;
            case '?':
            case ':':
            default:
                error = true;
                break;
        }
    // switch
    }
    // while
    int remaining = args.length - g.getOptind();
    int reqd = mode == 's' ? 2 : 1;
    if (error || remaining != reqd) {
        usage();
        System.exit(1);
    }
    String filearg = args[g.getOptind()];
    I2PClient client = I2PClientFactory.createClient();
    try {
        File f = new File(filearg);
        boolean exists = f.exists();
        PrivateKeyFile pkf = new PrivateKeyFile(f, client);
        Destination d;
        if (stype != null) {
            SigType type = SigType.parseSigType(stype);
            if (type == null)
                throw new IllegalArgumentException("Signature type " + stype + " is not supported");
            d = pkf.createIfAbsent(type);
        } else {
            d = pkf.createIfAbsent();
        }
        if (exists)
            System.out.println("Original Destination:");
        else
            System.out.println("Created Destination:");
        System.out.println(pkf);
        verifySignature(d);
        switch(mode) {
            case 0:
                // we are done
                break;
            case 'n':
                // Cert constructor generates a null cert
                pkf.setCertType(Certificate.CERTIFICATE_TYPE_NULL);
                System.out.println("New destination with null cert is:");
                break;
            case 'u':
                pkf.setCertType(99);
                System.out.println("New destination with unknown cert is:");
                break;
            case 'x':
                pkf.setCertType(Certificate.CERTIFICATE_TYPE_HIDDEN);
                System.out.println("New destination with hidden cert is:");
                break;
            case 'h':
                System.out.println("Estimating hashcash generation time, stand by...");
                System.out.println(estimateHashCashTime(hashEffort));
                pkf.setHashCashCert(hashEffort);
                System.out.println("New destination with hashcash cert is:");
                break;
            case 's':
                // Sign dest1 with dest2's Signing Private Key
                PrivateKeyFile pkf2 = new PrivateKeyFile(args[g.getOptind() + 1]);
                pkf.setSignedCert(pkf2);
                System.out.println("New destination with signed cert is:");
                break;
            case 't':
                // KeyCert
                SigType type = SigType.parseSigType(stype);
                if (type == null)
                    throw new IllegalArgumentException("Signature type " + stype + " is not supported");
                pkf.setKeyCert(type);
                System.out.println("New destination with key cert is:");
                break;
            case 'a':
                // addressbook auth
                OrderedProperties props = new OrderedProperties();
                HostTxtEntry he = new HostTxtEntry(hostname, d.toBase64(), props);
                he.sign(pkf.getSigningPrivKey());
                System.out.println("Addressbook Authentication String:");
                OutputStreamWriter out = new OutputStreamWriter(System.out);
                he.write(out);
                out.flush();
                System.out.println("");
                return;
            default:
                // shouldn't happen
                usage();
                return;
        }
        if (mode != 0) {
            System.out.println(pkf);
            pkf.write();
            verifySignature(pkf.getDestination());
        }
    } catch (I2PException e) {
        e.printStackTrace();
        System.exit(1);
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }
}
Also used : I2PException(net.i2p.I2PException) HostTxtEntry(net.i2p.client.naming.HostTxtEntry) IOException(java.io.IOException) SigType(net.i2p.crypto.SigType) Getopt(gnu.getopt.Getopt) I2PClient(net.i2p.client.I2PClient) OrderedProperties(net.i2p.util.OrderedProperties) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File)

Example 28 with I2PException

use of net.i2p.I2PException 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 29 with I2PException

use of net.i2p.I2PException 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)

Example 30 with I2PException

use of net.i2p.I2PException in project i2p.i2p by i2p.

the class ConnectionPacketHandler method verifySignature.

/**
 * Verify the signature if necessary.
 *
 * @throws I2PException if the signature was necessary and it was invalid
 */
private void verifySignature(Packet packet, Connection con) throws I2PException {
    // verify the signature if necessary
    if (con.getOptions().getRequireFullySigned() || packet.isFlagSet(Packet.FLAG_SYNCHRONIZE | Packet.FLAG_CLOSE)) {
        // we need a valid signature
        Destination from = con.getRemotePeer();
        if (from == null)
            from = packet.getOptionalFrom();
        boolean sigOk = packet.verifySignature(_context, from, null);
        if (!sigOk) {
            throw new I2PException("Received unsigned / forged packet: " + packet);
        }
    }
}
Also used : I2PException(net.i2p.I2PException) Destination(net.i2p.data.Destination)

Aggregations

I2PException (net.i2p.I2PException)39 IOException (java.io.IOException)31 Destination (net.i2p.data.Destination)26 I2PSocket (net.i2p.client.streaming.I2PSocket)15 Properties (java.util.Properties)8 File (java.io.File)7 InterruptedIOException (java.io.InterruptedIOException)7 ConnectException (java.net.ConnectException)7 I2PAppThread (net.i2p.util.I2PAppThread)7 OutputStream (java.io.OutputStream)6 I2PClient (net.i2p.client.I2PClient)6 I2PSocketOptions (net.i2p.client.streaming.I2PSocketOptions)6 DataFormatException (net.i2p.data.DataFormatException)6 ByteArrayInputStream (java.io.ByteArrayInputStream)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 I2PSession (net.i2p.client.I2PSession)5 I2PSessionException (net.i2p.client.I2PSessionException)5 I2PServerSocket (net.i2p.client.streaming.I2PServerSocket)5 Hash (net.i2p.data.Hash)5 NoRouteToHostException (java.net.NoRouteToHostException)4