<commit_before>/** Copyright (C) 2011 Turn, Inc.
 *
 * 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 com.turn.ttorrent.tracker;

import com.turn.ttorrent.bcodec.BEValue;
import com.turn.ttorrent.bcodec.BEncoder;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.simpleframework.http.Request;
import org.simpleframework.http.Response;
import org.simpleframework.http.Status;
import org.simpleframework.http.core.Container;

/** Tracker service to serve the tracker's announce requests.
 *
 * <p>
 * It only serves announce requests on /announce, and only serves torrents the
 * Tracker knows about.
 * </p>
 *
 * <p>
 * The list torrents of torrents is a map of torrent hashes to their
 * corresponding Torrent objects, and is maintained by the Tracker this service
 * is part of. The TrackerService only has a reference to this map, and does
 * not modify it.
 * </p>
 *
 * @author mpetazzoni
 * @see <a href="http://wiki.theory.org/BitTorrentSpecification">BitTorrent protocol specification</a>
 */
class TrackerService implements Container {

	private final static Logger logger =
		LoggerFactory.getLogger(TrackerService.class);

	private String version;
	private ConcurrentMap<String, TrackedTorrent> torrents;

	/** The various tracker error states.
	 *
	 * These errors are reported by the tracker to a client when expected
	 * parameters or conditions are not present while processing an announce
	 * request from a BitTorrent client.
	 */
	private enum TrackerError {
		UNKNOWN_TORRENT("The requested torrent does not exist on this tracker"),
		MISSING_HASH("Missing info hash"),
		MISSING_PEER_ID("Missing peer ID"),
		MISSING_PORT("Missing port"),
		INVALID_EVENT("Unexpected event for peer state"),
		NOT_IMPLEMENTED("Feature not implemented");

		private String message;

		TrackerError(String message) {
			this.message = message;
		}

		String getMessage() {
			return this.message;
		}

		BEValue toBEValue() throws UnsupportedEncodingException {
			Map<String, BEValue> result = new HashMap<String, BEValue>();
			result.put("failure reason", new BEValue(this.message, "UTF-8"));
			return new BEValue(result);
		}
	};

	/** Create a new TrackerService serving the given torrents.
	 *
	 * @param torrents The torrents this TrackerService should serve requests
	 * for.
	 */
	TrackerService(String version,
			ConcurrentMap<String, TrackedTorrent> torrents) {
		this.version = version;
		this.torrents = torrents;
	}

	/** Handle the incoming request on the tracker service.
	 *
	 * This makes sure the request is made to the tracker's announce URL, and
	 * delegates handling of the request to the <em>process()</em> method after
	 * preparing the response object.
	 *
	 * @param request The incoming HTTP request.
	 * @param response The response object.
	 */
	public void handle(Request request, Response response) {
		// Reject non-announce requests
		if (!Tracker.ANNOUNCE_URL.equals(request.getPath().toString())) {
			response.setCode(404);
			response.setText("Not Found");
			return;
		}

		OutputStream body = null;
		try {
			body = response.getOutputStream();
			this.process(request, response, body);
			body.flush();
		} catch (IOException ioe) {
			logger.warn("Error while writing response: {}!", ioe.getMessage());
		} finally {
			if (body != null) {
				try {
					body.close();
				} catch (IOException ioe) {
					// Ignore
				}
			}
		}
	}

