Search in sources :

Example 1 with TunnelBuildReplyMessage

use of net.i2p.data.i2np.TunnelBuildReplyMessage in project i2p.i2p by i2p.

the class BuildHandler method handleReq.

/**
 * If we are dropping lots of requests before even trying to handle them,
 * I suppose you could call us "overloaded"
 */
/**
 ** unused, see handleReq() below
 *    private final static int MAX_PROACTIVE_DROPS = 240;
 *
 *    private int countProactiveDrops() {
 *        int dropped = 0;
 *        dropped += countEvents("tunnel.dropLoadProactive", 60*1000);
 *        dropped += countEvents("tunnel.dropLoad", 60*1000);
 *        dropped += countEvents("tunnel.dropLoadBacklog", 60*1000);
 *        dropped += countEvents("tunnel.dropLoadDelay", 60*1000);
 *        return dropped;
 *    }
 *
 *    private int countEvents(String stat, long period) {
 *        RateStat rs = _context.statManager().getRate(stat);
 *        if (rs != null) {
 *            Rate r = rs.getRate(period);
 *            if (r != null)
 *                return (int)r.getCurrentEventCount();
 *        }
 *        return 0;
 *    }
 ***
 */
/**
 *  Actually process the request and send the reply.
 *
 *  Todo: Replies are not subject to RED for bandwidth reasons,
 *  and the bandwidth is not credited to any tunnel.
 *  If we did credit the reply to the tunnel, it would
 *  prevent the classification of the tunnel as 'inactive' on tunnels.jsp.
 */
