Search in sources :

Example 31 with I2PException

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

the class I2PTunnel method makeKey.

/**
 * Create a new destination, storing the destination and its private keys where
 * instructed.
 * Does NOT support non-default sig types.
 * Deprecated - only used by CLI
 *
 * @param writeTo location to store the destination and private keys
 * @param pubDest location to store the destination
 * @param l logger to send messages to
 */
private static void makeKey(OutputStream writeTo, OutputStream pubDest, Logging l) {
    try {
        l.log("Generating new keys...");
        I2PClient client = I2PClientFactory.createClient();
        Destination d = client.createDestination(writeTo);
        l.log("New destination: " + d.toBase32());
        writeTo.flush();
        writeTo.close();
        writePubKey(d, pubDest, l);
    } catch (I2PException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
Also used : I2PException(net.i2p.I2PException) Destination(net.i2p.data.Destination) I2PClient(net.i2p.client.I2PClient) IOException(java.io.IOException)

Example 32 with I2PException

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

the class I2PTunnel method showKey.

/**
 * Read in the given destination, display it, and write it to the given location
 * Deprecated - only used by CLI
 *
 * @param readFrom stream to read the destination from
 * @param pubDest stream to write the destination to
 * @param l logger to send messages to
 */
private static void showKey(InputStream readFrom, OutputStream pubDest, Logging l) {
    try {
        Destination d = new Destination();
        d.readBytes(readFrom);
        l.log("Destination: " + d.toBase32());
        readFrom.close();
        writePubKey(d, pubDest, l);
    } catch (I2PException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
Also used : I2PException(net.i2p.I2PException) Destination(net.i2p.data.Destination) IOException(java.io.IOException)

Example 33 with I2PException

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

the class I2PTunnelServer method run.

/**
 *  If usePool is set, this starts the executor pool.
 *  Then, do the accept() loop, and either
 *  hands each I2P socket to the executor or runs it in-line.
 */
public void run() {
    i2pss = sockMgr.getServerSocket();
    if (_log.shouldLog(Log.WARN)) {
        if (_usePool)
            _log.warn("Starting executor with " + getHandlerCount() + " threads max");
        else
            _log.warn("Threads disabled, running blockingHandles inline");
    }
    if (_usePool) {
        _executor = new CustomThreadPoolExecutor(getHandlerCount(), "ServerHandler pool " + remoteHost + ':' + remotePort);
    }
    TunnelControllerGroup tcg = TunnelControllerGroup.getInstance();
    if (tcg != null) {
        _clientExecutor = tcg.getClientExecutor();
    } else {
        // Fallback in case TCG.getInstance() is null, never instantiated
        // and we were not started by TCG.
        // Maybe a plugin loaded before TCG? Should be rare.
        // Never shut down.
        _clientExecutor = new TunnelControllerGroup.CustomThreadPoolExecutor();
    }
    I2PSocket i2ps = null;
    while (open) {
        try {
            i2ps = null;
            I2PServerSocket ci2pss = i2pss;
            if (ci2pss == null)
                throw new I2PException("I2PServerSocket closed");
            // returns non-null as of 0.9.17
            i2ps = ci2pss.accept();
            if (_usePool) {
                try {
                    _executor.execute(new Handler(i2ps));
                } catch (RejectedExecutionException ree) {
                    try {
                        i2ps.reset();
                    } catch (IOException ioe) {
                    }
                    if (open)
                        _log.logAlways(Log.WARN, "ServerHandler queue full, dropping incoming connection to " + remoteHost + ':' + remotePort + "; increase server max threads or " + PROP_HANDLER_COUNT + "; current is " + getHandlerCount());
                }
            } else {
                // use only for standard servers that can't get slowlorissed! Not for http or irc
                blockingHandle(i2ps);
            }
        } catch (RouterRestartException rre) {
            // Delay and loop if router is soft restarting
            _log.logAlways(Log.WARN, "Waiting for router restart");
            if (i2ps != null)
                try {
                    i2ps.close();
                } catch (IOException ioe) {
                }
            try {
                Thread.sleep(2 * 60 * 1000);
            } catch (InterruptedException ie) {
            }
            // This should be the same as before, but we have to call getServerSocket()
            // so sockMgr will call ConnectionManager.setAllowIncomingConnections(true) again
            i2pss = sockMgr.getServerSocket();
        } catch (I2PException ipe) {
            if (_log.shouldLog(Log.ERROR))
                _log.error("Error accepting - KILLING THE TUNNEL SERVER", ipe);
            open = false;
            if (i2ps != null)
                try {
                    i2ps.close();
                } catch (IOException ioe) {
                }
            break;
        } catch (ConnectException ce) {
            if (_log.shouldLog(Log.ERROR))
                _log.error("Error accepting", ce);
            open = false;
            if (i2ps != null)
                try {
                    i2ps.close();
                } catch (IOException ioe) {
                }
            break;
        } catch (SocketTimeoutException ste) {
            // ignored, we never set the timeout
            if (i2ps != null)
                try {
                    i2ps.close();
                } catch (IOException ioe) {
                }
        } catch (RuntimeException e) {
            // streaming borkage
            if (_log.shouldLog(Log.ERROR))
                _log.error("Uncaught exception accepting", e);
            if (i2ps != null)
                try {
                    i2ps.close();
                } catch (IOException ioe) {
                }
            // not killing the server..
            try {
                Thread.sleep(500);
            } catch (InterruptedException ie) {
            }
        }
    }
    if (_executor != null && !_executor.isTerminating() && !_executor.isShutdown())
        _executor.shutdownNow();
}
Also used : I2PException(net.i2p.I2PException) I2PSocket(net.i2p.client.streaming.I2PSocket) RouterRestartException(net.i2p.client.streaming.RouterRestartException) IOException(java.io.IOException) I2PServerSocket(net.i2p.client.streaming.I2PServerSocket) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) SocketTimeoutException(java.net.SocketTimeoutException) ConnectException(java.net.ConnectException)

Example 34 with I2PException

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

the class TunnelController method createAltPrivateKey.

/**
 * Creates alternate Destination with the same encryption keys as the primary Destination,
 * but a different signing key.
 *
 * Must have already called createPrivateKey() successfully.
 * Does nothing unless option OPT_ALT_PKF is set with the privkey file name.
 * Does nothing if the file already exists.
 *
 * @return success
 * @since 0.9.30
 */
private boolean createAltPrivateKey() {
    if (PREFERRED_SIGTYPE == SigType.DSA_SHA1)
        return false;
    File keyFile = getPrivateKeyFile();
    if (keyFile == null)
        return false;
    if (!keyFile.exists())
        return false;
    File altFile = getAlternatePrivateKeyFile();
    if (altFile == null)
        return false;
    if (altFile.equals(keyFile))
        return false;
    if (altFile.exists())
        return true;
    PrivateKeyFile pkf = new PrivateKeyFile(keyFile);
    FileOutputStream out = null;
    try {
        Destination dest = pkf.getDestination();
        if (dest == null)
            return false;
        if (dest.getSigType() != SigType.DSA_SHA1)
            return false;
        PublicKey pub = dest.getPublicKey();
        PrivateKey priv = pkf.getPrivKey();
        SimpleDataStructure[] signingKeys = KeyGenerator.getInstance().generateSigningKeys(PREFERRED_SIGTYPE);
        SigningPublicKey signingPubKey = (SigningPublicKey) signingKeys[0];
        SigningPrivateKey signingPrivKey = (SigningPrivateKey) signingKeys[1];
        KeyCertificate cert = new KeyCertificate(signingPubKey);
        Destination d = new Destination();
        d.setPublicKey(pub);
        d.setSigningPublicKey(signingPubKey);
        d.setCertificate(cert);
        int len = signingPubKey.length();
        if (len < 128) {
            byte[] pad = new byte[128 - len];
            RandomSource.getInstance().nextBytes(pad);
            d.setPadding(pad);
        } else if (len > 128) {
        // copy of excess data handled in KeyCertificate constructor
        }
        out = new SecureFileOutputStream(altFile);
        d.writeBytes(out);
        priv.writeBytes(out);
        signingPrivKey.writeBytes(out);
        try {
            out.close();
        } catch (IOException ioe) {
        }
        String destStr = d.toBase64();
        log("Alternate private key created and saved in " + altFile.getAbsolutePath());
        log("You should backup this file in a secure place.");
        log("New alternate destination: " + destStr);
        String b32 = d.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(altFile, backup, false, true)) {
                SecureFileOutputStream.setPerms(backup);
                log("Alternate private key backup saved to " + backup.getAbsolutePath());
            }
        }
        return true;
    } catch (GeneralSecurityException e) {
        log("Error creating keys " + e);
        return false;
    } catch (I2PSessionException e) {
        log("Error creating keys " + e);
        return false;
    } catch (I2PException e) {
        log("Error creating keys " + e);
        return false;
    } catch (IOException e) {
        log("Error creating keys " + e);
        return false;
    } catch (RuntimeException e) {
        log("Error creating keys " + e);
        return false;
    } finally {
        if (out != null)
            try {
                out.close();
            } catch (IOException ioe) {
            }
    }
}
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) SecureFile(net.i2p.util.SecureFile) SigningPublicKey(net.i2p.data.SigningPublicKey) PublicKey(net.i2p.data.PublicKey) GeneralSecurityException(java.security.GeneralSecurityException) PrivateKeyFile(net.i2p.data.PrivateKeyFile) IOException(java.io.IOException) SigningPrivateKey(net.i2p.data.SigningPrivateKey) KeyCertificate(net.i2p.data.KeyCertificate) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) FileOutputStream(java.io.FileOutputStream) I2PSessionException(net.i2p.client.I2PSessionException) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) SecureFile(net.i2p.util.SecureFile) PrivateKeyFile(net.i2p.data.PrivateKeyFile) File(java.io.File) SimpleDataStructure(net.i2p.data.SimpleDataStructure)

Example 35 with I2PException

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

the class SAMv3StreamSession method stopForwardingIncoming.

/**
 *  stop Forwarding Incoming connection coming from I2P
 * @throws SAMException
 * @throws InterruptedIOException
 */
public void stopForwardingIncoming() throws SAMException, InterruptedIOException {
    SessionRecord rec = SAMv3Handler.sSessionsHash.get(nick);
    if (rec == null)
        throw new InterruptedIOException();
    I2PServerSocket server = null;
    synchronized (this.socketServerLock) {
        if (this.socketServer == null) {
            if (_log.shouldLog(Log.DEBUG))
                _log.debug("no socket server is defined for this destination");
            throw new SAMException("no socket server is defined for this destination");
        }
        server = this.socketServer;
        this.socketServer = null;
        if (_log.shouldLog(Log.DEBUG))
            _log.debug("nulling socketServer in stopForwardingIncoming. Object " + this);
    }
    try {
        server.close();
    } catch (I2PException e) {
    }
}
Also used : I2PException(net.i2p.I2PException) InterruptedIOException(java.io.InterruptedIOException) I2PServerSocket(net.i2p.client.streaming.I2PServerSocket)

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