	/** Process the announce request.
	 *
	 * @param request The incoming announce request.
	 * @param response The response object.
	 * @param body The validated response body output stream.
	 */
	private void process(Request request, Response response,
			OutputStream body) throws IOException {
		/* Parse the query parameters.
		 *
		 * Unfortunately we need to rely on our own parsing function here
		 * because SimpleHTTP's Query map will contain UTF-8 decoded
		 * parameters, which doesn't work well for the byte-encoded strings we
		 * expect.
		 */
		Map<String, String> params = this.parseQuery(
				request.getAddress().toString());

		// Prepare the response headers.
		response.set("Content-Type", "text/plain");
		response.set("Server", this.version);
		response.setDate("Date", System.currentTimeMillis());

		// Validate the announce request coming from the client.
		TrackerError error = this.validateAnnounceRequest(params);
		if (error != null) {
			this.serveError(response, body, Status.BAD_REQUEST, error);
			return;
		}

		// Make sure we have the peer IP, fallbacking on the request's source
		// address if the peer didn't provide it.
		if (!params.containsKey("ip")) {
			params.put("ip", request.getClientAddress().getAddress()
					.getHostAddress());
		}

		// Grab the corresponding torrent (validateAnnounceRequest already made<commit_msg>Handle wildcard source IP addresses<commit_after>/** Copyright (C) 2011 Turn, Inc.
 *
 * 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 com.turn.ttorrent.tracker;

import com.turn.ttorrent.bcodec.BEValue;
import com.turn.ttorrent.bcodec.BEncoder;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.simpleframework.http.Request;
import org.simpleframework.http.Response;
import org.simpleframework.http.Status;
import org.simpleframework.http.core.Container;

/** Tracker service to serve the tracker's announce requests.
 *
 * <p>
 * It only serves announce requests on /announce, and only serves torrents the
 * Tracker knows about.
 * </p>
 *
 * <p>
 * The list torrents of torrents is a map of torrent hashes to their
 * corresponding Torrent objects, and is maintained by the Tracker this service
 * is part of. The TrackerService only has a reference to this map, and does
 * not modify it.
 * </p>
 *
 * @author mpetazzoni
 * @see <a href="http://wiki.theory.org/BitTorrentSpecification">BitTorrent protocol specification</a>
 */
public class TrackerService implements Container {

	private static final Logger logger =
		LoggerFactory.getLogger(TrackerService.class);

	private static final String WILDCARD_IPV4_ADDRESS = "0.0.0.0";

	private final String version;
	private final ConcurrentMap<String, TrackedTorrent> torrents;

	/** The various tracker error states.
	 *
	 * These errors are reported by the tracker to a client when expected
	 * parameters or conditions are not present while processing an announce
	 * request from a BitTorrent client.
	 */
	private enum TrackerError {
		UNKNOWN_TORRENT("The requested torrent does not exist on this tracker"),
		MISSING_HASH("Missing info hash"),
		MISSING_PEER_ID("Missing peer ID"),
		MISSING_PORT("Missing port"),
		INVALID_EVENT("Unexpected event for peer state"),
		NOT_IMPLEMENTED("Feature not implemented");

		private String message;

		TrackerError(String message) {
			this.message = message;
		}

		String getMessage() {
			return this.message;
		}

		BEValue toBEValue() throws UnsupportedEncodingException {
			Map<String, BEValue> result = new HashMap<String, BEValue>();
			result.put("failure reason", new BEValue(this.message, "UTF-8"));
			return new BEValue(result);
		}
	};

	/** Create a new TrackerService serving the given torrents.
	 *
	 * @param torrents The torrents this TrackerService should serve requests
	 * for.
	 */
	TrackerService(String version,
			ConcurrentMap<String, TrackedTorrent> torrents) {
		this.version = version;
		this.torrents = torrents;
	}

	/** Handle the incoming request on the tracker service.
	 *
	 * This makes sure the request is made to the tracker's announce URL, and
	 * delegates handling of the request to the <em>process()</em> method after
	 * preparing the response object.
	 *
	 * @param request The incoming HTTP request.
	 * @param response The response object.
	 */
	public void handle(Request request, Response response) {
		// Reject non-announce requests
		if (!Tracker.ANNOUNCE_URL.equals(request.getPath().toString())) {
			response.setCode(404);
			response.setText("Not Found");
			return;
		}

		OutputStream body = null;
		try {
			body = response.getOutputStream();
			this.process(request, response, body);
			body.flush();
		} catch (IOException ioe) {
			logger.warn("Error while writing response: {}!", ioe.getMessage());
		} finally {
			if (body != null) {
				try {
					body.close();
				} catch (IOException ioe) {
					// Ignore
				}
			}
		}
	}

	/** Process the announce request.
	 *
	 * @param request The incoming announce request.
	 * @param response The response object.
	 * @param body The validated response body output stream.
	 */
	private void process(Request request, Response response,
			OutputStream body) throws IOException {
		/* Parse the query parameters.
		 *
		 * Unfortunately we need to rely on our own parsing function here
		 * because SimpleHTTP's Query map will contain UTF-8 decoded
		 * parameters, which doesn't work well for the byte-encoded strings we
		 * expect.
		 */
		Map<String, String> params = this.parseQuery(
				request.getAddress().toString());

		// Prepare the response headers.
		response.set("Content-Type", "text/plain");
		response.set("Server", this.version);
		response.setDate("Date", System.currentTimeMillis());

		// Validate the announce request coming from the client.
		TrackerError error = this.validateAnnounceRequest(params);
		if (error != null) {
			this.serveError(response, body, Status.BAD_REQUEST, error);
			return;
		}

		// Make sure we have the peer IP, fallbacking on the request's source
		// address if the peer didn't provide it.
		if (!params.containsKey("ip") ||
			WILDCARD_IPV4_ADDRESS.equals(params.get("ip"))) {
			params.put("ip", request.getClientAddress().getAddress()
					.getHostAddress());
		}

		// Grab the corresponding torrent (validateAnnounceRequest already made
{'fraction_non_alphanumeric': 0.09986636971046771, 'fraction_numerical': 0.0032071269487750557, 'mean_word_length': 3.9915518008003557, 'pattern_counts': {'":': 0, '<': 29, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 1, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3219873', 'n_tokens_mistral': 3453, 'n_tokens_neox': 3075, 'n_words': 1107}