private void handleReq(RouterInfo nextPeerInfo, BuildMessageState state, BuildRequestRecord req, Hash nextPeer) {
    long ourId = req.readReceiveTunnelId();
    long nextId = req.readNextTunnelId();
    boolean isInGW = req.readIsInboundGateway();
    boolean isOutEnd = req.readIsOutboundEndpoint();
    Hash from = state.fromHash;
    if (from == null && state.from != null)
        from = state.from.calculateHash();
    if (isInGW && isOutEnd) {
        _context.statManager().addRateData("tunnel.rejectHostile", 1);
        _log.error("Dropping build request, IBGW+OBEP: " + req);
        if (from != null)
            _context.commSystem().mayDisconnect(from);
        return;
    }
    if (ourId <= 0 || ourId > TunnelId.MAX_ID_VALUE || nextId <= 0 || nextId > TunnelId.MAX_ID_VALUE) {
        _context.statManager().addRateData("tunnel.rejectHostile", 1);
        if (_log.shouldWarn())
            _log.warn("Dropping build request, bad tunnel ID: " + req);
        if (from != null)
            _context.commSystem().mayDisconnect(from);
        return;
    }
    // Loop checks
    if ((!isOutEnd) && _context.routerHash().equals(nextPeer)) {
        _context.statManager().addRateData("tunnel.rejectHostile", 1);
        // old i2pd
        if (_log.shouldWarn())
            _log.warn("Dropping build request, we are the next hop: " + req);
        if (from != null)
            _context.commSystem().mayDisconnect(from);
        return;
    }
    if (!isInGW) {
        // but if not, something is seriously wrong here.
        if (from == null || _context.routerHash().equals(from)) {
            _context.statManager().addRateData("tunnel.rejectHostile", 1);
            if (_log.shouldWarn())
                _log.warn("Dropping build request, we are the previous hop: " + req);
            return;
        }
    }
    if ((!isOutEnd) && (!isInGW)) {
        // A-B-C-A is not preventable
        if (nextPeer.equals(from)) {
            // i2pd does this
            _context.statManager().addRateData("tunnel.rejectHostile", 1);
            if (_log.shouldLog(Log.WARN))
                _log.warn("Dropping build request with the same previous and next hop: " + req);
            _context.commSystem().mayDisconnect(from);
            return;
        }
    }
    // time is in hours, rounded down.
    // tunnel-alt-creation.html specifies that this is enforced +/- 1 hour but it was not.
    // As of 0.9.16, allow + 5 minutes to - 65 minutes.
    long time = req.readRequestTime();
    long now = (_context.clock().now() / (60l * 60l * 1000l)) * (60 * 60 * 1000);
    long timeDiff = now - time;
    if (timeDiff > MAX_REQUEST_AGE) {
        _context.statManager().addRateData("tunnel.rejectTooOld", 1);
        if (_log.shouldLog(Log.WARN))
            _log.warn("Dropping build request too old... replay attack? " + DataHelper.formatDuration(timeDiff) + ": " + req);
        if (from != null)
            _context.commSystem().mayDisconnect(from);
        return;
    }
    if (timeDiff < 0 - MAX_REQUEST_FUTURE) {
        _context.statManager().addRateData("tunnel.rejectFuture", 1);
        if (_log.shouldLog(Log.WARN))
            _log.warn("Dropping build request too far in future " + DataHelper.formatDuration(0 - timeDiff) + ": " + req);
        if (from != null)
            _context.commSystem().mayDisconnect(from);
        return;
    }
    int response;
    if (_context.router().isHidden()) {
        _context.throttle().setTunnelStatus(_x("Rejecting tunnels: Hidden mode"));
        response = TunnelHistory.TUNNEL_REJECT_BANDWIDTH;
    } else {
        response = _context.throttle().acceptTunnelRequest();
    }
    // This only checked OUR tunnels, so the log message was wrong.
    // Now checked by TunnelDispatcher.joinXXX()
    // and returned as success value, checked below.
    // if (_context.tunnelManager().getTunnelInfo(new TunnelId(ourId)) != null) {
    // if (_log.shouldLog(Log.ERROR))
    // _log.error("Already participating in a tunnel with the given Id (" + ourId + "), so gotta reject");
    // if (response == 0)
    // response = TunnelHistory.TUNNEL_REJECT_PROBABALISTIC_REJECT;
    // }
    // if ( (response == 0) && (_context.random().nextInt(50) <= 1) )
    // response = TunnelHistory.TUNNEL_REJECT_PROBABALISTIC_REJECT;
    long recvDelay = _context.clock().now() - state.recvTime;
    if (response == 0) {
        // unused
        // int proactiveDrops = countProactiveDrops();
        float pDrop = ((float) recvDelay) / (float) (BuildRequestor.REQUEST_TIMEOUT * 3);
        pDrop = (float) Math.pow(pDrop, 16);
        if (_context.random().nextFloat() < pDrop) {
            // || (proactiveDrops > MAX_PROACTIVE_DROPS) ) ) {
            _context.statManager().addRateData("tunnel.rejectOverloaded", recvDelay);
            _context.throttle().setTunnelStatus(_x("Rejecting tunnels: Request overload"));
            // if (true || (proactiveDrops < MAX_PROACTIVE_DROPS*2))
            response = TunnelHistory.TUNNEL_REJECT_TRANSIENT_OVERLOAD;
        // else
        // response = TunnelHistory.TUNNEL_REJECT_BANDWIDTH;
        } else {
            _context.statManager().addRateData("tunnel.acceptLoad", recvDelay);
        }
    }
    /*
         * Being a IBGW or OBEP generally leads to more connections, so if we are
         * approaching our connection limit (i.e. !haveCapacity()),
         * reject this request.
         *
         * Don't do this for class N or O, under the assumption that they are already talking
         * to most of the routers, so there's no reason to reject. This may drive them
         * to their conn. limits, but it's hopefully a temporary solution to the
         * tunnel build congestion. As the net grows this will have to be revisited.
         */
    RouterInfo ri = _context.router().getRouterInfo();
    if (response == 0) {
        if (ri == null) {
            // ?? We should always have a RI
            response = TunnelHistory.TUNNEL_REJECT_BANDWIDTH;
        } else {
            char bw = ri.getBandwidthTier().charAt(0);
            if (bw != 'O' && bw != 'N' && bw != 'P' && bw != 'X' && ((isInGW && !_context.commSystem().haveInboundCapacity(87)) || (isOutEnd && !_context.commSystem().haveOutboundCapacity(87)))) {
                _context.statManager().addRateData("tunnel.rejectConnLimits", 1);
                _context.throttle().setTunnelStatus(_x("Rejecting tunnels: Connection limit"));
                response = TunnelHistory.TUNNEL_REJECT_BANDWIDTH;
            }
        }
    }
    // We may need another counter above for requests.
    if (response == 0 && !isInGW) {
        if (from != null && _throttler.shouldThrottle(from)) {
            if (_log.shouldLog(Log.WARN))
                _log.warn("Rejecting tunnel (hop throttle), previous hop: " + from + ": " + req);
            // no setTunnelStatus() indication
            _context.statManager().addRateData("tunnel.rejectHopThrottle", 1);
            response = TunnelHistory.TUNNEL_REJECT_BANDWIDTH;
        }
    }
    if (response == 0 && (!isOutEnd) && _throttler.shouldThrottle(nextPeer)) {
        if (_log.shouldLog(Log.WARN))
            _log.warn("Rejecting tunnel (hop throttle), next hop: " + req);
        _context.statManager().addRateData("tunnel.rejectHopThrottle", 1);
        // no setTunnelStatus() indication
        response = TunnelHistory.TUNNEL_REJECT_BANDWIDTH;
    }
    HopConfig cfg = null;
    if (response == 0) {
        cfg = new HopConfig();
        cfg.setCreation(_context.clock().now());
        cfg.setExpiration(_context.clock().now() + 10 * 60 * 1000);
        cfg.setIVKey(req.readIVKey());
        cfg.setLayerKey(req.readLayerKey());
        if (isInGW) {
        // default
        // cfg.setReceiveFrom(null);
        } else {
            if (from != null) {
                cfg.setReceiveFrom(from);
            } else {
                // b0rk
                return;
            }
        }
        cfg.setReceiveTunnelId(DataHelper.toLong(4, ourId));
        if (isOutEnd) {
        // default
        // cfg.setSendTo(null);
        // cfg.setSendTunnelId(null);
        } else {
            cfg.setSendTo(nextPeer);
            cfg.setSendTunnelId(DataHelper.toLong(4, nextId));
        }
        // now "actually" join
        boolean success;
        if (isOutEnd)
            success = _context.tunnelDispatcher().joinOutboundEndpoint(cfg);
        else if (isInGW)
            success = _context.tunnelDispatcher().joinInboundGateway(cfg);
        else
            success = _context.tunnelDispatcher().joinParticipant(cfg);
        if (success) {
            if (_log.shouldLog(Log.DEBUG))
                _log.debug("Joining: " + req);
        } else {
            // Dup Tunnel ID. This can definitely happen (birthday paradox).
            // Probability in 11 minutes (per hop type):
            // 0.1% for 2900 tunnels; 1% for 9300 tunnels
            response = TunnelHistory.TUNNEL_REJECT_BANDWIDTH;
            _context.statManager().addRateData("tunnel.rejectDupID", 1);
            if (_log.shouldLog(Log.WARN))
                _log.warn("DUP ID failure: " + req);
        }
    }
    if (response != 0) {
        _context.statManager().addRateData("tunnel.reject." + response, 1);
        _context.messageHistory().tunnelRejected(from, new TunnelId(ourId), nextPeer, // (isOutEnd ? "outbound endpoint" : isInGW ? "inbound gw" : "participant"));
        Integer.toString(response));
        if (from != null)
            _context.commSystem().mayDisconnect(from);
        // 81% = between 75% control measures in Transports and 87% rejection above
        if ((!_context.routerHash().equals(nextPeer)) && (!_context.commSystem().haveOutboundCapacity(81)) && (!_context.commSystem().isEstablished(nextPeer))) {
            _context.statManager().addRateData("tunnel.dropConnLimits", 1);
            if (_log.shouldLog(Log.WARN))
                _log.warn("Not sending rejection due to conn limits: " + req);
            return;
        }
    } else if (isInGW && from != null) {
        // we're the start of the tunnel, no use staying connected
        _context.commSystem().mayDisconnect(from);
    }
    if (_log.shouldLog(Log.DEBUG))
        _log.debug("Responding to " + state.msg.getUniqueId() + " after " + recvDelay + " with " + response + " from " + (from != null ? from : "tunnel") + ": " + req);
    EncryptedBuildRecord reply = BuildResponseRecord.create(_context, response, req.readReplyKey(), req.readReplyIV(), state.msg.getUniqueId());
    int records = state.msg.getRecordCount();
    int ourSlot = -1;
    for (int j = 0; j < records; j++) {
        if (state.msg.getRecord(j) == null) {
            ourSlot = j;
            state.msg.setRecord(j, reply);
            // + ": " + Base64.encode(reply));
            break;
        }
    }
    if (_log.shouldLog(Log.DEBUG))
        _log.debug("Read slot " + ourSlot + " containing: " + req + " accepted? " + response + " recvDelay " + recvDelay + " replyMessage " + req.readReplyMessageId());
    // now actually send the response
    long expires = _context.clock().now() + NEXT_HOP_SEND_TIMEOUT;
    if (!isOutEnd) {
        state.msg.setUniqueId(req.readReplyMessageId());
        state.msg.setMessageExpiration(expires);
        OutNetMessage msg = new OutNetMessage(_context, state.msg, expires, PRIORITY, nextPeerInfo);
        if (response == 0)
            msg.setOnFailedSendJob(new TunnelBuildNextHopFailJob(_context, cfg));
        _context.outNetMessagePool().add(msg);
    } else {
        // We are the OBEP.
        // send it to the reply tunnel on the reply peer within a new TunnelBuildReplyMessage
        // (enough layers jrandom?)
        TunnelBuildReplyMessage replyMsg;
        if (records == TunnelBuildMessage.MAX_RECORD_COUNT)
            replyMsg = new TunnelBuildReplyMessage(_context);
        else
            replyMsg = new VariableTunnelBuildReplyMessage(_context, records);
        for (int i = 0; i < records; i++) replyMsg.setRecord(i, state.msg.getRecord(i));
        replyMsg.setUniqueId(req.readReplyMessageId());
        replyMsg.setMessageExpiration(expires);
        TunnelGatewayMessage m = new TunnelGatewayMessage(_context);
        m.setMessage(replyMsg);
        m.setMessageExpiration(expires);
        m.setTunnelId(new TunnelId(nextId));
        if (_context.routerHash().equals(nextPeer)) {
            // ok, we are the gateway, so inject it
            if (_log.shouldLog(Log.DEBUG))
                _log.debug("We are the reply gateway for " + nextId + " when replying to replyMessage " + req);
            _context.tunnelDispatcher().dispatch(m);
        } else {
            // ok, the gateway is some other peer, shove 'er across
            OutNetMessage outMsg = new OutNetMessage(_context, m, expires, PRIORITY, nextPeerInfo);
            if (response == 0)
                outMsg.setOnFailedSendJob(new TunnelBuildNextHopFailJob(_context, cfg));
            _context.outNetMessagePool().add(outMsg);
        }
    }
}
Also used : EncryptedBuildRecord(net.i2p.data.i2np.EncryptedBuildRecord) TunnelGatewayMessage(net.i2p.data.i2np.TunnelGatewayMessage) RouterInfo(net.i2p.data.router.RouterInfo) HopConfig(net.i2p.router.tunnel.HopConfig) Hash(net.i2p.data.Hash) TunnelId(net.i2p.data.TunnelId) VariableTunnelBuildReplyMessage(net.i2p.data.i2np.VariableTunnelBuildReplyMessage) TunnelBuildReplyMessage(net.i2p.data.i2np.TunnelBuildReplyMessage) VariableTunnelBuildReplyMessage(net.i2p.data.i2np.VariableTunnelBuildReplyMessage) OutNetMessage(net.i2p.router.OutNetMessage)

