This commit is contained in:
orignal 2015-01-03 16:30:07 -05:00
commit 02851d7587
7 changed files with 604 additions and 171 deletions

View File

@ -18,6 +18,11 @@
#include "HTTPServer.h"
#include "ClientContext.h"
#ifdef USE_UPNP
#include "UPnP.h"
#endif
namespace i2p
{
namespace util
@ -89,11 +94,11 @@ namespace i2p
if (isDaemon)
{
std::string logfile_path = IsService () ? "/var/log" : i2p::util::filesystem::GetDataDir().string();
#ifndef _WIN32
#ifndef _WIN32
logfile_path.append("/i2pd.log");
#else
#else
logfile_path.append("\\i2pd.log");
#endif
#endif
StartLog (logfile_path);
}
else
@ -111,7 +116,10 @@ namespace i2p
LogPrint("Tunnels started");
i2p::client::context.Start ();
LogPrint("Client started");
#ifdef USE_UPNP
i2p::UPnP::upnpc.Start();
LogPrint("UPnP module loaded");
#endif
return true;
}
@ -128,6 +136,9 @@ namespace i2p
LogPrint("NetDB stoped");
d.httpServer->Stop();
LogPrint("HTTP Server stoped");
#ifdef USE_UPNP
i2p::UPnP::upnpc.Stop();
#endif
StopLog ();
delete d.httpServer; d.httpServer = nullptr;

View File

@ -36,6 +36,12 @@ else
LDLIBS = -lcryptopp -lboost_system -lboost_date_time -lboost_filesystem -lboost_regex -lboost_program_options -lpthread
endif
# UPNP Support (miniupnpc 1.5 or 1.6)
ifeq ($(USE_UPNP),1)
LDFLAGS += -ldl
CXXFLAGS += -DUSE_UPNP
endif
IS_64 := $(shell $(CXX) -dumpmachine 2>&1 | $(GREP) -c "64")
ifeq ($(USE_AESNI),yes)
ifeq ($(IS_64),1)

View File

@ -1,10 +1,15 @@
CXX = clang++
CXXFLAGS = -g -Wall -std=c++11 -DCRYPTOPP_DISABLE_ASM
CXXFLAGS = -g -Wall -std=c++11 -DCRYPTOPP_DISABLE_ASM -DMAC_OSX
#CXXFLAGS = -g -O2 -Wall -std=c++11 -DCRYPTOPP_DISABLE_ASM
INCFLAGS = -I/usr/local/include
LDFLAGS = -Wl,-rpath,/usr/local/lib -L/usr/local/lib
LDLIBS = -lcryptopp -lboost_system -lboost_date_time -lboost_filesystem -lboost_regex -lboost_program_options -lpthread
ifeq ($(USE_UPNP),1)
LDFLAGS += -ldl
CXXFLAGS += -DUSE_UPNP
endif
# OSX Notes
# http://www.hutsby.net/2011/08/macs-with-aes-ni.html
# Seems like all recent Mac's have AES-NI, after firmware upgrade 2.2

314
SOCKS.cpp
View File

