Search in sources :

Example 11 with I2PException

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

the class TunnelController method createPrivateKey.

/**
 * @return success
 */
private boolean createPrivateKey() {
    I2PClient client = I2PClientFactory.createClient();
    File keyFile = getPrivateKeyFile();
    if (keyFile == null) {
        log("No filename specified for the private key");
        return false;
    }
    if (keyFile.exists()) {
        // log("Not overwriting existing private keys in " + keyFile.getAbsolutePath());
        return true;
    } else {
        File parent = keyFile.getParentFile();
        if ((parent != null) && (!parent.exists()))
            parent.mkdirs();
    }
    FileOutputStream fos = null;
    try {
        fos = new SecureFileOutputStream(keyFile);
        SigType stype = PREFERRED_SIGTYPE;
        String st = _config.getProperty(OPT_SIG_TYPE);
        if (st != null) {
            SigType type = SigType.parseSigType(st);
            if (type != null && type.isAvailable())
                stype = type;
            else
                log("Unsupported sig type " + st + ", reverting to " + stype);
        }
        Destination dest = client.createDestination(fos, stype);
        String destStr = dest.toBase64();
        log("Private key created and saved in " + keyFile.getAbsolutePath());
        log("You should backup this file in a secure place.");
        log("New destination: " + destStr);
        String b32 = dest.toBase32();
        log("Base32: " + b32);
        File backupDir = new SecureFile(I2PAppContext.getGlobalContext().getConfigDir(), KEY_BACKUP_DIR);
        if (backupDir.isDirectory() || backupDir.mkdir()) {
            String name = b32 + '-' + I2PAppContext.getGlobalContext().clock().now() + ".dat";
            File backup = new File(backupDir, name);
            if (FileUtil.copy(keyFile, backup, false, true)) {
                SecureFileOutputStream.setPerms(backup);
                log("Private key backup saved to " + backup.getAbsolutePath());
            }
        }
    } catch (I2PException ie) {
        if (_log.shouldLog(Log.ERROR))
            _log.error("Error creating new destination", ie);
        log("Error creating new destination: " + ie.getMessage());
        return false;
    } catch (IOException ioe) {
        if (_log.shouldLog(Log.ERROR))
            _log.error("Error creating writing the destination to " + keyFile.getAbsolutePath(), ioe);
        log("Error writing the keys to " + keyFile.getAbsolutePath());
        return false;
    } finally {
        if (fos != null)
            try {
                fos.close();
            } catch (IOException ioe) {
            }
    }
    return true;
}
Also used : I2PException(net.i2p.I2PException) Destination(net.i2p.data.Destination) SecureFile(net.i2p.util.SecureFile) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) FileOutputStream(java.io.FileOutputStream) I2PClient(net.i2p.client.I2PClient) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) IOException(java.io.IOException) SecureFile(net.i2p.util.SecureFile) PrivateKeyFile(net.i2p.data.PrivateKeyFile) File(java.io.File) SigType(net.i2p.crypto.SigType)

Example 12 with I2PException

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

the class I2PTunnelDCCClient method clientConnectionRun.

/**
 *  Accept one connection only.
 */
protected void clientConnectionRun(Socket s) {
    I2PSocket i2ps = null;
    if (_log.shouldLog(Log.INFO))
        _log.info("Opening DCC connection to " + _dest + ':' + _remotePort);
    Destination dest = _context.namingService().lookup(_dest);
    if (dest == null) {
        _log.error("Could not find leaseset for DCC connection to " + _dest + ':' + _remotePort);
        closeSocket(s);
        stop();
        notifyEvent(CONNECT_STOP_EVENT, Integer.valueOf(getLocalPort()));
        return;
    }
    I2PSocketOptions opts = sockMgr.buildOptions();
    opts.setPort(_remotePort);
    try {
        i2ps = createI2PSocket(dest, opts);
        Thread t = new Runner(s, i2ps);
        // we are called from an unlimited thread pool, so run inline
        // t.start();
        t.run();
    } catch (IOException ex) {
        _log.error("Could not make DCC connection to " + _dest + ':' + _remotePort, ex);
        notifyEvent(CONNECT_STOP_EVENT, Integer.valueOf(getLocalPort()));
    } catch (I2PException ex) {
        _log.error("Could not make DCC connection to " + _dest + ':' + _remotePort, ex);
        notifyEvent(CONNECT_STOP_EVENT, Integer.valueOf(getLocalPort()));
    } finally {
        // only because we are running it inline
        closeSocket(s);
        if (i2ps != null) {
            try {
                i2ps.close();
            } catch (IOException ioe) {
            }
        }
    }
    stop();
}
Also used : I2PException(net.i2p.I2PException) Destination(net.i2p.data.Destination) I2PTunnelRunner(net.i2p.i2ptunnel.I2PTunnelRunner) I2PSocket(net.i2p.client.streaming.I2PSocket) I2PSocketOptions(net.i2p.client.streaming.I2PSocketOptions) IOException(java.io.IOException)

Example 13 with I2PException

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

the class I2PSocketEepGet method sendRequest.

/**
 *  Look up the address, get a socket from the I2PSocketManager supplied in the constructor,
 *  and send the request.
 *
 *  @param timeout ignored
 */
@Override
protected void sendRequest(SocketTimeout timeout) throws IOException {
    if (_outputStream == null) {
        File outFile = new File(_outputFile);
        if (outFile.exists())
            _alreadyTransferred = outFile.length();
    }
    if (_proxyIn != null)
        try {
            _proxyIn.close();
        } catch (IOException ioe) {
        }
    if (_proxyOut != null)
        try {
            _proxyOut.close();
        } catch (IOException ioe) {
        }
    if (_socket != null)
        try {
            _socket.close();
        } catch (IOException ioe) {
        }
    try {
        URI url = new URI(_actualURL);
        if ("http".equals(url.getScheme())) {
            String host = url.getHost();
            if (host == null)
                throw new MalformedURLException("no hostname: " + _actualURL);
            int port = url.getPort();
            if (port <= 0 || port > 65535)
                port = 80;
            // as the naming service accepts B64KEY (but not B64KEY.i2p atm)
            if ("i2p".equals(host)) {
                String file = url.getRawPath();
                try {
                    int slash = 1 + file.substring(1).indexOf('/');
                    host = file.substring(1, slash);
                    _actualURL = "http://" + host + file.substring(slash);
                    String query = url.getRawQuery();
                    if (query != null)
                        _actualURL = _actualURL + '?' + query;
                } catch (IndexOutOfBoundsException ioobe) {
                    throw new MalformedURLException("Bad /i2p/ format: " + _actualURL);
                }
            }
            // Use existing I2PSession for lookups.
            // This is much more efficient than using the naming service
            Destination dest;
            I2PSession sess = _socketManager.getSession();
            if (sess != null && !sess.isClosed()) {
                try {
                    if (host.length() == 60 && host.endsWith(".b32.i2p")) {
                        byte[] b = Base32.decode(host.substring(0, 52));
                        if (b != null) {
                            Hash h = Hash.create(b);
                            dest = sess.lookupDest(h, 20 * 1000);
                        } else {
                            dest = null;
                        }
                    } else {
                        dest = sess.lookupDest(host, 20 * 1000);
                    }
                } catch (I2PSessionException ise) {
                    dest = null;
                }
            } else {
                dest = _context.namingService().lookup(host);
            }
            if (dest == null)
                throw new UnknownHostException("Unknown or non-i2p host: " + host);
            // Set the timeouts, using the other existing options in the socket manager
            // This currently duplicates what SocketTimeout is doing in EepGet,
            // but when that's ripped out of EepGet to use setsotimeout, we'll need this.
            Properties props = new Properties();
            props.setProperty(I2PSocketOptions.PROP_CONNECT_TIMEOUT, "" + CONNECT_TIMEOUT);
            props.setProperty(I2PSocketOptions.PROP_READ_TIMEOUT, "" + INACTIVITY_TIMEOUT);
            // This is important - even if the underlying socket doesn't have a connect delay,
            // we want to set it for this connection, so the request headers will go out
            // in the SYN packet, saving one RTT.
            props.setProperty(PROP_CONNECT_DELAY, CONNECT_DELAY);
            I2PSocketOptions opts = _socketManager.buildOptions(props);
            opts.setPort(port);
            _socket = _socketManager.connect(dest, opts);
        } else {
            throw new MalformedURLException("Unsupported protocol: " + _actualURL);
        }
    } catch (URISyntaxException use) {
        IOException ioe = new MalformedURLException("Bad URL");
        ioe.initCause(use);
        throw ioe;
    } catch (I2PException ie) {
        throw new IOException("I2P error", ie);
    }
    _proxyIn = _socket.getInputStream();
    _proxyOut = _socket.getOutputStream();
    // SocketTimeout doesn't take an I2PSocket, but no matter, because we
    // always close our socket in fetch() above.
    // timeout.setSocket(_socket);
    String req = getRequest();
    _proxyOut.write(DataHelper.getUTF8(req));
    _proxyOut.flush();
}
Also used : I2PException(net.i2p.I2PException) Destination(net.i2p.data.Destination) MalformedURLException(java.net.MalformedURLException) UnknownHostException(java.net.UnknownHostException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) Hash(net.i2p.data.Hash) Properties(java.util.Properties) URI(java.net.URI) I2PSession(net.i2p.client.I2PSession) I2PSessionException(net.i2p.client.I2PSessionException) File(java.io.File)