Example 2 with TunnelBuildReplyMessage

use of net.i2p.data.i2np.TunnelBuildReplyMessage in project i2p.i2p by i2p.

the class BuildHandler method handleRequestAsInboundEndpoint.

/**
 * This request is actually a reply, process it as such
 */
private void handleRequestAsInboundEndpoint(BuildEndMessageState state) {
    int records = state.msg.getRecordCount();
    TunnelBuildReplyMessage msg;
    if (records == TunnelBuildMessage.MAX_RECORD_COUNT)
        msg = new TunnelBuildReplyMessage(_context);
    else
        msg = new VariableTunnelBuildReplyMessage(_context, records);
    for (int i = 0; i < records; i++) msg.setRecord(i, state.msg.getRecord(i));
    msg.setUniqueId(state.msg.getUniqueId());
    handleReply(msg, state.cfg, System.currentTimeMillis() - state.recvTime);
}
Also used : TunnelBuildReplyMessage(net.i2p.data.i2np.TunnelBuildReplyMessage) VariableTunnelBuildReplyMessage(net.i2p.data.i2np.VariableTunnelBuildReplyMessage) VariableTunnelBuildReplyMessage(net.i2p.data.i2np.VariableTunnelBuildReplyMessage)

Example 3 with TunnelBuildReplyMessage

