Search in sources :

Example 6 with DataFormatException

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

the class KRPC method messageAvailable.

// I2PSessionMuxedListener interface ----------------
/**
 * Instruct the client that the given session has received a message
 *
 * Will be called only if you register via addMuxedSessionListener().
 * Will be called only for the proto(s) and toPort(s) you register for.
 *
 * @param session session to notify
 * @param msgId message number available
 * @param size size of the message - why it's a long and not an int is a mystery
 * @param proto 1-254 or 0 for unspecified
 * @param fromPort 1-65535 or 0 for unspecified
 * @param toPort 1-65535 or 0 for unspecified
 */
public void messageAvailable(I2PSession session, int msgId, long size, int proto, int fromPort, int toPort) {
    // TODO throttle
    try {
        byte[] payload = session.receiveMessage(msgId);
        if (payload == null)
            return;
        _rxPkts.incrementAndGet();
        _rxBytes.addAndGet(payload.length);
        if (toPort == _qPort) {
            // repliable
            I2PDatagramDissector dgDiss = new I2PDatagramDissector();
            dgDiss.loadI2PDatagram(payload);
            payload = dgDiss.getPayload();
            Destination from = dgDiss.getSender();
            // TODO per-dest throttle
            receiveMessage(from, fromPort, payload);
        } else if (toPort == _rPort) {
            // raw
            receiveMessage(null, fromPort, payload);
        } else {
            if (_log.shouldLog(Log.WARN))
                _log.warn("msg on bad port");
        }
    } catch (DataFormatException e) {
        if (_log.shouldLog(Log.WARN))
            _log.warn("bad msg");
    } catch (I2PInvalidDatagramException e) {
        if (_log.shouldLog(Log.WARN))
            _log.warn("bad msg");
    } catch (I2PSessionException e) {
        if (_log.shouldLog(Log.WARN))
            _log.warn("bad msg");
    }
}
Also used : Destination(net.i2p.data.Destination) I2PDatagramDissector(net.i2p.client.datagram.I2PDatagramDissector) DataFormatException(net.i2p.data.DataFormatException) I2PSessionException(net.i2p.client.I2PSessionException) I2PInvalidDatagramException(net.i2p.client.datagram.I2PInvalidDatagramException)

Example 7 with DataFormatException

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

the class PluginUpdateRunner method processSUD.

/**
 *  @since 0.9.15
 *  @return success
 */
private void processSUD(File f, File appDir, String url) {
    TrustedUpdate up = new TrustedUpdate(_context);
    File to = new File(_context.getTempDir(), "tmp" + _context.random().nextInt() + ZIP);
    // extract to a zip file whether the sig is good or not, so we can get the properties file
    String err = up.migrateFile(f, to);
    if (err != null) {
        statusDone("<b>" + err + ' ' + _t("from {0}", url) + " </b>");
        f.delete();
        to.delete();
        return;
    }
    Properties props = getPluginConfig(f, to, url);
    if (props == null)
        return;
    // ok, now we check sigs and deal with a bad sig
    String pubkey = props.getProperty("key");
    String signer = DataHelper.stripHTML(props.getProperty("signer"));
    if (pubkey == null || signer == null || pubkey.length() != 172 || signer.length() <= 0) {
        f.delete();
        to.delete();
        // updateStatus("<b>" + "Plugin contains an invalid key" + ' ' + pubkey + ' ' + signer + "</b>");
        statusDone("<b>" + _t("Plugin from {0} contains an invalid key", url) + "</b>");
        return;
    }
    SigningPublicKey spk;
    try {
        spk = new SigningPublicKey(pubkey);
    } catch (DataFormatException dfe) {
        f.delete();
        to.delete();
        statusDone("<b>" + _t("Plugin from {0} contains an invalid key", url) + "</b>");
        return;
    }
    // add all existing plugin keys, so any conflicts with existing keys
    // will be discovered and rejected
    Map<String, String> existingKeys = PluginStarter.getPluginKeys(_context);
    for (Map.Entry<String, String> e : existingKeys.entrySet()) {
        // ignore dups/bad keys
        up.addKey(e.getKey(), e.getValue());
    }
    // add all trusted plugin keys, so any conflicts with trusted keys
    // will be discovered and rejected
    Map<String, String> trustedKeys = TrustedPluginKeys.getKeys();
    for (Map.Entry<String, String> e : trustedKeys.entrySet()) {
        // ignore dups/bad keys
        up.addKey(e.getKey(), e.getValue());
    }
    if (up.haveKey(pubkey)) {
        // the key is already in the TrustedUpdate keyring
        // verify the sig and verify that it is signed by the signer in the plugin.config file
        // Allow "" as the previously-known signer
        boolean ok = up.verify(f, spk);
        String signingKeyName = up.getKeys().get(spk);
        if ((!ok) || !(signer.equals(signingKeyName) || "".equals(signingKeyName))) {
            f.delete();
            to.delete();
            if (signingKeyName == null)
                _log.error("Failed to verify plugin signature, corrupt plugin or bad signature, signed by: " + signer);
            else
                _log.error("Plugin signer \"" + signer + "\" does not match existing signer in plugin.config file \"" + signingKeyName + "\"");
            statusDone("<b>" + _t("Plugin signature verification of {0} failed", url) + "</b>");
            return;
        }
    } else if (_context.getBooleanProperty(PROP_ALLOW_NEW_KEYS)) {
        // add to keyring...
        if (!up.addKey(pubkey, signer)) {
            // bad or duplicate key
            f.delete();
            to.delete();
            _log.error("Bad key or key mismatch - Failed to add plugin key \"" + pubkey + "\" for plugin signer \"" + signer + "\"");
            statusDone("<b>" + _t("Plugin signature verification of {0} failed", url) + "</b>");
            return;
        }
        // ...and try the verify again
        // verify the sig and verify that it is signed by the signer in the plugin.config file
        String signingKeyName = up.verifyAndGetSigner(f);
        if (!signer.equals(signingKeyName)) {
            f.delete();
            to.delete();
            if (signingKeyName == null)
                _log.error("Failed to verify plugin signature, corrupt plugin or bad signature, signed by: " + signer);
            else
                // shouldn't happen
                _log.error("Plugin signer \"" + signer + "\" does not match new signer in plugin.config file \"" + signingKeyName + "\"");
            statusDone("<b>" + _t("Plugin signature verification of {0} failed", url) + "</b>");
            return;
        }
    } else {
        // unknown key
        f.delete();
        to.delete();
        _log.error("Untrusted plugin key \"" + pubkey + "\" for plugin signer \"" + signer + "\"");
        // don't display signer, we're really checking the key not the signer name
        statusDone("<b>" + _t("Plugin not installed - signer is untrusted") + "</b>");
        return;
    }
    String sudVersion = TrustedUpdate.getVersionString(f);
    f.delete();
    processFinal(to, appDir, url, props, sudVersion, pubkey, signer);
}
Also used : SigningPublicKey(net.i2p.data.SigningPublicKey) DataFormatException(net.i2p.data.DataFormatException) TrustedUpdate(net.i2p.crypto.TrustedUpdate) OrderedProperties(net.i2p.util.OrderedProperties) Properties(java.util.Properties) SecureFile(net.i2p.util.SecureFile) SU3File(net.i2p.crypto.SU3File) File(java.io.File) Map(java.util.Map)