@ -4,44 +4,109 @@
#include "Destination.h"
#include "ClientContext.h"
#include "I2PEndian.h"
#include <cstring>
#include <cassert>
namespace i2p
{
namespace proxy
{
const uint8_t socks_leaseset_timeout = 10;
const uint8_t socks_timeout = 60;
void SOCKS4AHandler::AsyncSockRead()
void SOCKSHandler::AsyncSockRead()
{
LogPrint(eLogDebug,"--- SOCKS async sock read");
if(m_sock) {
m_sock->async_receive(boost::asio::buffer(m_sock_buff, socks_buffer_size),
std::bind(&SOCKS4AHandler::HandleSockRecv, this,
std::bind(&SOCKSHandler::HandleSockRecv, this,
std::placeholders::_1, std::placeholders::_2));
} else {
LogPrint(eLogError,"--- SOCKS no socket for read");
}
}
void SOCKS4AHandler::Terminate() {
void SOCKSHandler::Terminate() {
CloseStream();
CloseSock();
delete this; // HACK: ew
}
void SOCKS4AHandler::SocksFailed()
void SOCKSHandler::Socks5AuthNegoFailed()
{
LogPrint(eLogWarning,"--- SOCKS failed");
//TODO: send the right response
boost::asio::async_write(*m_sock, boost::asio::buffer("\x00\x5b 12345"),
std::bind(&SOCKS4AHandler::SentSocksFailed, this,
LogPrint(eLogWarning,"--- SOCKS5 authentication negotiation failed");
boost::asio::async_write(*m_sock, boost::asio::buffer("\x05\xff",2),
std::bind(&SOCKSHandler::SentSocksFailed, this,
std::placeholders::_1));
}
void SOCKS4AHandler::CloseSock()
void SOCKSHandler::Socks5ChooseAuth()
{
LogPrint(eLogDebug,"--- SOCKS5 choosing authentication method");
//TODO: Choose right method
boost::asio::async_write(*m_sock, boost::asio::buffer("\x05\x00",2),
std::bind(&SOCKSHandler::SentSocksResponse, this,
std::placeholders::_1, nullptr));
}
static const char *socks5Replies[9] = {
"\x05\x00\x00\x01\x00\x00\x00\x00\x00\x00",
"\x05\x01\x00\x01\x00\x00\x00\x00\x00\x00",
"\x05\x02\x00\x01\x00\x00\x00\x00\x00\x00",
"\x05\x03\x00\x01\x00\x00\x00\x00\x00\x00",
"\x05\x04\x00\x01\x00\x00\x00\x00\x00\x00",
"\x05\x05\x00\x01\x00\x00\x00\x00\x00\x00",
"\x05\x06\x00\x01\x00\x00\x00\x00\x00\x00",
"\x05\x07\x00\x01\x00\x00\x00\x00\x00\x00",
"\x05\x08\x00\x01\x00\x00\x00\x00\x00\x00" };
/* All hope is lost */
void SOCKSHandler::SocksRequestFailed()
{
switch (m_socksv) {
case 4:
LogPrint(eLogWarning,"--- SOCKS4 failed");
//TODO: send the right response
boost::asio::async_write(*m_sock, boost::asio::buffer("\x00\x5b\x00\x00\x00\x00\x00\x00",8),
std::bind(&SOCKSHandler::SentSocksFailed, this, std::placeholders::_1));
break;
case 5:
assert(m_error <= 8);
LogPrint(eLogWarning,"--- SOCKS5 failed");
//TODO: use error properly and address type m_error
boost::asio::async_write(*m_sock, boost::asio::buffer(socks5Replies[m_error],10),
std::bind(&SOCKSHandler::SentSocksFailed, this, std::placeholders::_1));
break;
default:
LogPrint (eLogError,"--- SOCKS had invalid version");
Terminate();
break;
}
}
void SOCKSHandler::SocksRequestSuccess()
{
std::shared_ptr<std::vector<uint8_t>> response(new std::vector<uint8_t>);
switch (m_socksv) {
case 4:
LogPrint(eLogInfo,"--- SOCKS4 connection success");
//TODO: send the right response
boost::asio::async_write(*m_sock, boost::asio::buffer("\x00\x5a\x00\x00\x00\x00\x00\x00",8),
std::bind(&SOCKSHandler::SentSocksResponse, this,
std::placeholders::_1, nullptr));
break;
case 5:
LogPrint(eLogInfo,"--- SOCKS5 connection success");
//TODO: send the right response using the port? and the localside i2p address
boost::asio::async_write(*m_sock, boost::asio::buffer("\x05\x00\x00\x01\x00\x00\x00\x00\x00\x00",10),
std::bind(&SOCKSHandler::SentSocksResponse, this,
std::placeholders::_1, response));
break;
default:
LogPrint (eLogError,"--- SOCKS had invalid version");
Terminate();
break;
}
}
void SOCKSHandler::CloseSock()
{
if (m_sock) {
LogPrint(eLogDebug,"--- SOCKS close sock");
@ -51,7 +116,7 @@ namespace proxy
}
}
void SOCKS4AHandler::CloseStream()
void SOCKSHandler::CloseStream()
{
if (m_stream) {
LogPrint(eLogDebug,"--- SOCKS close stream");
@ -59,11 +124,7 @@ namespace proxy
}
}
const size_t socks_hostname_size = 1024;
const size_t socks_ident_size = 1024;
const size_t destb32_len = 52;
std::size_t SOCKS4AHandler::HandleData(uint8_t *sock_buff, std::size_t len)
std::size_t SOCKSHandler::HandleData(uint8_t *sock_buff, std::size_t len)
{
assert(len); // This should always be called with a least a byte left to parse
switch (m_state) {
@ -71,6 +132,10 @@ namespace proxy
return HandleVersion(sock_buff);
case SOCKS4A:
return HandleSOCKS4A(sock_buff,len);
case SOCKS5_S1:
return HandleSOCKS5Step1(sock_buff,len);
case SOCKS5_S3:
return HandleSOCKS5Step3(sock_buff,len);
default:
LogPrint(eLogError,"--- SOCKS state?? ", m_state);
Terminate();
@ -78,12 +143,18 @@ namespace proxy
}
}
std::size_t SOCKS4AHandler::HandleVersion(uint8_t *sock_buff)
std::size_t SOCKSHandler::HandleVersion(uint8_t *sock_buff)
{
switch (*sock_buff) {
case 4:
m_state = SOCKS4A; // Switch to the 4a handler
m_pstate = GET4A_COMMAND; //Initialize the parser at the right position
m_socksv = 4;
return 1;
case 5:
m_state = SOCKS5_S1; // Switch to the 4a handler
m_pstate = GET5_AUTHNUM; //Initialize the parser at the right position
m_socksv = 5;
return 1;
default:
LogPrint(eLogError,"--- SOCKS rejected invalid version", ((int)*sock_buff));
@ -92,7 +163,7 @@ namespace proxy
}
}
std::size_t SOCKS4AHandler::HandleSOCKS4A(uint8_t *sock_buff, std::size_t len)
std::size_t SOCKSHandler::HandleSOCKS4A(uint8_t *sock_buff, std::size_t len)
{
std::size_t rv = 0;
while (len > 0) {
@ -103,7 +174,7 @@ namespace proxy
if ( *sock_buff != 1 ) {
//TODO: we need to support binds and other shit!
LogPrint(eLogError,"--- SOCKS4a unsupported command", ((int)*sock_buff));
SocksFailed();
SocksRequestFailed();
return 0;
}
m_pstate = GET4A_PORT1;
@ -133,7 +204,7 @@ namespace proxy
m_pstate = GET4A_IDENT;
if( m_ip == 0 || m_ip > 255 ) {
LogPrint(eLogError,"--- SOCKS4a rejected because it's actually SOCKS4");
SocksFailed();
SocksRequestFailed();
return 0;
}
break;
@ -145,11 +216,12 @@ namespace proxy
if (!*sock_buff) {
m_pstate = DONE;
m_state = READY;
m_need_more = false;
return rv;
}
if (m_destination.size() > HOST_NAME_MAX) {
if (m_destination.size() > max_socks_hostname_size) {
LogPrint(eLogError,"--- SOCKS4a destination is too large ");
SocksFailed();
SocksRequestFailed();
return 0;
}
m_destination.push_back(*sock_buff);
@ -165,7 +237,125 @@ namespace proxy
return rv;
}
void SOCKS4AHandler::HandleSockRecv(const boost::system::error_code & ecode, std::size_t len)
std::size_t SOCKSHandler::HandleSOCKS5Step1(uint8_t *sock_buff, std::size_t len)
{
std::size_t rv = 0;
while (len > 0) {
rv++;
switch (m_pstate)
{
case GET5_AUTHNUM:
m_authleft = *sock_buff;
m_pstate = GET5_AUTH;
break;
case GET5_AUTH:
m_authleft --;
if (*sock_buff == 0)
m_authchosen = 0;
if ( m_authleft == 0 ) {
if (m_authchosen == 0xff) {
//TODO: we maybe want support for other methods!
LogPrint(eLogError,"--- SOCKS5 couldn't negotiate authentication");
Socks5AuthNegoFailed();
return 0;
}
m_pstate = GET5_REQUESTV;
m_state = SOCKS5_S3;
m_need_more = false;
Socks5ChooseAuth();
return rv;
}
break;
default:
LogPrint(eLogError,"--- SOCKS5 parse state?? ", m_pstate);
Terminate();
return 0;
}
sock_buff++;
len--;
}
return rv;
}
//TODO this may be merged with the SOCKS4a code
std::size_t SOCKSHandler::HandleSOCKS5Step3(uint8_t *sock_buff, std::size_t len)
{
std::size_t rv = 0;
while (len > 0) {
rv++;
switch (m_pstate)
{
case GET5_REQUESTV:
if (*sock_buff != 5) {
LogPrint(eLogError,"--- SOCKS rejected unknown request version", ((int)*sock_buff));
m_error = 0x7;
SocksRequestFailed();
return 0;
}
m_pstate = GET5_COMMAND;
break;
case GET5_COMMAND:
if ( *sock_buff != 1 ) {
//TODO: we need to support binds and other shit!
LogPrint(eLogError,"--- SOCKS5 unsupported command", ((int)*sock_buff));
m_error = 0x7;
SocksRequestFailed();
return 0;
}
m_pstate = GET5_GETRSV;
break;
case GET5_GETRSV:
if ( *sock_buff != 0 ) {
LogPrint(eLogError,"--- SOCKS5 unknown reserved field", ((int)*sock_buff));
m_error = 0x7;
SocksRequestFailed();
return 0;
}
m_pstate = GET5_GETADDRTYPE;
break;
case GET5_GETADDRTYPE:
if ( *sock_buff != 0x3 ) {
//TODO: we may want to support other address types!
LogPrint(eLogError,"--- SOCKS5 unsupported address type", ((int)*sock_buff));
m_error = 0x8;
SocksRequestFailed();
return 0;
}
m_pstate = GET5_HOST_SIZE;
break;
case GET5_HOST_SIZE:
m_addrleft = *sock_buff;
m_pstate = GET5_HOST;
break;
case GET5_HOST:
m_destination.push_back(*sock_buff);
m_addrleft--;
if (m_addrleft == 0)
m_pstate = GET5_PORT1;
break;
case GET5_PORT1:
m_port = ((uint16_t)*sock_buff) << 8;
m_pstate = GET5_PORT2;
break;
case GET5_PORT2:
m_port |= ((uint16_t)*sock_buff);
m_pstate = DONE;
m_state = READY;
m_need_more = false;
return rv;
break;
default:
LogPrint(eLogError,"--- SOCKS5 parse state?? ", m_pstate);
Terminate();
return 0;
}
sock_buff++;
len--;
}
return rv;
}
void SOCKSHandler::HandleSockRecv(const boost::system::error_code & ecode, std::size_t len)
{
LogPrint(eLogDebug,"--- SOCKS sock recv: ", len);
if(ecode) {
@ -175,109 +365,105 @@ namespace proxy
}
std::size_t pos = 0;
while (pos != len && m_state != READY) {
m_need_more = true;
while (pos != len && m_state != READY && m_need_more) {
assert(pos < len); //We are overflowing the buffer otherwise
std::size_t rv = HandleData(m_sock_buff + pos, len - pos);
if (!rv) return; //Something went wrong die misserably
pos += rv;
}
assert(!(m_state == READY && m_need_more));
if (m_state == READY) {
LogPrint(eLogInfo,"--- SOCKS requested ", m_destination, ":" , m_port);
if (pos != len) {
LogPrint(eLogError,"--- SOCKS rejected because be can't handle extra data");
SocksFailed();
SocksRequestFailed();
return ;
}
if(m_destination.find(".i2p") == std::string::npos) {
LogPrint(eLogError,"--- SOCKS invalid hostname: ", m_destination);
SocksFailed();
SocksRequestFailed();
return;
}
m_parent->GetLocalDestination ()->CreateStream (
std::bind (&SOCKS4AHandler::HandleStreamRequestComplete,
std::bind (&SOCKSHandler::HandleStreamRequestComplete,
this, std::placeholders::_1), m_destination, m_port);
}
} else if (m_need_more)
AsyncSockRead();
}
void SOCKS4AHandler::ConnectionSuccess()
{
LogPrint(eLogInfo,"--- SOCKS connection success");
//TODO: send the right response
boost::asio::async_write(*m_sock, boost::asio::buffer("\x00\x5a 12345"),
std::bind(&SOCKS4AHandler::SentConnectionSuccess, this,
std::placeholders::_1));
}
void SOCKS4AHandler::SentSocksFailed(const boost::system::error_code & ecode)
void SOCKSHandler::SentSocksFailed(const boost::system::error_code & ecode)
{
if (!ecode) {
Terminate();
}
else
{
} else {
LogPrint (eLogError,"--- SOCKS Closing socket after sending failure because: ", ecode.message ());
Terminate();
}
}
void SOCKS4AHandler::SentConnectionSuccess(const boost::system::error_code & ecode)
void SOCKSHandler::SentSocksResponse(const boost::system::error_code & ecode, std::shared_ptr<std::vector<uint8_t>> response)
{
response.reset(); // Information wants to be free, so does memory
if (!ecode) {
LogPrint (eLogInfo,"--- SOCKS New I2PTunnel connection");
auto connection = std::make_shared<i2p::client::I2PTunnelConnection>((i2p::client::I2PTunnel *)m_parent, m_sock, m_stream);
m_parent->AddConnection (connection);
connection->I2PConnect ();
if(m_state == READY) {
LogPrint (eLogInfo,"--- SOCKS New I2PTunnel connection");
auto connection = std::make_shared<i2p::client::I2PTunnelConnection>((i2p::client::I2PTunnel *)m_parent, m_sock, m_stream);
m_parent->AddConnection (connection);
connection->I2PConnect ();
} else {
AsyncSockRead();
}
}
else
{
LogPrint (eLogError,"--- SOCKS Closing socket after sending success because: ", ecode.message ());
LogPrint (eLogError,"--- SOCKS Closing socket after sending reply because: ", ecode.message ());
Terminate();
}
}
void SOCKS4AHandler::HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream)
void SOCKSHandler::HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream)
{
if (stream)
{
if (stream) {
m_stream = stream;
ConnectionSuccess();
}
else
{
SocksRequestSuccess();
} else {
m_error = 0x4;
LogPrint (eLogError,"--- SOCKS Issue when creating the stream, check the previous warnings for more info.");
SocksFailed();
SocksRequestFailed();
}
}
void SOCKS4AServer::Start ()
void SOCKSServer::Start ()
{
m_Acceptor.listen ();
Accept ();
}
void SOCKS4AServer::Stop ()
void SOCKSServer::Stop ()
{
m_Acceptor.close();
m_Timer.cancel ();
ClearConnections ();
}
void SOCKS4AServer::Accept ()
void SOCKSServer::Accept ()
{
auto newSocket = new boost::asio::ip::tcp::socket (GetService ());
m_Acceptor.async_accept (*newSocket, std::bind (&SOCKS4AServer::HandleAccept, this,
m_Acceptor.async_accept (*newSocket, std::bind (&SOCKSServer::HandleAccept, this,
std::placeholders::_1, newSocket));
}
void SOCKS4AServer::HandleAccept (const boost::system::error_code& ecode, boost::asio::ip::tcp::socket * socket)
void SOCKSServer::HandleAccept (const boost::system::error_code& ecode, boost::asio::ip::tcp::socket * socket)
{
if (!ecode)
{
LogPrint(eLogDebug,"--- SOCKS accepted");
new SOCKS4AHandler(this, socket);
new SOCKSHandler(this, socket);
Accept();
}
else

87
SOCKS.h
View File

@ -1,8 +1,8 @@
#ifndef SOCKS4A_H__
#define SOCKS4A_H__
#ifndef SOCKS_H__
#define SOCKS_H__
#include <climits>
#include <memory>
#include <vector>
#include <boost/asio.hpp>
#include "Identity.h"
#include "Streaming.h"
@ -14,14 +14,18 @@ namespace proxy
{
const size_t socks_buffer_size = 8192;
const size_t max_socks_hostname_size = 255; // Limit for socks5 and bad idea to traverse
class SOCKS4AServer;
class SOCKS4AHandler {
class SOCKSServer;
class SOCKSHandler {
private:
enum state {
GET_VERSION,
SOCKS4A,
SOCKS5_S1, //Authentication negotiation
SOCKS5_S2, //Authentication
SOCKS5_S3, //Request
READY
};
enum parseState {
@ -34,6 +38,36 @@ namespace proxy
GET4A_IP4,
GET4A_IDENT,
GET4A_HOST,
GET5_AUTHNUM,
GET5_AUTH,
GET5_REQUESTV,
GET5_COMMAND,
GET5_GETRSV,
GET5_GETADDRTYPE,
GET5_IPV4_1,
GET5_IPV4_2,
GET5_IPV4_3,
GET5_IPV4_4,
GET5_IPV6_1,
GET5_IPV6_2,
GET5_IPV6_3,
GET5_IPV6_4,
GET5_IPV6_5,
GET5_IPV6_6,
GET5_IPV6_7,
GET5_IPV6_8,
GET5_IPV6_9,
GET5_IPV6_10,
GET5_IPV6_11,
GET5_IPV6_12,
GET5_IPV6_13,
GET5_IPV6_14,
GET5_IPV6_15,
GET5_IPV6_16,
GET5_HOST_SIZE,
GET5_HOST,
GET5_PORT1,
GET5_PORT2,
DONE
};
@ -41,20 +75,25 @@ namespace proxy
std::size_t HandleData(uint8_t *sock_buff, std::size_t len);
std::size_t HandleVersion(uint8_t *sock_buff);
std::size_t HandleSOCKS4A(uint8_t *sock_buff, std::size_t len);
std::size_t HandleSOCKS5Step1(uint8_t *sock_buff, std::size_t len);
std::size_t HandleSOCKS5Step3(uint8_t *sock_buff, std::size_t len);
void HandleSockRecv(const boost::system::error_code & ecode, std::size_t bytes_transfered);
void Terminate();
void CloseSock();
void CloseStream();
void AsyncSockRead();
void SocksFailed();
void Socks5AuthNegoFailed();
void Socks5ChooseAuth();
void SocksRequestFailed();
void SocksRequestSuccess();
void SentSocksFailed(const boost::system::error_code & ecode);
void SentConnectionSuccess(const boost::system::error_code & ecode);
void ConnectionSuccess();
//HACK: we need to pass the shared_ptr to ensure the buffer will live enough
void SentSocksResponse(const boost::system::error_code & ecode, std::shared_ptr<std::vector<uint8_t>> response);
void HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream);
uint8_t m_sock_buff[socks_buffer_size];
SOCKS4AServer * m_parent;
SOCKSServer * m_parent;
boost::asio::ip::tcp::socket * m_sock;
std::shared_ptr<i2p::stream::Stream> m_stream;
state m_state;
@ -63,23 +102,31 @@ namespace proxy
uint16_t m_port;
uint32_t m_ip;
std::string m_destination;
public:
SOCKS4AHandler(SOCKS4AServer * parent, boost::asio::ip::tcp::socket * sock) :
m_parent(parent), m_sock(sock), m_stream(nullptr), m_state(GET_VERSION)
{ AsyncSockRead(); m_destination.reserve(HOST_NAME_MAX+1); }
uint8_t m_authleft; //Authentication methods left
//TODO: this will probably be more elegant as enums
uint8_t m_authchosen; //Authentication chosen
uint8_t m_addrtype; //Address type chosen
uint8_t m_addrleft; //Address type chosen
uint8_t m_error; //Address type chosen
uint8_t m_socksv; //Address type chosen
bool m_need_more; //Address type chosen
~SOCKS4AHandler() { CloseSock(); CloseStream(); }
public:
SOCKSHandler(SOCKSServer * parent, boost::asio::ip::tcp::socket * sock) :
m_parent(parent), m_sock(sock), m_stream(nullptr), m_state(GET_VERSION),
m_authchosen(0xff), m_addrtype(0x01), m_error(0x01)
{ AsyncSockRead(); m_destination.reserve(max_socks_hostname_size+1); }
~SOCKSHandler() { CloseSock(); CloseStream(); }
};
class SOCKS4AServer: public i2p::client::I2PTunnel
class SOCKSServer: public i2p::client::I2PTunnel
{
public:
SOCKS4AServer(int port) : I2PTunnel(nullptr),
SOCKSServer(int port) : I2PTunnel(nullptr),
m_Acceptor (GetService (), boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port)),
m_Timer (GetService ()) {};
~SOCKS4AServer() { Stop(); }
~SOCKSServer() { Stop(); }
void Start ();
void Stop ();
@ -95,7 +142,7 @@ namespace proxy
boost::asio::deadline_timer m_Timer;
};
typedef SOCKS4AServer SOCKSProxy;
typedef SOCKSServer SOCKSProxy;
}
}

270
UPnP.cpp
View File

@ -1,68 +1,226 @@
#ifdef USE_UPNP
#include <string>
#include <boost/lexical_cast.hpp>
#include <thread>
#include <boost/thread/thread.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include "Log.h"
#include "RouterContext.h"
#include "UPnP.h"
#include "NetDb.h"
#include "util.h"
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/upnpcommands.h>
#include <dlfcn.h>
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
typedef UPNPDev* (*upnp_upnpDiscoverFunc) (int, const char *, const char *, int);
typedef int (*upnp_UPNP_AddPortMappingFunc) (const char *, const char *, const char *, const char *,
const char *, const char *, const char *, const char *);
#else
/* miniupnpc 1.6 */
typedef UPNPDev* (*upnp_upnpDiscoverFunc) (int, const char *, const char *, int, int, int *);
typedef int (*upnp_UPNP_AddPortMappingFunc) (const char *, const char *, const char *, const char *,
const char *, const char *, const char *, const char *, const char *);
#endif
typedef int (*upnp_UPNP_GetValidIGDFunc) (struct UPNPDev *, struct UPNPUrls *, struct IGDdatas *, char *, int);
typedef int (*upnp_UPNP_GetExternalIPAddressFunc) (const char *, const char *, char *);
typedef int (*upnp_UPNP_DeletePortMappingFunc) (const char *, const char *, const char *, const char *, const char *);
typedef void (*upnp_freeUPNPDevlistFunc) (struct UPNPDev *);
typedef void (*upnp_FreeUPNPUrlsFunc) (struct UPNPUrls *);
namespace i2p
{
UPnP::UPnP (): m_Timer (m_Service),
m_Endpoint (boost::asio::ip::udp::v4 (), UPNP_REPLY_PORT),
m_MulticastEndpoint (boost::asio::ip::address::from_string (UPNP_GROUP), UPNP_PORT),
m_Socket (m_Service, m_Endpoint.protocol ())
{
m_Socket.set_option (boost::asio::socket_base::receive_buffer_size (65535));
m_Socket.set_option (boost::asio::socket_base::send_buffer_size (65535));
m_Socket.set_option(boost::asio::ip::udp::socket::reuse_address(true));
}
UPnP::~UPnP ()
{
}
namespace UPnP
{
UPnP upnpc;
void UPnP::Run ()
{
DiscoverRouter ();
m_Service.run ();
}
void UPnP::DiscoverRouter ()
{
m_Timer.expires_from_now (boost::posix_time::seconds(5)); // 5 seconds
m_Timer.async_wait (boost::bind (&UPnP::HandleTimer, this, boost::asio::placeholders::error));
UPnP::UPnP () : m_Thread (nullptr) , m_IsModuleLoaded (false)
{
}
std::string address = UPNP_GROUP;
address += ":" + boost::lexical_cast<std::string>(UPNP_PORT);
std::string request = "M-SEARCH * HTTP/1.1\r\n"
"HOST: " + address + "\r\n"
"ST:" + UPNP_ROUTER + "\r\n"
"MAN:\"ssdp:discover\"\r\n"
"MX:3\r\n"
"\r\n\r\n";
m_Socket.send_to (boost::asio::buffer (request.c_str (), request.length ()), m_MulticastEndpoint);
Receive ();
}
void UPnP::Stop ()
{
if (m_Thread)
{
m_Thread->join ();
delete m_Thread;
m_Thread = nullptr;
}
}
void UPnP::Receive ()
{
m_Socket.async_receive_from (boost::asio::buffer (m_ReceiveBuffer, UPNP_MAX_PACKET_LEN), m_SenderEndpoint,
boost::bind (&UPnP::HandleReceivedFrom, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
void UPnP::HandleReceivedFrom (const boost::system::error_code& ecode, size_t bytes_transferred)
{
LogPrint ("UPnP: ", bytes_transferred, " received from ", m_SenderEndpoint.address ());
std::string str (m_ReceiveBuffer, bytes_transferred);
LogPrint (str);
m_Timer.cancel ();
}
void UPnP::Start()
{
m_Thread = new std::thread (std::bind (&UPnP::Run, this));
}
UPnP::~UPnP ()
{
}
void UPnP::Run ()
{
#ifdef MAC_OSX
m_Module = dlopen ("libminiupnpc.dylib", RTLD_LAZY);
#elif WIN32
m_Module = dlopen ("libminiupnpc.dll", RTLD_LAZY);
#else
m_Module = dlopen ("libminiupnpc.so", RTLD_LAZY);
#endif
if (!m_Module)
{
LogPrint ("no UPnP module available (", dlerror (), ")");
return;
}
else
{
m_IsModuleLoaded = true;
}
for (auto& address : context.GetRouterInfo ().GetAddresses ())
{
if (!address.host.is_v6 ())
{
m_Port = std::to_string (util::config::GetArg ("-port", address.port));
Discover ();
if (address.transportStyle == data::RouterInfo::eTransportSSU )
{
TryPortMapping (I2P_UPNP_UDP);
}
else if (address.transportStyle == data::RouterInfo::eTransportNTCP )
{
TryPortMapping (I2P_UPNP_TCP);
}
}
}
}
void UPnP::Discover ()
{
const char *error;
upnp_upnpDiscoverFunc upnpDiscoverFunc = (upnp_upnpDiscoverFunc) dlsym (m_Module, "upnpDiscover");
// reinterpret_cast<upnp_upnpDiscoverFunc> (dlsym(...));
if ( (error = dlerror ()))
{
LogPrint ("Error loading UPNP library. This often happens if there is version mismatch!");
return;
}
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
m_Devlist = upnpDiscoverFunc (2000, m_MulticastIf, m_Minissdpdpath, 0);
#else
/* miniupnpc 1.6 */
int nerror = 0;
m_Devlist = upnpDiscoverFunc (2000, m_MulticastIf, m_Minissdpdpath, 0, 0, &nerror);
#endif
int r;
upnp_UPNP_GetValidIGDFunc UPNP_GetValidIGDFunc = (upnp_UPNP_GetValidIGDFunc) dlsym (m_Module, "UPNP_GetValidIGD");
r = (*UPNP_GetValidIGDFunc) (m_Devlist, &m_upnpUrls, &m_upnpData, m_NetworkAddr, sizeof (m_NetworkAddr));
if (r == 1)
{
upnp_UPNP_GetExternalIPAddressFunc UPNP_GetExternalIPAddressFunc = (upnp_UPNP_GetExternalIPAddressFunc) dlsym (m_Module, "UPNP_GetExternalIPAddress");
r = UPNP_GetExternalIPAddressFunc (m_upnpUrls.controlURL, m_upnpData.first.servicetype, m_externalIPAddress);
if(r != UPNPCOMMAND_SUCCESS)
{
LogPrint ("UPnP: UPNP_GetExternalIPAddress () returned ", r);
return;
}
else
{
if (m_externalIPAddress[0])
{
LogPrint ("UPnP: ExternalIPAddress = ", m_externalIPAddress);
i2p::context.UpdateAddress (boost::asio::ip::address::from_string (m_externalIPAddress));
return;
}
else
{
LogPrint ("UPnP: GetExternalIPAddress failed.");
return;
}
}
}
}
void UPnP::TryPortMapping (int type)
{
std::string strType;
switch (type)
{
case I2P_UPNP_TCP:
strType = "TCP";
break;
case I2P_UPNP_UDP:
default:
strType = "UDP";
}
int r;
std::string strDesc = "I2Pd";
try {
for (;;) {
upnp_UPNP_AddPortMappingFunc UPNP_AddPortMappingFunc = (upnp_UPNP_AddPortMappingFunc) dlsym(m_Module, "UPNP_AddPortMapping");
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
r = UPNP_AddPortMappingFunc (m_upnpUrls.controlURL, m_upnpData.first.servicetype, m_Port.c_str (), m_Port.c_str (), m_NetworkAddr, strDesc.c_str (), strType.c_str (), 0);
#else
/* miniupnpc 1.6 */
r = UPNP_AddPortMappingFunc (m_upnpUrls.controlURL, m_upnpData.first.servicetype, m_Port.c_str (), m_Port.c_str (), m_NetworkAddr, strDesc.c_str (), strType.c_str (), 0, "0");
#endif
if (r!=UPNPCOMMAND_SUCCESS)
{
LogPrint ("AddPortMapping (", m_Port.c_str () ,", ", m_Port.c_str () ,", ", m_NetworkAddr, ") failed with code ", r);
return;
}
else
{
LogPrint ("UPnP Port Mapping successful. (", m_NetworkAddr ,":", m_Port.c_str(), " type ", strType.c_str () ," -> ", m_externalIPAddress ,":", m_Port.c_str() ,")");
return;
}
sleep(20*60);
}
}
catch (boost::thread_interrupted)
{
CloseMapping(type);
Close();
throw;
}
}
void UPnP::CloseMapping (int type)
{
std::string strType;
switch (type)
{
case I2P_UPNP_TCP:
strType = "TCP";
break;
case I2P_UPNP_UDP:
default:
strType = "UDP";
}
int r = 0;
upnp_UPNP_DeletePortMappingFunc UPNP_DeletePortMappingFunc = (upnp_UPNP_DeletePortMappingFunc) dlsym (m_Module, "UPNP_DeletePortMapping");
r = UPNP_DeletePortMappingFunc (m_upnpUrls.controlURL, m_upnpData.first.servicetype, m_Port.c_str (), strType.c_str (), 0);
LogPrint ("UPNP_DeletePortMapping() returned : ", r, "\n");
}
void UPnP::Close ()
{
upnp_freeUPNPDevlistFunc freeUPNPDevlistFunc = (upnp_freeUPNPDevlistFunc) dlsym (m_Module, "freeUPNPDevlist");
freeUPNPDevlistFunc (m_Devlist);
m_Devlist = 0;
upnp_FreeUPNPUrlsFunc FreeUPNPUrlsFunc = (upnp_FreeUPNPUrlsFunc) dlsym (m_Module, "FreeUPNPUrlsFunc");
FreeUPNPUrlsFunc (&m_upnpUrls);
dlclose (m_Module);
}
void UPnP::HandleTimer (const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
{
LogPrint ("UPnP: timeout expired");
m_Service.stop ();
}
}
}
}
#endif

72
UPnP.h
View File

@ -1,41 +1,61 @@
#ifndef UPNP_H__
#define UPNP_H__
#ifndef __UPNP_H__
#define __UPNP_H__
#ifdef USE_UPNP
#include <string>
#include <thread>
#include <miniupnpc/miniwget.h>
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/upnpcommands.h>
#include <miniupnpc/upnperrors.h>
#include <boost/asio.hpp>
#include "util.h"
#define I2P_UPNP_TCP 1
#define I2P_UPNP_UDP 2
namespace i2p
{
const int UPNP_MAX_PACKET_LEN = 1500;
const char UPNP_GROUP[] = "239.255.255.250";
const int UPNP_PORT = 1900;
const int UPNP_REPLY_PORT = 1901;
const char UPNP_ROUTER[] = "urn:schemas-upnp-org:device:InternetGatewayDevice:1";
namespace UPnP
{
class UPnP
{
public:
public:
UPnP ();
~UPnP ();
UPnP ();
~UPnP ();
void Close ();
void Run ();
void Start ();
void Stop ();
private:
void Discover ();
void TryPortMapping (int type);
void CloseMapping (int type);
private:
void Run ();
void DiscoverRouter ();
void Receive ();
void HandleReceivedFrom (const boost::system::error_code& ecode, size_t bytes_transferred);
void HandleTimer (const boost::system::error_code& ecode);
private:
std::thread * m_Thread;
struct UPNPUrls m_upnpUrls;
struct IGDdatas m_upnpData;
boost::asio::io_service m_Service;
boost::asio::deadline_timer m_Timer;
boost::asio::ip::udp::endpoint m_Endpoint, m_MulticastEndpoint, m_SenderEndpoint;
boost::asio::ip::udp::socket m_Socket;
char m_ReceiveBuffer[UPNP_MAX_PACKET_LEN];
};
// For miniupnpc
char * m_MulticastIf = 0;
char * m_Minissdpdpath = 0;
struct UPNPDev * m_Devlist = 0;
char m_NetworkAddr[64];
char m_externalIPAddress[40];
bool m_IsModuleLoaded;
std::string m_Port = std::to_string (util::config::GetArg ("-port", 17070));
void *m_Module;
};
extern UPnP upnpc;
}
}
#endif
#endif