Search in sources :

Example 31 with RouterInfo

use of net.i2p.data.router.RouterInfo in project i2p.i2p by i2p.

the class OutboundReceiver method receiveEncrypted.

public long receiveEncrypted(byte[] encrypted) {
    TunnelDataMessage msg = new TunnelDataMessage(_context);
    msg.setData(encrypted);
    msg.setTunnelId(_config.getConfig(0).getSendTunnel());
    if (_log.shouldLog(Log.DEBUG))
        _log.debug("received encrypted, sending out " + _config + ": " + msg);
    RouterInfo ri = _nextHopCache;
    if (ri == null)
        ri = _context.netDb().lookupRouterInfoLocally(_config.getPeer(1));
    if (ri != null) {
        _nextHopCache = ri;
        send(msg, ri);
        return msg.getUniqueId();
    } else {
        // It should be rare to forget the router info for a peer in our own tunnel.
        if (_log.shouldLog(Log.WARN))
            _log.warn("lookup of " + _config.getPeer(1) + " required for " + msg);
        _context.netDb().lookupRouterInfo(_config.getPeer(1), new SendJob(_context, msg), new FailedJob(_context), MAX_LOOKUP_TIME);
        return -1;
    }
}
Also used : RouterInfo(net.i2p.data.router.RouterInfo) TunnelDataMessage(net.i2p.data.i2np.TunnelDataMessage)

Example 32 with RouterInfo

use of net.i2p.data.router.RouterInfo in project i2p.i2p by i2p.

the class UDPTransport method pickTestPeer.

/**
 *  Pick a Bob (if we are Alice) or a Charlie (if we are Bob).
 *
 *  For Bob (as called from PeerTestEvent below), returns an established IPv4/v6 peer.
 *  While the protocol allows Alice to select an unestablished Bob, we don't support that.
 *
 *  For Charlie (as called from PeerTestManager), returns an established IPv4 or IPv6 peer.
 *  (doesn't matter how Bob and Charlie communicate)
 *
 *  Any returned peer must advertise an IPv4 address to prove it is IPv4-capable.
 *  Ditto for v6.
 *
 *  @param peerRole The role of the peer we are looking for, BOB or CHARLIE only (NOT our role)
 *  @param isIPv6 true to get a v6-capable peer back
 *  @param dontInclude may be null
 *  @return IPv4 peer or null
 */
PeerState pickTestPeer(PeerTestState.Role peerRole, boolean isIPv6, RemoteHostId dontInclude) {
    if (peerRole == ALICE)
        throw new IllegalArgumentException();
    List<PeerState> peers = new ArrayList<PeerState>(_peersByIdent.values());
    for (Iterator<PeerState> iter = new RandomIterator<PeerState>(peers); iter.hasNext(); ) {
        PeerState peer = iter.next();
        if ((dontInclude != null) && (dontInclude.equals(peer.getRemoteHostId())))
            continue;
        // enforce IPv4/v6 connection if we are ALICE looking for a BOB
        byte[] ip = peer.getRemoteIP();
        if (peerRole == BOB) {
            if (isIPv6) {
                if (ip.length != 16)
                    continue;
            } else {
                if (ip.length != 4)
                    continue;
            }
        }
        // enforce IPv4/v6 advertised for all
        RouterInfo peerInfo = _context.netDb().lookupRouterInfoLocally(peer.getRemotePeer());
        if (peerInfo == null)
            continue;
        if (isIPv6) {
            String v = peerInfo.getVersion();
            if (VersionComparator.comp(v, MIN_V6_PEER_TEST_VERSION) < 0)
                continue;
        }
        ip = null;
        List<RouterAddress> addrs = getTargetAddresses(peerInfo);
        for (RouterAddress addr : addrs) {
            byte[] rip = addr.getIP();
            if (rip != null) {
                if (isIPv6) {
                    if (rip.length != 16)
                        continue;
                } else {
                    if (rip.length != 4)
                        continue;
                }
                // as of 0.9.27, we trust the 'B' cap for IPv6
                String caps = addr.getOption(UDPAddress.PROP_CAPACITY);
                if (caps != null && caps.contains(CAP_TESTING)) {
                    ip = rip;
                    break;
                }
            }
        }
        if (ip == null)
            continue;
        if (isTooClose(ip))
            continue;
        return peer;
    }
    return null;
}
Also used : RouterInfo(net.i2p.data.router.RouterInfo) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) RouterAddress(net.i2p.data.router.RouterAddress) RandomIterator(net.i2p.router.util.RandomIterator)

Example 33 with RouterInfo

use of net.i2p.data.router.RouterInfo in project i2p.i2p by i2p.

the class UDPTransport method bid.

