Search in sources :

Example 21 with Destination

use of net.i2p.data.Destination 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 22 with Destination

use of net.i2p.data.Destination 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 23 with Destination

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

the class TunnelController method getDestination.

/**
 *  Returns null if not running.
 *  @return Destination or null
 *  @since 0.9.17
 */
public Destination getDestination() {
    if (_tunnel != null) {
        List<I2PSession> sessions = _tunnel.getSessions();
        for (int i = 0; i < sessions.size(); i++) {
            I2PSession session = sessions.get(i);
            Destination dest = session.getMyDestination();
            if (dest != null)
                return dest;
        }
    }
    return null;
}
Also used : Destination(net.i2p.data.Destination) I2PSession(net.i2p.client.I2PSession)

Example 24 with Destination

use of net.i2p.data.Destination 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 25 with Destination

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

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