use of net.i2p.data.i2np.TunnelBuildReplyMessage in project i2p.i2p by i2p.

the class BuildMessageTestStandalone method testBuildMessage.

public void testBuildMessage() {
    I2PAppContext ctx = I2PAppContext.getGlobalContext();
    Log log = ctx.logManager().getLog(getClass());
    List<Integer> order = pickOrder();
    TunnelCreatorConfig cfg = createConfig(ctx);
    _replyRouter = new Hash();
    byte[] h = new byte[Hash.HASH_LENGTH];
    Arrays.fill(h, (byte) 0xFF);
    _replyRouter.setData(h);
    _replyTunnel = 42;
    // populate and encrypt the message
    TunnelBuildMessage msg = new TunnelBuildMessage(ctx);
    for (int i = 0; i < order.size(); i++) {
        int hop = order.get(i).intValue();
        PublicKey key = null;
        if (hop < _pubKeys.length)
            key = _pubKeys[hop];
        BuildMessageGenerator.createRecord(i, hop, msg, cfg, _replyRouter, _replyTunnel, ctx, key);
    }
    BuildMessageGenerator.layeredEncrypt(ctx, msg, cfg, order);
    log.debug("\n================================================================" + "\nMessage fully encrypted" + "\n================================================================");
    // now msg is fully encrypted, so lets go through the hops, decrypting and replying
    // as necessary
    BuildMessageProcessor proc = new BuildMessageProcessor(ctx);
    for (int i = 0; i < cfg.getLength(); i++) {
        // this not only decrypts the current hop's record, but encrypts the other records
        // with the reply key
        BuildRequestRecord req = proc.decrypt(msg, _peers[i], _privKeys[i]);
        // If false, no records matched the _peers[i], or the decryption failed
        assertTrue("foo @ " + i, req != null);
        long ourId = req.readReceiveTunnelId();
        byte[] replyIV = req.readReplyIV();
        long nextId = req.readNextTunnelId();
        Hash nextPeer = req.readNextIdentity();
        boolean isInGW = req.readIsInboundGateway();
        boolean isOutEnd = req.readIsOutboundEndpoint();
        long time = req.readRequestTime();
        long now = (ctx.clock().now() / (60l * 60l * 1000l)) * (60 * 60 * 1000);
        int ourSlot = -1;
        EncryptedBuildRecord reply = BuildResponseRecord.create(ctx, 0, req.readReplyKey(), req.readReplyIV(), -1);
        for (int j = 0; j < TunnelBuildMessage.MAX_RECORD_COUNT; j++) {
            if (msg.getRecord(j) == null) {
                ourSlot = j;
                msg.setRecord(j, reply);
                break;
            }
        }
        log.debug("Read slot " + ourSlot + " containing hop " + i + " @ " + _peers[i].toBase64() + " receives on " + ourId + " w/ replyIV " + Base64.encode(replyIV) + " sending to " + nextId + " on " + nextPeer.toBase64() + " inGW? " + isInGW + " outEnd? " + isOutEnd + " time difference " + (now - time));
    }
    log.debug("\n================================================================" + "\nAll hops traversed and replies gathered" + "\n================================================================");
    // now all of the replies are populated, toss 'em into a reply message and handle it
    TunnelBuildReplyMessage reply = new TunnelBuildReplyMessage(ctx);
    for (int i = 0; i < TunnelBuildMessage.MAX_RECORD_COUNT; i++) reply.setRecord(i, msg.getRecord(i));
    int[] statuses = (new BuildReplyHandler(ctx)).decrypt(reply, cfg, order);
    if (statuses == null)
        throw new RuntimeException("bar");
    boolean allAgree = true;
    for (int i = 0; i < cfg.getLength(); i++) {
        Hash peer = cfg.getPeer(i);
        int record = order.get(i).intValue();
        if (statuses[record] != 0)
            allAgree = false;
    // else
    // penalize peer according to the rejection cause
    }
    log.debug("\n================================================================" + "\nAll peers agree? " + allAgree + "\n================================================================");
}
Also used : EncryptedBuildRecord(net.i2p.data.i2np.EncryptedBuildRecord) I2PAppContext(net.i2p.I2PAppContext) Log(net.i2p.util.Log) PublicKey(net.i2p.data.PublicKey) TunnelBuildMessage(net.i2p.data.i2np.TunnelBuildMessage) Hash(net.i2p.data.Hash) BuildRequestRecord(net.i2p.data.i2np.BuildRequestRecord) TunnelBuildReplyMessage(net.i2p.data.i2np.TunnelBuildReplyMessage)

Aggregations

TunnelBuildReplyMessage (net.i2p.data.i2np.TunnelBuildReplyMessage)3 Hash (net.i2p.data.Hash)2 EncryptedBuildRecord (net.i2p.data.i2np.EncryptedBuildRecord)2 VariableTunnelBuildReplyMessage (net.i2p.data.i2np.VariableTunnelBuildReplyMessage)2 I2PAppContext (net.i2p.I2PAppContext)1 PublicKey (net.i2p.data.PublicKey)1 TunnelId (net.i2p.data.TunnelId)1 BuildRequestRecord (net.i2p.data.i2np.BuildRequestRecord)1 TunnelBuildMessage (net.i2p.data.i2np.TunnelBuildMessage)1 TunnelGatewayMessage (net.i2p.data.i2np.TunnelGatewayMessage)1 RouterInfo (net.i2p.data.router.RouterInfo)1 OutNetMessage (net.i2p.router.OutNetMessage)1 HopConfig (net.i2p.router.tunnel.HopConfig)1 Log (net.i2p.util.Log)1