public TransportBid bid(RouterInfo toAddress, long dataSize) {
    if (dataSize > OutboundMessageState.MAX_MSG_SIZE) {
        // NTCP max is lower, so msg will get dropped
        return null;
    }
    Hash to = toAddress.getIdentity().calculateHash();
    PeerState peer = getPeerState(to);
    if (peer != null) {
        if (_log.shouldLog(Log.DEBUG))
            _log.debug("bidding on a message to an established peer: " + peer);
        if (preferUDP())
            return _cachedBid[FAST_PREFERRED_BID];
        else
            return _cachedBid[FAST_BID];
    } else {
        // If we don't have a port, all is lost
        if (_reachabilityStatus == Status.HOSED) {
            markUnreachable(to);
            return null;
        }
        // Validate his SSU address
        RouterAddress addr = getTargetAddress(toAddress);
        if (addr == null) {
            markUnreachable(to);
            return null;
        }
        // Check for supported sig type
        SigType type = toAddress.getIdentity().getSigType();
        if (type == null || !type.isAvailable()) {
            markUnreachable(to);
            return null;
        }
        // Can we connect to them if we are not DSA?
        RouterInfo us = _context.router().getRouterInfo();
        if (us != null) {
            RouterIdentity id = us.getIdentity();
            if (id.getSigType() != SigType.DSA_SHA1) {
                String v = toAddress.getVersion();
                if (VersionComparator.comp(v, MIN_SIGTYPE_VERSION) < 0) {
                    markUnreachable(to);
                    return null;
                }
            }
        }
        if (!allowConnection())
            return _cachedBid[TRANSIENT_FAIL_BID];
        if (_log.shouldLog(Log.DEBUG))
            _log.debug("bidding on a message to an unestablished peer: " + to);
        // Try to maintain at least 5 peers (30 for v6) so we can determine our IP address and
        // we have a selection to run peer tests with.
        // If we are firewalled, and we don't have enough peers that volunteered to
        // also introduce us, also bid aggressively so we are preferred over NTCP.
        // (Otherwise we only talk UDP to those that are firewalled, and we will
        // never get any introducers)
        int count = _peersByIdent.size();
        if (alwaysPreferUDP()) {
            return _cachedBid[SLOW_PREFERRED_BID];
        } else if (count < _min_peers || (_haveIPv6Address && count < _min_v6_peers) || (introducersRequired() && _introManager.introducerCount() < MIN_INTRODUCER_POOL)) {
            // TODO After some time, decide that UDP is blocked/broken and return TRANSIENT_FAIL_BID?
            if (_context.random().nextInt(4) == 0)
                return _cachedBid[SLOWEST_BID];
            else
                return _cachedBid[SLOW_PREFERRED_BID];
        } else if (preferUDP()) {
            return _cachedBid[SLOW_BID];
        } else if (haveCapacity()) {
            if (addr.getCost() > DEFAULT_COST)
                return _cachedBid[SLOWEST_COST_BID];
            else
                return _cachedBid[SLOWEST_BID];
        } else {
            if (addr.getCost() > DEFAULT_COST)
                return _cachedBid[NEAR_CAPACITY_COST_BID];
            else
                return _cachedBid[NEAR_CAPACITY_BID];
        }
    }
}
Also used : RouterInfo(net.i2p.data.router.RouterInfo) RouterIdentity(net.i2p.data.router.RouterIdentity) RouterAddress(net.i2p.data.router.RouterAddress) Hash(net.i2p.data.Hash) SigType(net.i2p.crypto.SigType)

Example 34 with RouterInfo

use of net.i2p.data.router.RouterInfo in project i2p.i2p by i2p.

the class UDPTransport method messageReceived.

/**
 * infinite loop
 *    public RouterAddress getCurrentAddress() {
 *        if (needsRebuild())
 *            rebuildExternalAddress(false);
 *        return super.getCurrentAddress();
 *    }
 **
 */
