premiere-libtorrent/src/natpmp.cpp

373 lines
9.9 KiB
C++
Raw Normal View History

/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are 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, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <boost/bind.hpp>
#include <asio/ip/host_name.hpp>
2007-09-10 08:12:41 +02:00
#include "libtorrent/natpmp.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/assert.hpp"
#include "libtorrent/enum_net.hpp"
2007-09-10 08:12:41 +02:00
using boost::bind;
using namespace libtorrent;
enum { num_mappings = 2 };
natpmp::natpmp(io_service& ios, address const& listen_interface, portmap_callback_t const& cb)
: m_callback(cb)
, m_currently_mapping(-1)
, m_retry_count(0)
, m_socket(ios)
, m_send_timer(ios)
, m_refresh_timer(ios)
, m_disabled(false)
{
m_mappings[0].protocol = 2; // tcp
m_mappings[1].protocol = 1; // udp
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log.open("natpmp.log", std::ios::in | std::ios::out | std::ios::trunc);
#endif
rebind(listen_interface);
}
void natpmp::rebind(address const& listen_interface)
{
2008-01-11 10:38:05 +01:00
asio::error_code ec;
address gateway = get_default_gateway(m_socket.get_io_service(), listen_interface, ec);
if (ec)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
2008-01-11 10:38:05 +01:00
m_log << time_now_string() << " failed to find default router: "
<< ec.message() << std::endl;
#endif
2008-01-11 10:38:05 +01:00
disable("failed to find default router");
return;
}
m_disabled = false;
2008-01-11 10:38:05 +01:00
udp::endpoint nat_endpoint(gateway, 5351);
if (nat_endpoint == m_nat_endpoint) return;
m_nat_endpoint = nat_endpoint;
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
2008-01-11 10:38:05 +01:00
m_log << time_now_string() << " found router at: "
<< m_nat_endpoint.address() << std::endl;
#endif
m_socket.open(udp::v4(), ec);
if (ec)
{
disable(ec.message().c_str());
return;
}
m_socket.bind(udp::endpoint(address_v4::any(), 0), ec);
if (ec)
{
disable(ec.message().c_str());
return;
}
2007-05-16 23:36:27 +02:00
for (int i = 0; i < num_mappings; ++i)
{
if (m_mappings[i].local_port == 0)
continue;
refresh_mapping(i);
}
}
void natpmp::disable(char const* message)
{
m_disabled = true;
std::stringstream msg;
msg << "NAT-PMP disabled: " << message;
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << msg.str() << std::endl;
#endif
m_callback(0, 0, msg.str());
}
void natpmp::set_mappings(int tcp, int udp)
{
if (m_disabled) return;
update_mapping(0, tcp);
update_mapping(1, udp);
}
void natpmp::update_mapping(int i, int port)
{
natpmp::mapping& m = m_mappings[i];
if (port <= 0) return;
if (m.local_port != port)
m.need_update = true;
m.local_port = port;
// prefer the same external port as the local port
if (m.external_port == 0) m.external_port = port;
if (m_currently_mapping == -1)
{
// the socket is not currently in use
// send out a mapping request
m_retry_count = 0;
send_map_request(i);
m_socket.async_receive_from(asio::buffer(&m_response_buffer, 16)
, m_remote, bind(&natpmp::on_reply, self(), _1, _2));
}
}
void natpmp::send_map_request(int i)
{
using namespace libtorrent::detail;
TORRENT_ASSERT(m_currently_mapping == -1
|| m_currently_mapping == i);
m_currently_mapping = i;
mapping& m = m_mappings[i];
char buf[12];
char* out = buf;
write_uint8(0, out); // NAT-PMP version
write_uint8(m.protocol, out); // map "protocol"
write_uint16(0, out); // reserved
write_uint16(m.local_port, out); // private port
write_uint16(m.external_port, out); // requested public port
int ttl = m.external_port == 0 ? 0 : 3600;
write_uint32(ttl, out); // port mapping lifetime
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " ==> port map request: " << (m.protocol == 1 ? "udp" : "tcp")
<< " local: " << m.local_port << " external: " << m.external_port
<< " ttl: " << ttl << std::endl;
#endif
asio::error_code ec;
m_socket.send_to(asio::buffer(buf, 12), m_nat_endpoint, 0, ec);
// linear back-off instead of exponential
++m_retry_count;
m_send_timer.expires_from_now(milliseconds(250 * m_retry_count), ec);
m_send_timer.async_wait(bind(&natpmp::resend_request, self(), i, _1));
}
void natpmp::resend_request(int i, asio::error_code const& e)
{
if (e) return;
if (m_currently_mapping != i) return;
if (m_retry_count >= 9)
{
m_mappings[i].need_update = false;
// try again in two hours
m_mappings[i].expires = time_now() + hours(2);
return;
}
send_map_request(i);
}
void natpmp::on_reply(asio::error_code const& e
, std::size_t bytes_transferred)
{
using namespace libtorrent::detail;
if (e) return;
if (m_remote != m_nat_endpoint)
{
m_socket.async_receive_from(asio::buffer(&m_response_buffer, 16)
, m_remote, bind(&natpmp::on_reply, self(), _1, _2));
return;
}
asio::error_code ec;
m_send_timer.cancel(ec);
TORRENT_ASSERT(m_currently_mapping >= 0);
int i = m_currently_mapping;
mapping& m = m_mappings[i];
char* in = m_response_buffer;
int version = read_uint8(in);
int cmd = read_uint8(in);
int result = read_uint16(in);
int time = read_uint32(in);
int private_port = read_uint16(in);
int public_port = read_uint16(in);
int lifetime = read_uint32(in);
(void)time; // to remove warning
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== port map response: " << (cmd - 128 == 1 ? "udp" : "tcp")
<< " local: " << private_port << " external: " << public_port
<< " ttl: " << lifetime << std::endl;
#endif
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
if (version != 0)
{
m_log << "*** unexpected version: " << version << std::endl;
}
#endif
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
if (private_port != m.local_port)
{
m_log << "*** unexpected local port: " << private_port << std::endl;
}
#endif
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
if (cmd != 128 + m.protocol)
{
m_log << "*** unexpected protocol: " << (cmd - 128) << std::endl;
}
#endif
if (public_port == 0 || lifetime == 0)
{
// this means the mapping was
// successfully closed
m.local_port = 0;
}
else
{
m.expires = time_now() + seconds(int(lifetime * 0.7f));
m.external_port = public_port;
}
if (result != 0)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << "*** ERROR: " << result << std::endl;
#endif
std::stringstream errmsg;
errmsg << "NAT router reports error (" << result << ") ";
switch (result)
{
case 1: errmsg << "Unsupported protocol version"; break;
case 2: errmsg << "Not authorized to create port map (enable NAT-PMP on your router)"; break;
case 3: errmsg << "Network failure"; break;
case 4: errmsg << "Out of resources"; break;
case 5: errmsg << "Unsupported opcode"; break;
}
m_mappings[i].expires = time_now() + hours(2);
m_callback(0, 0, errmsg.str());
}
else if (m.local_port != 0)
{
// don't report when we remove mappings
int tcp_port = 0;
int udp_port = 0;
if (m.protocol == 1) udp_port = m.external_port;
else tcp_port = public_port;
m_callback(tcp_port, udp_port, "");
}
m_currently_mapping = -1;
m_mappings[i].need_update = false;
m_send_timer.cancel(ec);
update_expiration_timer();
try_next_mapping(i);
}
void natpmp::update_expiration_timer()
{
ptime now = time_now();
ptime min_expire = now + seconds(3600);
int min_index = -1;
for (int i = 0; i < num_mappings; ++i)
if (m_mappings[i].expires < min_expire
&& m_mappings[i].local_port != 0)
{
min_expire = m_mappings[i].expires;
min_index = i;
}
if (min_index >= 0)
{
asio::error_code ec;
m_refresh_timer.expires_from_now(min_expire - now, ec);
m_refresh_timer.async_wait(bind(&natpmp::mapping_expired, self(), _1, min_index));
}
}
void natpmp::mapping_expired(asio::error_code const& e, int i)
{
if (e) return;
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << "*** mapping " << i << " expired, updating" << std::endl;
#endif
refresh_mapping(i);
}
void natpmp::refresh_mapping(int i)
{
m_mappings[i].need_update = true;
if (m_currently_mapping == -1)
{
// the socket is not currently in use
// send out a mapping request
m_retry_count = 0;
send_map_request(i);
m_socket.async_receive_from(asio::buffer(&m_response_buffer, 16)
, m_remote, bind(&natpmp::on_reply, self(), _1, _2));
}
}
void natpmp::try_next_mapping(int i)
{
++i;
if (i >= num_mappings) i = 0;
if (m_mappings[i].need_update)
refresh_mapping(i);
}
void natpmp::close()
{
2007-10-26 03:30:12 +02:00
asio::error_code ec;
m_socket.close(ec);
if (m_disabled) return;
for (int i = 0; i < num_mappings; ++i)
{
if (m_mappings[i].local_port == 0)
continue;
m_mappings[i].external_port = 0;
refresh_mapping(i);
}
m_refresh_timer.cancel(ec);
m_send_timer.cancel(ec);
}