org.aotorrent.tracker.TrackerConnectionHandler.java Source code

Java tutorial

Introduction

Here is the source code for org.aotorrent.tracker.TrackerConnectionHandler.java

Source

/*
 * Copyright 2014 Napolov Dmitry
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.aotorrent.tracker;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Lists;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import org.aotorrent.common.Torrent;
import org.aotorrent.common.protocol.tracker.HTTPTrackerResponse;
import org.apache.commons.codec.binary.Hex;

import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URLDecoder;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author dmitry 21.08.14 0:42
 */
class TrackerConnectionHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private final Map<String, Cache<InetSocketAddress, Integer>> torrents;

    TrackerConnectionHandler(Map<String, Cache<InetSocketAddress, Integer>> torrents) {
        this.torrents = torrents;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        final Map<String, String> parameters = splitQuery(new URI(request.getUri()));

        final String infoHash = parameters.get("info_hash");

        if (infoHash == null || infoHash.length() != Torrent.INFO_HASH_LENGTH || !parameters.containsKey("port")) {
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.BAD_REQUEST);
            ctx.writeAndFlush(response);
            ctx.close();
            return;
        }

        final InetAddress address = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress();
        final int port = Integer.parseInt(parameters.get("port"));

        final InetSocketAddress peerAddress = new InetSocketAddress(address, port);

        final String hexHash = Hex.encodeHexString(infoHash.getBytes());
        Cache<InetSocketAddress, Integer> peersCache = torrents.get(hexHash);
        if (peersCache == null) {
            peersCache = CacheBuilder.newBuilder().maximumSize(10000)
                    .expireAfterWrite(HTTPTrackerResponse.DEFAULT_INTERVAL * 2, TimeUnit.SECONDS).build();
            torrents.put(hexHash, peersCache);
        }

        final Collection<InetSocketAddress> filteredPeers;
        if (peersCache.asMap().size() > 0) {
            final ArrayList<InetSocketAddress> peers = Lists.newArrayList(peersCache.asMap().keySet());
            Collections.shuffle(peers);
            int numWant = parameters.containsKey("numwant") ? Integer.parseInt(parameters.get("numwant")) : 50;
            if (numWant < 1) {
                numWant = 50;
            }
            if (numWant >= peers.size()) {
                numWant = peers.size() - 1;
            }

            filteredPeers = peers.subList(0, numWant);
        } else {
            filteredPeers = Collections.emptyList();
        }

        HTTPTrackerResponse response = new HTTPTrackerResponse(filteredPeers);

        HttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                response.toTransmit());

        ctx.writeAndFlush(httpResponse);
        ctx.close();

        peersCache.put(peerAddress, 0);
    }

    private Map<String, String> splitQuery(URI uri) throws UnsupportedEncodingException {
        final Map<String, String> queryPairs = new HashMap<>();
        final String rawQuery = uri.getRawQuery();
        if (rawQuery != null) {
            final String[] pairs = rawQuery.split("&");
            for (String pair : pairs) {
                final int idx = pair.indexOf("=");
                final String key = idx > 0
                        ? URLDecoder.decode(pair.substring(0, idx), Torrent.DEFAULT_TORRENT_ENCODING)
                        : pair;
                final String value = idx > 0 && pair.length() > idx + 1
                        ? URLDecoder.decode(pair.substring(idx + 1), Torrent.DEFAULT_TORRENT_ENCODING)
                        : null;
                queryPairs.put(key, value);
            }
        }
        return queryPairs;
    }
}