@Override
public void messageReceived(I2NPMessage inMsg, RouterIdentity remoteIdent, Hash remoteIdentHash, long msToReceive, int bytesReceived) {
    if (inMsg.getType() == DatabaseStoreMessage.MESSAGE_TYPE) {
        DatabaseStoreMessage dsm = (DatabaseStoreMessage) inMsg;
        DatabaseEntry entry = dsm.getEntry();
        if (entry == null)
            return;
        if (entry.getType() == DatabaseEntry.KEY_TYPE_ROUTERINFO && ((RouterInfo) entry).getNetworkId() != _networkID) {
            // this is pre-0.6.1.10, so it isn't going to happen any more
            /*
                if (remoteIdentHash != null) {
                    _context.banlist().banlistRouter(remoteIdentHash, "Sent us a peer from the wrong network");
                    dropPeer(remoteIdentHash);
                    if (_log.shouldLog(Log.ERROR))
                        _log.error("Dropping the peer " + remoteIdentHash
                                   + " because they are in the wrong net");
                } else if (remoteIdent != null) {
                    _context.banlist().banlistRouter(remoteIdent.calculateHash(), "Sent us a peer from the wrong network");
                    dropPeer(remoteIdent.calculateHash());
                    if (_log.shouldLog(Log.ERROR))
                        _log.error("Dropping the peer " + remoteIdent.calculateHash()
                                   + " because they are in the wrong net");
                }
                 */
            Hash peerHash = entry.getHash();
            PeerState peer = getPeerState(peerHash);
            if (peer != null) {
                RemoteHostId remote = peer.getRemoteHostId();
                _dropList.add(remote);
                _context.statManager().addRateData("udp.dropPeerDroplist", 1);
                _context.simpleTimer2().addEvent(new RemoveDropList(remote), DROPLIST_PERIOD);
            }
            markUnreachable(peerHash);
            _context.banlist().banlistRouter(peerHash, "Part of the wrong network, version = " + ((RouterInfo) entry).getVersion());
            // _context.banlist().banlistRouter(peerHash, "Part of the wrong network", STYLE);
            if (peer != null)
                sendDestroy(peer);
            dropPeer(peerHash, false, "wrong network");
            if (_log.shouldLog(Log.WARN))
                _log.warn("Dropping the peer " + peerHash + " because they are in the wrong net: " + entry);
            return;
        } else {
            if (entry.getType() == DatabaseEntry.KEY_TYPE_ROUTERINFO) {
                if (_log.shouldLog(Log.DEBUG))
                    _log.debug("Received an RI from the same net");
            } else {
                if (_log.shouldLog(Log.DEBUG))
                    _log.debug("Received a leaseSet: " + dsm);
            }
        }
    } else {
        if (_log.shouldLog(Log.DEBUG))
            _log.debug("Received another message: " + inMsg.getClass().getName());
    }
    PeerState peer = getPeerState(remoteIdentHash);
    super.messageReceived(inMsg, remoteIdent, remoteIdentHash, msToReceive, bytesReceived);
    if (peer != null)
        peer.expireInboundMessages();
}
Also used : RouterInfo(net.i2p.data.router.RouterInfo) DatabaseStoreMessage(net.i2p.data.i2np.DatabaseStoreMessage) DatabaseEntry(net.i2p.data.DatabaseEntry) Hash(net.i2p.data.Hash)

Example 35 with RouterInfo

use of net.i2p.data.router.RouterInfo in project i2p.i2p by i2p.

the class SSUDemo method loadPeers.

private void loadPeers() {
    File infoDir = getInfoDir();
    if (!infoDir.exists())
        infoDir.mkdirs();
    while (true) {
        File[] peerFiles = infoDir.listFiles();
        if ((peerFiles != null) && (peerFiles.length > 0)) {
            for (int i = 0; i < peerFiles.length; i++) {
                if (peerFiles[i].isFile() && !peerFiles[i].isHidden()) {
                    if (!_us.routerHash().toBase64().equals(peerFiles[i].getName())) {
                        System.out.println("Reading info: " + peerFiles[i].getAbsolutePath());
                        try {
                            FileInputStream in = new FileInputStream(peerFiles[i]);
                            RouterInfo ri = new RouterInfo();
                            ri.readBytes(in);
                            peerRead(ri);
                        } catch (IOException ioe) {
                            System.err.println("Error reading " + peerFiles[i].getAbsolutePath());
                            ioe.printStackTrace();
                        } catch (DataFormatException dfe) {
                            System.err.println("Corrupt " + peerFiles[i].getAbsolutePath());
                            dfe.printStackTrace();
                        }
                    }
                }
            }
        }
        try {
            Thread.sleep(30 * 1000);
        } catch (InterruptedException ie) {
        }
    }
}
Also used : DataFormatException(net.i2p.data.DataFormatException) RouterInfo(net.i2p.data.router.RouterInfo) IOException(java.io.IOException) File(java.io.File) FileInputStream(java.io.FileInputStream)

Aggregations

RouterInfo (net.i2p.data.router.RouterInfo)95 Hash (net.i2p.data.Hash)45 ArrayList (java.util.ArrayList)18 RouterAddress (net.i2p.data.router.RouterAddress)17 DataFormatException (net.i2p.data.DataFormatException)11 IOException (java.io.IOException)10 RouterIdentity (net.i2p.data.router.RouterIdentity)10 DatabaseEntry (net.i2p.data.DatabaseEntry)9 OutNetMessage (net.i2p.router.OutNetMessage)9 File (java.io.File)8 DatabaseStoreMessage (net.i2p.data.i2np.DatabaseStoreMessage)8 Properties (java.util.Properties)7 LeaseSet (net.i2p.data.LeaseSet)6 BigInteger (java.math.BigInteger)5 Date (java.util.Date)5 SigType (net.i2p.crypto.SigType)5 TunnelId (net.i2p.data.TunnelId)5 TunnelInfo (net.i2p.router.TunnelInfo)5 FileOutputStream (java.io.FileOutputStream)4 HashMap (java.util.HashMap)4