Example 14 with I2PException

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

the class StreamSinkSend method runClient.

/**
 * Actually connect and run the client - this call blocks until completion.
 */
public void runClient() {
    I2PSocketManager 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) {
            }
    }
    System.out.println("Send " + _sendFile + " to " + peer.calculateHash().toBase64());
    try {
        I2PSocket sock = mgr.connect(peer);
        byte[] buf = new byte[32 * 1024];
        OutputStream out = sock.getOutputStream();
        long beforeSending = System.currentTimeMillis();
        fis = new FileInputStream(_sendFile);
        long size = 0;
        while (true) {
            int read = fis.read(buf);
            if (read < 0)
                break;
            out.write(buf, 0, read);
            size += read;
            if (_log.shouldLog(Log.DEBUG))
                _log.debug("Wrote " + read);
            if (_writeDelay > 0) {
                try {
                    Thread.sleep(_writeDelay);
                } catch (InterruptedException ie) {
                }
            }
        }
        fis.close();
        sock.close();
        long afterSending = System.currentTimeMillis();
        System.out.println("Sent " + (size / 1024) + "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) NoRouteToHostException(java.net.NoRouteToHostException) FileInputStream(java.io.FileInputStream) DataFormatException(net.i2p.data.DataFormatException) ConnectException(java.net.ConnectException)

Example 15 with I2PException

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

the class I2PClientImpl method createDestination.

/**
 * Create the destination with the given payload and write it out along with
 * the PrivateKey and SigningPrivateKey to the destKeyStream
 *
 * If cert is a KeyCertificate, the signing keypair will be of the specified type.
 * The KeyCertificate data must be .............................
 * The padding if any will be randomized. The extra key data if any will be set in the
 * key cert.
 *
 * Caller must close stream.
 *
 * @param destKeyStream location to write out the destination, PrivateKey, and SigningPrivateKey,
 *                      format is specified in {@link net.i2p.data.PrivateKeyFile PrivateKeyFile}
 */
public Destination createDestination(OutputStream destKeyStream, Certificate cert) throws I2PException, IOException {
    Destination d = new Destination();
    Object[] keypair = KeyGenerator.getInstance().generatePKIKeypair();
    PublicKey publicKey = (PublicKey) keypair[0];
    PrivateKey privateKey = (PrivateKey) keypair[1];
    SimpleDataStructure[] signingKeys;
    if (cert.getCertificateType() == Certificate.CERTIFICATE_TYPE_KEY) {
        KeyCertificate kcert = cert.toKeyCertificate();
        SigType type = kcert.getSigType();
        try {
            signingKeys = KeyGenerator.getInstance().generateSigningKeys(type);
        } catch (GeneralSecurityException gse) {
            throw new I2PException("keygen fail", gse);
        }
    } else {
        signingKeys = KeyGenerator.getInstance().generateSigningKeys();
    }
    SigningPublicKey signingPubKey = (SigningPublicKey) signingKeys[0];
    SigningPrivateKey signingPrivKey = (SigningPrivateKey) signingKeys[1];
    d.setPublicKey(publicKey);
    d.setSigningPublicKey(signingPubKey);
    if (cert.getCertificateType() == Certificate.CERTIFICATE_TYPE_KEY) {
        // fix up key certificate or padding
        KeyCertificate kcert = cert.toKeyCertificate();
        SigType type = kcert.getSigType();
        int len = type.getPubkeyLen();
        if (len < 128) {
            byte[] pad = new byte[128 - len];
            RandomSource.getInstance().nextBytes(pad);
            d.setPadding(pad);
        } else if (len > 128) {
            System.arraycopy(signingPubKey.getData(), 128, kcert.getPayload(), KeyCertificate.HEADER_LENGTH, len - 128);
        }
    }
    d.setCertificate(cert);
    d.writeBytes(destKeyStream);
    privateKey.writeBytes(destKeyStream);
    signingPrivKey.writeBytes(destKeyStream);
    destKeyStream.flush();
    return d;
}
Also used : I2PException(net.i2p.I2PException) Destination(net.i2p.data.Destination) SigningPublicKey(net.i2p.data.SigningPublicKey) PrivateKey(net.i2p.data.PrivateKey) SigningPrivateKey(net.i2p.data.SigningPrivateKey) SigningPublicKey(net.i2p.data.SigningPublicKey) PublicKey(net.i2p.data.PublicKey) GeneralSecurityException(java.security.GeneralSecurityException) SigType(net.i2p.crypto.SigType) SigningPrivateKey(net.i2p.data.SigningPrivateKey) KeyCertificate(net.i2p.data.KeyCertificate) SimpleDataStructure(net.i2p.data.SimpleDataStructure)

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