Example 8 with DataFormatException

use of net.i2p.data.DataFormatException 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 9 with DataFormatException

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

the class StreamSinkServer method runServer.

/**
 * Actually fire up the server - this call blocks forever (or until the server
 * socket closes)
 */
public void runServer() {
    I2PSocketManager mgr = null;
    if (_i2cpHost != null)
        mgr = I2PSocketManagerFactory.createManager(_i2cpHost, _i2cpPort, new Properties());
    else
        mgr = I2PSocketManagerFactory.createManager();
    Destination dest = mgr.getSession().getMyDestination();
    if (_log.shouldLog(Log.INFO))
        _log.info("Listening for connections on: " + dest.calculateHash().toBase64());
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(_destFile);
        dest.writeBytes(fos);
    } catch (IOException ioe) {
        _log.error("Error writing out our destination to " + _destFile, ioe);
        return;
    } catch (DataFormatException dfe) {
        _log.error("Error formatting the destination", dfe);
        return;
    } finally {
        if (fos != null)
            try {
                fos.close();
            } catch (IOException ioe) {
            }
    }
    I2PServerSocket sock = mgr.getServerSocket();
    startup(sock);
}
Also used : Destination(net.i2p.data.Destination) DataFormatException(net.i2p.data.DataFormatException) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) Properties(java.util.Properties)

Example 10 with DataFormatException

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

the class SU3File method verifyHeader.

/**
 *  This does not check the signature, but it will fail if the signer is unknown,
 *  unless setVerifySignature(false) has been called.
 *
 *  Throws IOE if verify vails.
 */
public void verifyHeader() throws IOException {
    if (_headerVerified)
        return;
    InputStream in = null;
    try {
        in = new FileInputStream(_file);
        verifyHeader(in);
    } catch (DataFormatException dfe) {
        IOException ioe = new IOException("foo");
        ioe.initCause(dfe);
        throw ioe;
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (IOException ioe) {
            }
    }
}
Also used : DataFormatException(net.i2p.data.DataFormatException) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) DigestInputStream(java.security.DigestInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream)

Aggregations

DataFormatException (net.i2p.data.DataFormatException)112 IOException (java.io.IOException)53 Destination (net.i2p.data.Destination)32 Properties (java.util.Properties)19 ByteArrayOutputStream (java.io.ByteArrayOutputStream)17 FileInputStream (java.io.FileInputStream)16 Hash (net.i2p.data.Hash)14 File (java.io.File)13 SigType (net.i2p.crypto.SigType)13 I2PSessionException (net.i2p.client.I2PSessionException)12 InputStream (java.io.InputStream)11 PrivateKey (net.i2p.data.PrivateKey)11 SigningPrivateKey (net.i2p.data.SigningPrivateKey)11 SigningPublicKey (net.i2p.data.SigningPublicKey)11 RouterInfo (net.i2p.data.router.RouterInfo)11 Signature (net.i2p.data.Signature)10 FileOutputStream (java.io.FileOutputStream)8 InterruptedIOException (java.io.InterruptedIOException)8 HashMap (java.util.HashMap)8 PublicKey (net.i2p.data.PublicKey)8