⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 dht_tracker.cpp

📁 LINUX下
💻 CPP
📖 第 1 页 / 共 2 页
字号:
/*Copyright (c) 2006, Arvid NorbergAll rights reserved.Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditionsare met:    * Redistributions of source code must retain the above copyright      notice, this list of conditions and the following disclaimer.    * Redistributions in binary form must reproduce the above copyright      notice, this list of conditions and the following disclaimer in      the documentation and/or other materials provided with the distribution.    * Neither the name of the author nor the names of its      contributors may be used to endorse or promote products derived      from this software without specific prior written permission.THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THEIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSEARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BELIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, ORCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OFSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESSINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER INCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THEPOSSIBILITY OF SUCH DAMAGE.*/#include "libtorrent/pch.hpp"#include <fstream>#include <set>#include <numeric>#include <stdexcept>#include <boost/bind.hpp>#include <boost/ref.hpp>#include <boost/optional.hpp>#include <boost/lexical_cast.hpp>#include <boost/filesystem/operations.hpp>#include "libtorrent/kademlia/node.hpp"#include "libtorrent/kademlia/node_id.hpp"#include "libtorrent/kademlia/traversal_algorithm.hpp"#include "libtorrent/kademlia/dht_tracker.hpp"#include "libtorrent/socket.hpp"#include "libtorrent/bencode.hpp"#include "libtorrent/io.hpp"#include "libtorrent/version.hpp"using boost::ref;using boost::lexical_cast;using libtorrent::dht::node_impl;using libtorrent::dht::node_id;using libtorrent::dht::packet_t;using libtorrent::dht::msg;using libtorrent::dht::packet_iterator;namespace messages = libtorrent::dht::messages;using namespace libtorrent::detail;enum{	key_refresh = 5 // generate a new write token key every 5 minutes};using asio::ip::udp;typedef asio::ip::address_v4 address;namespace{	const int tick_period = 1; // minutes	struct count_peers	{		int& count;		count_peers(int& c): count(c) {}		void operator()(std::pair<libtorrent::dht::node_id			, libtorrent::dht::torrent_entry> const& t)		{			count += std::distance(t.second.peers.begin()				, t.second.peers.end());		}	};		boost::optional<node_id> read_id(libtorrent::entry const& d)	{		using namespace libtorrent;		using libtorrent::dht::node_id;		if (d.type() != entry::dictionary_t) return boost::optional<node_id>();		entry const* nid = d.find_key("node-id");		if (!nid			|| nid->type() != entry::string_t			|| nid->string().length() != 40)			return boost::optional<node_id>();		return boost::optional<node_id>(			boost::lexical_cast<node_id>(nid->string()));	}	template <class EndpointType>	void read_endpoint_list(libtorrent::entry const* n, std::vector<EndpointType>& epl)					{		using namespace libtorrent;		entry::list_type const& contacts = n->list();		for (entry::list_type::const_iterator i = contacts.begin()			, end(contacts.end()); i != end; ++i)		{			std::string const& p = i->string();			if (p.size() < 6) continue;			std::string::const_iterator in = p.begin();			if (p.size() == 6)				epl.push_back(read_v4_endpoint<EndpointType>(in));			else if (p.size() == 18)				epl.push_back(read_v6_endpoint<EndpointType>(in));		}	}}namespace libtorrent { namespace dht{	void intrusive_ptr_add_ref(dht_tracker const* c)	{		TORRENT_ASSERT(c != 0);		TORRENT_ASSERT(c->m_refs >= 0);		++c->m_refs;	}	void intrusive_ptr_release(dht_tracker const* c)	{		TORRENT_ASSERT(c != 0);		TORRENT_ASSERT(c->m_refs > 0);		if (--c->m_refs == 0)			delete c;	}#ifdef TORRENT_DHT_VERBOSE_LOGGING	TORRENT_DEFINE_LOG(dht_tracker)#endif	// class that puts the networking and the kademlia node in a single	// unit and connecting them together.	dht_tracker::dht_tracker(asio::io_service& ios, dht_settings const& settings		, asio::ip::address listen_interface, entry const& bootstrap)		: m_strand(ios)		, m_socket(ios, udp::endpoint(listen_interface, settings.service_port))		, m_dht(bind(&dht_tracker::send_packet, this, _1), settings			, read_id(bootstrap))		, m_buffer(0)		, m_last_new_key(time_now() - minutes(key_refresh))		, m_timer(ios)		, m_connection_timer(ios)		, m_refresh_timer(ios)		, m_settings(settings)		, m_refresh_bucket(160)		, m_host_resolver(ios)		, m_refs(0)	{		using boost::bind;		m_in_buf[0].resize(1000);		m_in_buf[1].resize(1000);#ifdef TORRENT_DHT_VERBOSE_LOGGING		m_counter = 0;		std::fill_n(m_replies_bytes_sent, 5, 0);		std::fill_n(m_queries_bytes_received, 5, 0);		std::fill_n(m_replies_sent, 5, 0);		std::fill_n(m_queries_received, 5, 0);		m_announces = 0;		m_failed_announces = 0;		m_total_message_input = 0;		m_ut_message_input = 0;		m_lt_message_input = 0;		m_mp_message_input = 0;		m_gr_message_input = 0;		m_mo_message_input = 0;		m_total_in_bytes = 0;		m_total_out_bytes = 0;		m_queries_out_bytes = 0;				// turns on and off individual components' logging//		rpc_log().enable(false);//		node_log().enable(false);//		traversal_log().enable(false);//		dht_tracker_log.enable(false);#endif		std::vector<udp::endpoint> initial_nodes;		if (bootstrap.type() == entry::dictionary_t)		{			try			{			if (entry const* nodes = bootstrap.find_key("nodes"))				read_endpoint_list<udp::endpoint>(nodes, initial_nodes);			} catch (std::exception&) {}		}		m_socket.async_receive_from(asio::buffer(&m_in_buf[m_buffer][0]			, m_in_buf[m_buffer].size()), m_remote_endpoint[m_buffer]			, m_strand.wrap(bind(&dht_tracker::on_receive, self(), _1, _2)));		m_timer.expires_from_now(seconds(1));		m_timer.async_wait(m_strand.wrap(bind(&dht_tracker::tick, self(), _1)));		m_connection_timer.expires_from_now(seconds(10));		m_connection_timer.async_wait(m_strand.wrap(			bind(&dht_tracker::connection_timeout, self(), _1)));		m_refresh_timer.expires_from_now(seconds(5));		m_refresh_timer.async_wait(m_strand.wrap(bind(&dht_tracker::refresh_timeout, self(), _1)));		m_dht.bootstrap(initial_nodes, bind(&dht_tracker::on_bootstrap, self()));	}	void dht_tracker::stop()	{		m_timer.cancel();		m_connection_timer.cancel();		m_refresh_timer.cancel();		m_socket.close();		m_host_resolver.cancel();	}	void dht_tracker::dht_status(session_status& s)	{		boost::tie(s.dht_nodes, s.dht_node_cache) = m_dht.size();		s.dht_torrents = m_dht.data_size();		s.dht_global_nodes = m_dht.num_global_nodes();	}	void dht_tracker::connection_timeout(asio::error_code const& e)		try	{		if (e) return;		if (!m_socket.is_open()) return;		time_duration d = m_dht.connection_timeout();		m_connection_timer.expires_from_now(d);		m_connection_timer.async_wait(m_strand.wrap(bind(&dht_tracker::connection_timeout, self(), _1)));	}	catch (std::exception& exc)	{#ifndef NDEBUG		std::cerr << "exception-type: " << typeid(exc).name() << std::endl;		std::cerr << "what: " << exc.what() << std::endl;		TORRENT_ASSERT(false);#endif	};	void dht_tracker::refresh_timeout(asio::error_code const& e)		try	{		if (e) return;		if (!m_socket.is_open()) return;		time_duration d = m_dht.refresh_timeout();		m_refresh_timer.expires_from_now(d);		m_refresh_timer.async_wait(m_strand.wrap(			bind(&dht_tracker::refresh_timeout, self(), _1)));	}	catch (std::exception&)	{		TORRENT_ASSERT(false);	};	void dht_tracker::rebind(asio::ip::address listen_interface, int listen_port)	{		m_socket.close();		udp::endpoint ep(listen_interface, listen_port);		m_socket.open(ep.protocol());		m_socket.bind(ep);		m_socket.async_receive_from(asio::buffer(&m_in_buf[m_buffer][0]			, m_in_buf[m_buffer].size()), m_remote_endpoint[m_buffer]			, m_strand.wrap(bind(&dht_tracker::on_receive, self(), _1, _2)));	}	void dht_tracker::tick(asio::error_code const& e)		try	{		if (e) return;		if (!m_socket.is_open()) return;		m_timer.expires_from_now(minutes(tick_period));		m_timer.async_wait(m_strand.wrap(bind(&dht_tracker::tick, self(), _1)));		ptime now = time_now();		if (now - m_last_new_key > minutes(key_refresh))		{			m_last_new_key = now;			m_dht.new_write_key();#ifdef TORRENT_DHT_VERBOSE_LOGGING			TORRENT_LOG(dht_tracker) << time_now_string() << " new write key";#endif		}		#ifdef TORRENT_DHT_VERBOSE_LOGGING		static bool first = true;		if (first)		{			boost::filesystem::create_directory("libtorrent_logs");		}		std::ofstream st("libtorrent_logs/routing_table_state.txt", std::ios_base::trunc);		m_dht.print_state(st);				// count torrents		int torrents = std::distance(m_dht.begin_data(), m_dht.end_data());				// count peers		int peers = 0;		std::for_each(m_dht.begin_data(), m_dht.end_data(), count_peers(peers));		std::ofstream pc("libtorrent_logs/dht_stats.log", std::ios_base::app);		if (first)		{			first = false;			pc << "\n\n *****   starting log at " << time_now_string() << "   *****\n\n"				<< "minute:active nodes:passive nodes"				":ping replies sent:ping queries recvd:ping"				":ping replies sent:ping queries recvd:ping"				":find_node replies bytes sent:find_node queries bytes recv"				":find_node replies bytes sent:find_node queries bytes recv"				":get_peers replies sent:get_peers queries recvd:get_peers"				":get_peers replies bytes sent:get_peers queries bytes recv"				":announce_peer replies sent:announce_peer queries recvd:announce_peer"				":announce_peer replies bytes sent:announce_peer queries bytes recv"				":error replies sent:error queries recvd:error"				":error replies bytes sent:error queries bytes recv"				":num torrents:num peers:announces per min"				":failed announces per min:total msgs per min"				":ut msgs per min:lt msgs per min:mp msgs per min"				":gr msgs per min:bytes in per sec:bytes out per sec"				":queries out bytes per sec\n\n";		}		int active;		int passive;		boost::tie(active, passive) = m_dht.size();		pc << (m_counter * tick_period)			<< "\t" << active			<< "\t" << passive;		for (int i = 0; i < 5; ++i)			pc << "\t" << (m_replies_sent[i] / float(tick_period))				<< "\t" << (m_queries_received[i] / float(tick_period))				<< "\t" << (m_replies_bytes_sent[i] / float(tick_period*60))				<< "\t" << (m_queries_bytes_received[i] / float(tick_period*60));				pc << "\t" << torrents			<< "\t" << peers			<< "\t" << m_announces / float(tick_period)			<< "\t" << m_failed_announces / float(tick_period)			<< "\t" << (m_total_message_input / float(tick_period))			<< "\t" << (m_ut_message_input / float(tick_period))			<< "\t" << (m_lt_message_input / float(tick_period))			<< "\t" << (m_mp_message_input / float(tick_period))			<< "\t" << (m_gr_message_input / float(tick_period))			<< "\t" << (m_mo_message_input / float(tick_period))			<< "\t" << (m_total_in_bytes / float(tick_period*60))			<< "\t" << (m_total_out_bytes / float(tick_period*60))			<< "\t" << (m_queries_out_bytes / float(tick_period*60))			<< std::endl;		++m_counter;		std::fill_n(m_replies_bytes_sent, 5, 0);		std::fill_n(m_queries_bytes_received, 5, 0);		std::fill_n(m_replies_sent, 5, 0);		std::fill_n(m_queries_received, 5, 0);		m_announces = 0;		m_failed_announces = 0;		m_total_message_input = 0;		m_ut_message_input = 0;		m_lt_message_input = 0;		m_total_in_bytes = 0;		m_total_out_bytes = 0;		m_queries_out_bytes = 0;#endif	}	catch (std::exception&)	{		TORRENT_ASSERT(false);	};	void dht_tracker::announce(sha1_hash const& ih, int listen_port		, boost::function<void(std::vector<tcp::endpoint> const&		, sha1_hash const&)> f)	{		m_dht.announce(ih, listen_port, f);	}	// translate bittorrent kademlia message into the generice kademlia message	// used by the library	void dht_tracker::on_receive(asio::error_code const& error, size_t bytes_transferred)		try	{		if (error == asio::error::operation_aborted) return;		if (!m_socket.is_open()) return;			int current_buffer = m_buffer;		m_buffer = (m_buffer + 1) & 1;		m_socket.async_receive_from(asio::buffer(&m_in_buf[m_buffer][0]			, m_in_buf[m_buffer].size()), m_remote_endpoint[m_buffer]			, m_strand.wrap(bind(&dht_tracker::on_receive, self(), _1, _2)));		if (error) return;		node_ban_entry* match = 0;		node_ban_entry* min = m_ban_nodes;		ptime now = time_now();		for (node_ban_entry* i = m_ban_nodes; i < m_ban_nodes + num_ban_nodes; ++i)		{			if (i->src == m_remote_endpoint[current_buffer])			{				match = i;				break;			}			if (i->count < min->count) min = i;		}		if (match)		{			++match->count;			if (match->count >= 20)			{				if (now < match->limit)				{#ifdef TORRENT_DHT_VERBOSE_LOGGING					if (match->count == 20)					{						TORRENT_LOG(dht_tracker) << time_now_string() << " BANNING PEER [ ip: "							<< m_remote_endpoint[current_buffer] << " | "							"time: " << total_seconds((now - match->limit) + seconds(5))							<< " | count: " << match->count << " ]";					}#endif					// we've received 20 messages in less than 5 seconds from					// this node. Ignore it until it's silent for 5 minutes					match->limit = now + minutes(5);					return;				}				// we got 50 messages from this peer, but it was in				// more than 5 seconds. Reset the counter and the timer				match->count = 0;				match->limit = now + seconds(5);			}		}		else		{			min->count = 1;			min->limit = now + seconds(5);			min->src = m_remote_endpoint[current_buffer];		}#ifdef TORRENT_DHT_VERBOSE_LOGGING		++m_total_message_input;		m_total_in_bytes += bytes_transferred;#endif		try		{			using libtorrent::entry;			using libtorrent::bdecode;						TORRENT_ASSERT(bytes_transferred > 0);			entry e = bdecode(m_in_buf[current_buffer].begin()				, m_in_buf[current_buffer].end());#ifdef TORRENT_DHT_VERBOSE_LOGGING			TORRENT_LOG(dht_tracker) << time_now_string() << " RECEIVED ["				<< m_remote_endpoint[current_buffer] << "]:";#endif			libtorrent::dht::msg m;			m.message_id = 0;			m.addr = m_remote_endpoint[current_buffer];			m.transaction_id = e["t"].string();#ifdef TORRENT_DHT_VERBOSE_LOGGING			try			{				entry const* ver = e.find_key("v");				if (!ver) throw std::exception();				std::string const& client = ver->string();				if (client.size() > 1 && std::equal(client.begin(), client.begin() + 2, "UT"))				{					++m_ut_message_input;					TORRENT_LOG(dht_tracker) << "   client: uTorrent";				}				else if (client.size() > 1 && std::equal(client.begin(), client.begin() + 2, "LT"))				{					++m_lt_message_input;					TORRENT_LOG(dht_tracker) << "   client: libtorrent";				}				else if (client.size() > 1 && std::equal(client.begin(), client.begin() + 2, "MP"))				{					++m_mp_message_input;					TORRENT_LOG(dht_tracker) << "   client: MooPolice";				}				else if (client.size() > 1 && std::equal(client.begin(), client.begin() + 2, "GR"))				{					++m_gr_message_input;					TORRENT_LOG(dht_tracker) << "   client: GetRight";				}				else if (client.size() > 1 && std::equal(client.begin(), client.begin() + 2, "MO"))				{					++m_mo_message_input;					TORRENT_LOG(dht_tracker) << "   client: Mono Torrent";				}				else				{					TORRENT_LOG(dht_tracker) << "   client: " << client;				}			}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -